0

I'm using jQuery $.getJSON(..) to get some json.

The passed value shows me "undefined".

Is there a way to do that?

getTopMenuJson : function(currentPage) {
    if(currentPage == null) currentPage = 1;

    var retJSON;

    $.getJSON(
            requestURLs.topMenuJson, 
            {
                'ITEM_PER_PAGE' : TopMenuHandler.ITEM_PER_PAGE,
                'CURRENT_PAGE' : currentPage
            },
            function(JSON) {
                //alert(JSON); **<--This gives me result (Object)**
                retJSON = JSON;
            }
    );

    **alert(retJSON); //<!-- This doesn't, but Undefined**
},

1 Answer 1

1

It doesn't and it shouldn't as getJSON is internally doing an AJAX call, the first A in AJAX stands for Asynchronous, it simply means that the script execution won't wait until your success function is called.

You could instead use $.ajax and pass in async: false to one of its options to make sure that your script waits for the ajax call to be finished, but be aware that doing that would freeze the browser / tab until your AJAX call is finished.

$.ajax({
  url: requestURLs.topMenuJson,
  dataType: 'json',
  data:  
  {
     'ITEM_PER_PAGE' : TopMenuHandler.ITEM_PER_PAGE,
     'CURRENT_PAGE' : currentPage
  },
  success: function(JSON) {
     //alert(JSON); **<--This gives me result (Object)**
     // this won't work without async:false
     // as the execution of script won't wait until this function 
     // is finished
     retJSON = JSON; 
  },
  async: false
});

http://api.jquery.com/jQuery.ajax/

async Default: true By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm.. I think that the issue is when trying to assign the value to retJSON. Instead of doing it, he's re-declaring the retJSON var.
@lu1s even if he does retJSON = JSON in that callback, that won't work as well :), but ya, you have a point, I'll edit my code snippet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.