Access javascript variable inside ajax success

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

Inside ajax, if I try to access it flag, it says that it is not defined. How to use it inside ajax function?

Any idea?

Both flags and ajax are function bodies. There is nothing else inside this function.

+4
source share
2 answers

You have access to the variable if you make it by reference. All objects in Javascript are reference values, only eigenvalues ​​are not (e.g. int, string, bool, etc.)

This way you can declare your flag as an object:

    var flag = {}; //use object to endure references.
    $.ajax(
        ... //type,url,beforeSend, I cannot able to access flag here
        success: function()
        {
          console.log(flag) //you should have access
        }
    )

Or make the success function have the necessary parameters:

var flag = true; //True if checkbox is checked
    $.ajax(
        ... //type,url,beforeSend, I cannot 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 parameter array, `flag`
    )
+2
source

. beforeSend jqXHR ajax.

caturl , .

 $.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>");
   }
0

All Articles