1

I have a function which will return a JSON back. When checking the returned data in the calling function it was found to be undefined.

Only thing I can think of is ajax is async and it didn't wait for the data to be returned. Cuz that could be the only reason why the second alert box got triggered before the first alert.

$.get( '/search/s/g/' , { 'q' : query } , function(data) {
    var result = $.parseJSON(data);
    if ( result.length < 10 ) { 
        data2 = extendSearch(query);
        alert("second"); // This got triggered first.
    }
    populateSearchResult(result);
});

function extendSearch(q) {
    $.get('/search/s/f/', { 'q': q }, function(data) { 
         alert("first"); // This got triggered as the second alert box
         return data;
    });
}

Now how do i solve this?

Praveen
  • 2,400
  • 3
  • 23
  • 30
  • 1
    ***Do not*** use `data2` outside of the `$.get` complete callback. the same goes for `data` in `extendSearch` – Kevin B Nov 06 '13 at 18:05
  • 2
    The **A** in Ajax. *sigh* – Dave Newton Nov 06 '13 at 18:05
  • `data2 = extendSearch(query);` - `extendSearch` function will return you `null` as it is an asynchronous call. Read this post http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call for more information. – Selvakumar Arumugam Nov 06 '13 at 18:07
  • @Praveen [Ajax is also acceptable.](http://en.wikipedia.org/wiki/Ajax_(programming)). The point is you've completely neglected the fact that there's that **A** at the beginning. – Dave Newton Nov 06 '13 at 18:08
  • @DaveNewton Anyways thats not the issue here... just let it go man... – Praveen Nov 06 '13 at 18:09
  • 2
    @Praveen that actually is the issue. You're writing your code as if ajax were synchronous, but it's actually **A** synchronous. that's the point Dave is making. – Kevin B Nov 06 '13 at 18:11
  • @KevinB I knew that, and I have mentioned it in my post, just wanted a solution to it. – Praveen Nov 06 '13 at 18:13
  • The solution is to re-think how you write your code... Use callbacks. There's at least a half dozen different ways you could write/organize your code to work asynchronously. – Kevin B Nov 06 '13 at 18:13
  • 1
    http://jsfiddle.net/NLMvx/ – adeneo Nov 06 '13 at 18:18
  • thanks adeneo, i was looking for something like that – Praveen Nov 06 '13 at 18:22

1 Answers1

1

Don't return data, In expandSearch do what you need to do inside the success callback.

function expandSearch(q) {
    $.get('/search/s/f/', { 'q': q }, function(data) { 
         alert("first"); // This got triggered as the second alert box
         // do something with the data here
         // modify dom or w/e
    });
}
dm03514
  • 54,664
  • 18
  • 108
  • 145