0

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.

1 Answer 1

1

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 your GetUniversity() function yields no return value, you could use.

To solve this, you got 2 options:

  1. (worse) Use $.ajax instead and set async: false in 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!
  2. (better) Pass all the dependent functionality into the callback of $.getJSON. It will be executed, when the request has finished and the rest of your code/page will work just fine in the meantime.

 

function GetUniversity()
{       
    $.getJSON(AddressAccess+"Home/university/format/json",
        function(data) 
        { 
            var UniveristyData = data[0];
            alert(UniveristyData.Name);
            var out = '';
            for(i in UniveristyData) {
              out+= i + ' ' + UniveristyData[i] + "\n";
            }
            alert(out);
        }); 
}

$(document).on('pagebeforeshow','#searchpage', GetUniversity );
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.