Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery each not working as expected

Tags:

jquery

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 ?

like image 878
chhameed Avatar asked Jun 26 '26 07:06

chhameed


1 Answers

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 async option to false.

Go to this link and search for the async option 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.

like image 149
MD Sayem Ahmed Avatar answered Jun 28 '26 23:06

MD Sayem Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!