0

I have some problem with variables. I wrote this function and it doesn't work. Why? mydata = null. How get data from post function?

function getData(input) {
    var mydata = null;        
    $.post('getdata.php', {
            input: input
        },
        function(data) {  
            mydata = data;
        }, 'json'
    );   
    return mydata; 
}

1 Answers1

0

That will not work because the ajax request is (as its name implies) asynchronous, so the return happens before the callback is executed. You need to return a promise and do the logic you want with the data once it is resolved:

getData(input).then(function(data) {
 // do your stuff with the data
});

And to promisify your function:

function getData(input) {
    return new Promise(function(resolve, reject) {
        $.post('getdata.php', {
            input: input
        },
        function(data) {  
           resolve(data);
        }, 'json'
    );   
    });
}
A. Llorente
  • 1,142
  • 6
  • 16
  • Oh, thanks for all. I found answer: "If you use jQuery, you can set the async option to false. If you use any other jQuery Ajax method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax)." – Geralt Riwia May 23 '18 at 14:22