I have the next function. My PHP script returns an array with element error
with value 'ERR':
var updatePaymentType = function(plan_pt_id, pt_id){
var error = null;
var data = new Object()
data["function"] = "update";
data["payment_type_id"] = pt_id;
data["plan_payment_type_id"] = plan_pt_id;
data["data"] = $("#saveform").serializeArray();
$.ajax({
type: "POST",
url: "<?=ROOT_PATH?>/commission/plan/edit/id/<?=$this->editId?>",
data: data,
dataType: "json",
success : function (data)
{
error = data['error'];
alert(error); // All works. Output ERR
}
});
alert(error); // Not work. Output null
return error;
};
My function should returns an error. But it returns null
. Thank you very much.
AJAX requests are asynchronous, meaning the value isn't set until after you already returned (the success
handler runs later , when the server responds with data).
To return the error type you have to make it synchronous with async: false
like this:
$.ajax({
async: false,
type: "POST",
...
But this locks up the browser, it's better to call whatever uses the value from your success
callback, like this:
success : function (data)
{
var error = data['error'];
functionThatTakesError(error);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.