jQuery variable scope issue in function containing ajax() [duplicate]
jQuery variable scope issue in function containing ajax() [duplicate]
This question already has an answer here:
As we know if we call a function multiple times, the variables don't conflict with each other as they have different scope, for ex. new_var
is different in both invocations of a function any_function
new_var
any_function
function any_function(argument1)
new_var = argument1;
alert(new_var);
any_function("hello i am first");
any_function("hello i am second");
But I have a function which does an ajax call, when I call this function multiple times, the variable new_var
, gets modified according to the last call (invocation) and I always get the same value for all the invocations of the function do_ajax()
new_var
do_ajax()
function do_ajax(argument1)
// var new_var = argument1;
new_var = argument1;
$.ajax(
url : window.location.href,
success: function(r)
alert(new_var);
);
do_ajax("first ajax done");
do_ajax("second ajax done");
You can see the results here https://codepen.io/nikhilnagpal123/pen/XPrvxa
And another interesting thing is if I put var
before the variable new_var
then I get the expected results
var
new_var
https://codepen.io/nikhilnagpal123/pen/oPNvXJ
from this, I can guess that somehow the variable gets modified, but how can another invocation of that function modify that variable, but there shouldn't be the conflict, they should have different scope,
Could someone explain it pls?
Sorry, Above Question is kind of stupid one, Basically, when we declare a variable inside a function without var
we give that function a global scope and that variable can be accessed globally
var
for ex.
function any_function(argument1)
new_var = "hello";
any_function("hello");
alert(new_var); //global variable, also can be accessed by window.new_var
But if I use var
when declaring the variable, it will have a local scope only
var
function any_function(argument1)
var new_var = "hello";
any_function("hello");
alert(new_var); // can not be accessed globaly `new_var` scope was only limited to function `any_function` where it was decalred
So in the above question, the last ajax call modifies the global variable when I don't use var
while declaring them,
var
I had this wrong conception in my mind that when we don't declare a variable outside the function, it would always have a local scope inside the function where we declare it doesn't matter whether we use var
or not, that created the whole misunderstanding,
var
Thanks to the users @Alex and @mplungjan for making things clear for me.
Thanks!
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Aug 20 at 23:06
Possible duplicate of How do I return the response from an asynchronous call?
– mplungjan
Aug 20 at 10:01