Reputation: 99
I have spent the last 30 mins figuring this out.
Let's assume the following case:
<script>
var x = 0 ; //global variable
function compute() {
x = x+1;
}
</script>
Should the value of x be incremented so I can access it into a function later on?
I have the following codes:
var id1 = 0;
var id2 = 0;
$.ajax({
url: "http://localhost/twee/chat/comment",
type: 'POST',
data: form_data,
success: function(data) {
var data1 = parseInt(data);
id1 = id2 = data1;
}
});
I want to be able to access the values of id1 and id2 (updated since i declared them as 0) in a later function.
However, the value is staying zero and data1 is retrieved just fine.
Upvotes: 0
Views: 474
Reputation: 375992
Your ajax callback is asynchronous. It won't run the success
function until after the remote server responds. Once it does, your function is executed, and the variable is incremented.
This is a difficulty in Javascript programming, and asynchronous programming in general: there are a number of balls in the air at once, and it is difficult to reason about how they might complete their operations, and when you can see the results.
It's very easy to think of the $.ajax() call as "get the results from the server," but it's really, "make a request to the server." Who knows when it might finish?
Upvotes: 0
Reputation: 33865
I dont know when you try to use the ID's, but the ajax call is asynchronus, so if you try to read the variables like this:
var id1 = 0;
var id3 = 0 ;
$.ajax({
url: "http://localhost/twee/chat/comment",
type: 'POST',
data: form_data,
success: function(data) {
var data1 = parseInt(data, 10);
id1 = id2 = data1;
alert(id1) // Will alert whatever number returned as data.
}});
alert(id1) // Will alert 0
The second alert will be called almost simultaneously with the ajax call, and at that point the data has not been updated yet, while the first alert will not be called until the data has returned. If you are going to use the ID's, you will have to use them within your success-callback, or in a function that is called within your success-callback.
Upvotes: 2
Reputation: 156055
Are you sure that you're checking the value of id1
after the success
callback runs? ajax
is an asynchronous operation, your callback won't be called until the response comes back from the server.
Upvotes: 0