Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 35231  / 11 Years ago, sun, june 30, 2013, 12:00:00

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.


More From » jquery

 Answers
9

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);

[#77294] Friday, June 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiley

Total Points: 733
Total Questions: 118
Total Answers: 94

Location: Liechtenstein
Member since Wed, Dec 8, 2021
2 Years ago
;