Skip to content Skip to sidebar Skip to footer

Access Javascript Variable Inside Ajax Success

var flag = false; //True if checkbox is checked $.ajax({ ... //type, url, beforeSend, I'm not able to access flag here success: function(){ // I'm not able to acces

Solution 1:

You have access to the variable if you make it by reference. All objects in Javascript are referenced values, just the primitive values aren't (such as: int, string, bool, etc...)

So you can either declare your flag as an object:

var flag = {}; //use object to endure references.

$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(){
        console.log(flag) //you should have access
    }
});

Or force the success function to have the parameters you want:

var flag = true; //True if checkbox is checked

$.ajax({
    ... //type, url, beforeSend, I'm not able to access flag here
    success: function(flag){
        console.log(flag) //you should have access
    }.bind(this, flag) // Bind set first the function scope, and then the parameters. So success function will set to it's parameter array, `flag`
});

Solution 2:

Here is one way. The beforeSend callback option gives you access to both the jqXHR object and the ajax settings object.

You won't be able to use caturl in the append of error, as it will not be in synch with the request throwing error.

 $.ajax({
    /* url, data ...& other opts*/
    beforeSend:function( jqXHR, settings){
        /* add url property and get value from settings (or from caturl)*/
         jqXHR.url= settings.url;
   },
   /* error to be deprecated in jQuery 1.8 , superseded by "fail" */
   error: function(jqXHR, , textStatus, error){
       var url=jqXHR.url;
     /* replace caturl with url in your append */ 
     $('#showdata').prepend("ERROR : '" + error + "' trying to access: " + url + "</br>");
   }

Post a Comment for "Access Javascript Variable Inside Ajax Success"