How do I return the response from an asynchronous call? Did not helped me and will probably confuse a lot on googlers because its state what is working as not working. witch is; the_data_you_want = response and this is actually the answer.
I am working on a project that uses Ajax, Jquery, Promise, and PHP.
I fill an array with a function.
var data = validateInput2(field_id, data_type, value).then(function (response) {
console.log("Succès !", response); <-----------------------------
data = response; Scope where data is filled
alert('R : '+data); <-----------------------------
}, function (error) {
console.error("Échec !", error);
});
alert('DATA : '+data); <---------------------------
if (data[0] == 'true') { Outside the scope where data
$(container[1]).addClass("pass_f"); is a pending promise object
$(container[1]).html(data[2]);
$(container[0]).html(data[1]);
}
else {
$(container[1]).removeClass("pass_f");
$(container[1]).addClass("err_f");
$(container[1]).html(data[2]);
$(container[0]).html(data[1]);
}
Now if you take a look at the alert statement, The first one alert('R : '+data);
is showing me what i am suppose to see. an array sent back from PHP.
I can see the same good values in the console because of console.log("Succès !", response);
but when i keep going and get to the part where the page should get updated. Witch is the alert('DATA : '+data);
The data is no longer what it was. Instead I get [object Object]
in the alert box. And in the console I get
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
It seems like the array contained in result is only there inside;
{
console.log("Succès !", response);
data = response;
alert('R : '+data);
}
So I know that my Promise is working because my page is waiting for the object with the status pending and that I no longer have the data undefined error.