views:

388

answers:

2

I have a form being AJAX'd in by jQuery on a page with multiple forms. I'm performing the following function, which is a wrapper for the $.ajax function:

function do_json_get(uri){
    var ret = '';
    var url = AJAX_URL + uri;

    $.ajax({
        type: 'GET',
        url: url,
        async: false,
        success: function(data) {
            ret = data.html;
        },
        dataType: 'json'
    });

    return ret;
}

When I go to the AJAX server directly (which is rendering the form in PHP), I get the raw JSON response - so I know the server is outputting to the browser, and the AJAX server is doing other things like setting the proper cookies, so I know that the connection is good (I get a 200 response code). Yet the data object is coming back null.

What else could I be missing?

A: 

Oh boy. This question again.

AJAX: Asynchronous JavaScript And XML*. Asynchronous. Asynchronous. Asynchronous.

Your function, do_json_get() returns ret before the success handler function in the AJAX call executes. The order of operation is not proceeding, here, from top to bottom. In other words, you just can't do it that way.

Because of its asynchronous nature, AJAX operates on callbacks, not return values. You need to change your paradigm. The success handler function needs to do whatever is required with data.html itself, or pass it off to another function.

* Yes, I know the XML part of the original acronym is largely vestigial these days

Peter Bailey
This would be a great answer if I didn't specify async: false in the $.ajax call to avoid just such a race condition.
b. e. hollenbeck
-1, because he made it blocking.
Mef
@b. e. hollenbeck, just because you can set `async` to `false` doesn't mean you should've in this case. Handle the JSON within the callback or employ a delegate method.
macek
@Peter Bailey, just because you're frustrated that this is a common misconception doesn't mean you should take your anger out on the OP.
macek
And just for the sake of completeness, I put the $.ajax inline with the rest of the function and I still have the same problem.
b. e. hollenbeck
@macek don't assume I'm angry. I'm not. Anger would involve CAPS and lots of exclamations points and perhaps some expletives. Clearly I misunderstood the problem but that doesn't mean I'm *angry* about it.
Peter Bailey
+3  A: 

Here's a guess. If you're serving the page from the file system, Firefox (and I think Chrome) will see it as originating from a different domain. You'll get the 200 response, but no data.

Try Safari, or maybe give jsonp a shot in place of json.

EDIT:

Since you're getting the data from a different domain, it won't work. I think it is not allowed by the XMLHTTPRequest.

patrick dw
I didn't realize jsonp was necessary outside of the domain. Thank you!
b. e. hollenbeck