Skip to content

Unable to set a variable with an AJAX call

An answer to this question on Stack Overflow.

Question

I have a call to ajax which seems to execute properly, but I can't set a breakpoint in the success section of the call. The underlying database is changed and I want to return a value of the number of items that have been changed in 'tppunk'. In debugging with Firebug, the debugger doesn't stop in 'success' even though it does succeed. Instead, I jump to the code after the call and 'tppunk' is identified as undefined. Here's my code:

var json = {'tagset': tagset}
var tppunk;
$.ajax({
    url: clr_url_base+'savetags.php?data='+encodeURIComponent($.toJSON(json)),
    type: 'GET',
    success: function (d) {
        tppunk = d;
        $('h2').removeClass("changed");
        $('h2').addClass("saved");
    },
    complete: function () {
        $('h2').removeClass("changed");
        $('h2').addClass("saved");
    }
});
if(corp == "CPA")
    window.opener.$('span.tppunk').text(tppunk);

Answer

The AJAX call is asynchronous, so your code hits

$.ajax ...

and sends a request to the server.

It then merrily continues on its way and hits

if(corp=="CPA") ...

At some later point in time, the server responds and your success function is called. This probably occurs well after your if(corp block.

What you'll want to do is put the if(corp block inside your success call somehow.