charlie
charlie

Reputation: 510

Variable lost in ajax request

I'm facing a strange behaviour when trying to pass a variable as parameter to a nested ajax request callback:

$('form').on('submit',function(e){
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    })
    e.preventDefault(e);
    $.ajax({
        type:"POST",
        url:dest_url,
        data:$(this).serialize(),
        dataType: 'json',
        success: function(data){
            if($.isEmptyObject(data.error)){
                // performing some actions
                // at this point, data.id contains my id

                // We call an other function, 
                // which performs an other ajax request, 
                // with data.id as parameter

                listRefresh(data.id);

            }else{
                // error message
            }
        },
        error: function(data){
            // error message
        }
    })
});


function listRefresh(id){
    console.log(id); // At this point, id contains my id
    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    })
    var src_url = location.href + '?id='+id;
    $.ajax({
        url: location.href,
        type: 'GET',
        cache: false
    })
    .done(function(id) {
        console.log(id); 

        // At this point the console outputs 
        // all my html code in place of id

        // I tried to pass data, response, id, but still the same issue
    })
    .fail(function() {
        //error message
    });
}

As said in code comments above, in the listRefresh ajax done callback, my variable seems to disapear and the console.log outputs my entire html code in the console... I've never seen something like this. Do you have an explanation of why, and how could I pass my id as parameter to the ajax callback ?

Upvotes: 2

Views: 1097

Answers (2)

David
David

Reputation: 219117

The first argument passed to the function in done is the response from the AJAX request. It doesn't matter what you call the variable, that's what will be passed to that function.

You can capture the value in the closure however, simply give it another name and assign it to a local variable. Something like this:

done(function(response) {
    var theId = id;

    // "response" contains the response from the server.
    // "theId" contains the value of `id` from outside this function.
})

Upvotes: 3

Enrico Agrusti
Enrico Agrusti

Reputation: 514

The parameter of the .done() method is the response of the AJAX call. If your call returned a HTML page, the id variable got all of the html string assigned to it.

To keep the id in its variable simply use another one like:

.done(function(data) {
  console.log(data)
  console.log(id); 
});

Upvotes: 2

Related Questions