0

I want to return a ajax call value to other function. Code shown below

script

var obj2 = ajax_call();
    function ajax_call() {
    var obj3;   
    $.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){
        obj3 = $.parseJSON(data);
    });
    return(obj3);
    }
    console.log(obj2+'test'); 
Rijo
  • 2,963
  • 5
  • 35
  • 62

2 Answers2

0
    function ajax_call() {
    return $.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){            
        return data;
    });

    }

    var obj2 = ajax_call();
    console.log(obj2+'test'); 
Sami
  • 8,168
  • 9
  • 66
  • 99
0

AJAX returns result in future (that's why it is asynchronous). Since JavaScript runs in a single thread, you cannot return a value immediately.

You need to understand jQuery's Promise API instead, which $.post already supports.

Modify your code a bit to leverage the power of promises in your code.

function ajax_call() {
  return $.post("action.php", {action: 'view_style_code_action',style_val: v})
}

ajax_call()
  .then(function(data) {
    // Do the parsing here
    var obj3 = $.parseJSON(data);

    // Do rest of your work here.
    ...
  });
31piy
  • 23,323
  • 6
  • 47
  • 67