tags:

views:

29

answers:

1

In an attempt to make my jQuery code modular, i.e. reusable, I've placed an ajax() function inside of another function fetch_ajax(). I'm trying to call fetch_ajax() with parameters from other places, which should simply run the contained ajax() and return the response.

But that's not happening - instead, fetch_ajax() apparently returns false too quickly to the caller and doesn't wait until ajax() has completed the request and gotten a response.

Here's the code:

The fetch_ajax() function

function fetch_ajax(url) {
  $.ajax({
    type: 'GET', 
    url: url,
    success: function(response) {
      return response;
    }
  });
}

The calling function:

function caller() {
  response = fetch_ajax('script.php');
  alert(response); //this is always 'undefined'
}

In fetch_ajax(), I've tried not directly returning response from within ajax(), but writing it to a variable, and returning that variable after ajax() - that didn't work either (same result).

When I place a 2nd alert right before return response; inside of the ajax() function, I'm seeing that one fire AFTER the one inside caller(). So I'm thinking that somehow, fetch_ajax() doesn't wait for the contained function to execute before it returns false.

What am I doing wrong?

Thank you.

+1  A: 

Your train of thought is wrong - the .ajax() function is written to not wait for the contained function. success is an event listener, so it is fired dynamically whenever the response arrives. You could use synchronous requests or jQuery queues to solve this, but both have disadvantages.

See http://stackoverflow.com/questions/755885/how-do-i-make-jquery-wait-for-an-ajax-call-to-finish-before-it-returns for the synchronous request solution. It's much simpler than the other one, but will hang your browser if the server dies right then or a hyperactive firewall blocks the answer or an angry lolcat eats your request on the way.

MvanGeest
Thanks for this, it's the explanation I needed. I think the best way for me right now would be to rewrite `fetch_ajax()` to something like `output_ajax()`, if you catch my drift. With a handful more params passed to this new function, it should also be capable of accounting for teh lolcats :) Thanks.
bobsoap