views:

39

answers:

1

I have a function like this that does an ajax call to grab some data from a database.

    function db (content) {
        $.post('/ajax/db.php', { 
           operation:operation,
           content:content
        }, function(data)
        {
            console.log(data);
            return data;
        });
    }

console.log(data); gives me the data that I want.

However how do I pass data to function db so that I can do something like:

var returnedData = db ('content');

Thanks!

+4  A: 

AJAX Operations are asynchronous so returning it directly isn't an option, not unless you make it synchronous (which locks up the browser). Instead, you should pass the data onto the next function in the callback, like this:

function db (content) {
    $.post('/ajax/db.php', { 
       operation:operation,
       content:content
    }, function(data)
    {   
        nextFunction(data);
    });
}

Or make it take a callback so you can pass the function that will get the data, when it's ready, like this:

function db (content, callback) {
    $.post('/ajax/db.php', { 
       operation:operation,
       content:content
    }, callback);
}

Then call it providing the callback function, for example:

db('content', function(data) { 
  //do something with data
});
Nick Craver
Just to be aware of my options, how do I make it synchronous?
Mark
@Mark - You would use the full `$.ajax()` version (like in the `$.post()` documentation: http://api.jquery.com/jQuery.post/) with the `async: false,` option added....but if at all possible, avoid doing that :)
Nick Craver
Great explanations, thanks.
Mark