I'm making a project that includes web api and JQuery. One of the html pages has to show store and the manager's name of the store.
Every store has:
ID,
StoreName,
ManagerID.
Every Manager has:
ID,
ManagerName.
The store isn't hold the manager name directly.
The code looks like this:
// There is a html code with <table id='table'>...</table> before the script.
var storesUri = 'api/stores' //The stores uri
$(document).ready(function() {
$.getJSON(storesUri)
.done(function(data) {
$.each(data, function(key, item) {
$('#table).append(
'<tr>' +
'<td>' + item.ID + '</td>' +
'<td>' + item.storeName + '</td>' +
'<td>' + findManagerNameByID(item.ManagerID) + '</td>' + //get the manager name by the manager id
'</tr>');
});
});
});
var managersUri = 'api/managers' //The managers uri
function findManagerNameByID(id) {
var res = 'N/A';
$getJSON(managersUri + '/' + id)
.done(function(data) {
res = data.ManagerName; //puts in res the fit manager name
})
.fail(function(jqXHR, testStatus, err) {
res = 'None';
});
//alert('1');
return res;
}
After this code the table has to include for each store the store ID, store name and the store manager name. Instead of that the table includes for each store the store ID, the store name and 'N/A' (the default value of res).
The thing is that, if I add to the code "alert('1');" right before the return (You can see it in commant) the table will be okay and it'll include for each store the store ID, store name and the store manager as I wanted.
I think this is happen becase the 'return res;' line somehow happens before the 'res=data.ManagerName;' line (I think that because when the code has the little delay of the alert before the return, everything is okay). How can I make the table be filled correctly without the alert? thanks.