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 access flag here
}
});
Inside ajax, if I try to access flag
it says it is not defined. How can I use it inside ajax function?
Any Idea?
Both flag and ajax is body of a function. Nothing else is present inside that function.
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 access flag here
}
});
Inside ajax, if I try to access flag
it says it is not defined. How can I use it inside ajax function?
Any Idea?
Both flag and ajax is body of a function. Nothing else is present inside that function.
Share Improve this question edited Sep 14, 2020 at 8:37 drhelado 336 bronze badges asked Jun 9, 2015 at 14:03 GibbsGibbs 23k14 gold badges83 silver badges145 bronze badges 15 | Show 10 more comments2 Answers
Reset to default 15You 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`
});
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>");
}
success
doesn't magically remove variable from context. Here theflag
variable is even not accessible from ajax option so OP is setting it outside of ajax method scope$ – A. Wolff Commented Jun 9, 2015 at 14:14flag
and the$.ajax
call are at the same scope then flag will be available (and it is). There's some missing code in your question... – fdomn-m Commented Jun 9, 2015 at 14:15