0

I have looking for the solution with my case. In other question variable from ajax success will execute like this:

$.ajax({
...,
success: function(data) {
    myFunction(data);
});

myFunction(data){
    // process the data here ..
}

But in my case I call another ajax(2) with ajax(1). And really need that variable from ajax(2) to ajax(1) for process. My code look like this:

$("#formVerify").submit(function(event) {
    $.ajax({
        ....
        success: function(data){
            var result= call_id(data.id);
            console.log(result);
        }
    });
});

function call_id(data) {
    var output = null;
    $.ajax({
        ....
        success: function(result){
            output = result;
        }
    });
    return output;
}

the result will always null because I set output to, or sometimes it is undefined if I don't set the value to null. I tried async: false but in my machine it wouldn't work. Need help thank you

1 Answer 1

1

Remember Ajax call doesn't return result, you can't use return statement in ajax call. You can get the result only using callback/promises.

Change you first ajax call to pass the callback instead of trying to get the return value:

 $("#formVerify").submit(function(event) {
    $.ajax({
        ....
        success: function(data){
            call_id(data.id, function(result){
                console.log(result);
            });
            
        }
    });
});

and change your second ajax call_id function to take callback as parameter like this:

function call_id(data, callback) {
    $.ajax({
        ....
        success: callback
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

I got error callback is not defined right in callback(result)
your call_id should have callback as second parameter, you could also use it as updated one.

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.