4

I've got a Javascript function called getCartProducts() which gets a JSON array via AJAX using $.post() which returns a value. I want to let my function return that value, but I don't know how to do that.

Here's my function:

function getCartProduct(id){
  $.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
    var result = data;
  });
  return result;
}

I know that this wont work, because te variable result is only active in the $.post() function, but I don't know how to get it straight.

jacoz
  • 3,508
  • 5
  • 26
  • 42
Daniel Gelling
  • 892
  • 1
  • 9
  • 22

1 Answers1

14

Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):

function returnData(param) {
    console.log(param);
}

Now add that callback function as a parameter to your AJAX function, and lets run it:

function getCartProduct(id, callback){
    $.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
        callback(data);
    });
}

getCartProduct(id, returnData);
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 2
    please read the duplicate question, and then use the "deferred" object method from its accepted answer. It's far more powerful than passing callbacks around. The "modern" way is to `return $.post(...)` and then the caller can process the resulting promise with `getCartProduct(myId).done(function(data) { ... })` – Alnitak Jun 30 '13 at 20:21
  • If you do decide to use a callback, consider using the line... `if (typeof callback != "undefined") { callback(data); }` This way you have the option to send a callback or not. – DanimalReks Mar 12 '21 at 21:09