I have the following Javascript function:
function GetUniversity()
{
$.getJSON(AddressAccess+"Home/university/format/json",
function(data)
{
data = data[0];
return data;
});
}
Now I when I test the data in the function the data var definitely has data returned from the url. Now here is my code for where I call this function:
$(document).on('pagebeforeshow','#searchpage',
function()
{
var UniveristyDat = null;
UniveristyData = GetUniversity();
alert(UniveristyData.Name);
var out = '';
for(i in UniveristyData)
{
out+= i + ' ' + UniveristyData[i] + "\n";
}
alert(out);
}
);
Now in theory the UniveristyData var should have contense returned to it but for some reason its null. Not to sure what is going on here.
The call to
$.getJSON()is asynchronous. The function you pass it, will be executed, when the request is finished. The rest of the code, however, is evaluated immediately. Thus yourGetUniversity()function yields no return value, you could use.To solve this, you got 2 options:
$.ajaxinstead and setasync: falsein the options. This will hold the execution of the JavaScript until the request has finished. Be careful, however, as this means that your whole page is rendered unusable in the meantime!$.getJSON. It will be executed, when the request has finished and the rest of your code/page will work just fine in the meantime.