views:

145

answers:

2

I've created a wrapper function for jQuery's $.ajax() method so I can pass different dataTypes and post variables - like so:

function doPost(dType, postData, uri){

    $.ajax({
        url: SITE_URL + uri,
        dataType: dType,
        data: postData,
        success: function(data){
          return data;
        });
}

The problem I'm having is getting the data (which is always JSON) back out. I've tried setting a var ret before the $.ajax() function call and setting it as ret = data in the success function. Am I being stupid about this? If I don't set a success function, will the $.ajax simply return the data? Or is it just success: return data? Or does success require a callback function to handle the data, which could just be return data?

A: 

When you call $.ajax() it creates the request and then moves on to the next thing. It doesn't sit around and wait for the return and block the next lines of code. That means that unless the success callback function can't return the value of data for the doPost function.

If you really want to have a wrapper function then you could do something like this:

function doPost(dType, postData, uri, success){
    $.ajax({
        url: SITE_URL + uri,
        dataType: dType,
        data: postData,
        success: success
    });
}

And define your success handler when you call doPost, but the wrapper function really isn't doing much for you at the point.

PetersenDidIt
A: 

Well, you are inside a function - take advantage of variable scope ;-)

function doPost(dType, postData, uri) { 
    var result;
    $.ajax({ 
        url: SITE_URL + uri, 
        dataType: dType, 
        data: postData, 
        async: false,
        success: function(data){ 
          result = data;
        }); 
    return result;
} 

This actually works, but I guess the async part is obligatory then... Otherwise the call of $.ajax would return immediately, and result would still be undefined - you would always get undefined as result of your function call.

However, when you make the $.ajax call synchronous, it blocks until the data is received, and you can return the data as result of your own function.

But you have to be clear that when using this method, no other code will be executed until the ajax load finishes!

Mef
By doing this it means you stop any other code execution till the ajax request returns.
PetersenDidIt
That's the nature of synchronous calls, so what...? Was that a criticism?
Mef
no criticism just a note. you had not added the note to your answer about this yet
PetersenDidIt
OK, added it to the anwser unmistakeably :-)
Mef
The async was the key - another thing to note for anyone coming across this question/answer - you need to (safely) eval the returned data object, since outside of the $.ajax() function, your script doesn't know that the data is JSON. I used the jQuery JSON plugin, personally.
b. e. hollenbeck