I have the following code .
var last_id = '';
$('.products').each(function(){
$.ajax({
type: "POST",
url: "index.php",
data: 'id='+last_id,
success: function(id){
last_id = id;
}
});
});
My problem is that , i want to get the last inserted id from ajax success and pass it to ajax when id call on second time.
but now it can’t get the last_id and in second time it again send as empty string
But when i alert it in ajax success it alert the last id ?
How can i achieved it ?
It won’t work because when you send the second request, the first request’s response hasn’t arrived yet. That’s the way it is because the requests you are sending are all asynchronous, so the second request won’t wait for the first request to complete. That’s why an empty string is being sent the second time too.
One way to send synchronous requests is to set
asyncoption tofalse.Go to this link and search for the
asyncoption there to find a proper explanation.But you should note that sending synchronous requests may temporarily block the browser, because it waits for the request to complete before doing anything else.