Jquery return value from $.post() in function

  • Added:
  • |
  • In: Wordpress

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.

This Question Has 1 Answeres | Orginal Question | Daniel Gelling

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

function returnData(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){

getCartProduct(id, returnData);

Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns