Consider the following code snippet using JavaScript (with the jQuery library):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function blah() { var pagedata; $.ajax({ type: "GET", url: "test.php", error: function(request, error) { alert("Error: " + error); }, success: function(data) { pagedata = data; } }); return pagedata; } |
Looks reasonable enough. The purpose of the function is to make a GET request to some page (“test.php” in this case), store the result in a temporary variable and return said variable (of type string).
However, it turns out that this doesn’t work too well. When the function is called, chances are pretty good that the returned string is empty. Why? At first I thought it was because of some weird variable scoping rules in JavaScript, but that didn’t really make too much sense.
It turns out that I forgot about the “A” in “AJAX” (i.e. Asynchronous JavaScript and XML). The function above doesn’t execute in a top-bottom manner; the $.ajax() call is made in parallel with the rest of the script. Generally this isn’t too much of a problem (indeed, it’s a valued property by those making web applications) but in this case it isn’t what I want.
Anyway, there’s a simple solution to this. What I want to do is make the call synchronous with the rest of the script. Fortunately, jQuery makes this extremely easy in the $.ajax() method by providing an option (async: false) to turn this off. Thus:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function blah() { var pagedata; $.ajax({ async: false, type: "GET", url: "test.php", error: function(request, error) { alert("Error: " + error); }, success: function(data) { pagedata = data; } }); return pagedata; } |
This locks up the browser while the call is being made so it’s probably not the best solution. It shouldn’t matter too much with small requests though (or requests made with the user’s consent via. the UI or something).
Tags: AJAX, JavaScript, jQuery