1

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.

1 Answer 1

6

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);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

This looks like the problem. To further explain, the "a" in ajax stands for asynchronous, meaning that your code will not wait for the http request to return before continuing execution. In this case, your return statement will be executed long before the ajax request has returned a value, making it impossible for your outer function to return the value from the server. By using a callback, you can avoid this and pass the value to the proper method as soon as it is returned from the server :-)
Thanks. It works pretty. I am using your second variant with handleErrors function.
How would you access that variable error in another function if needed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.