Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute ajax request one by one

Tags:

jquery

ajax

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.

Below you can see an overview of my goal.

Here is my script structure.. & its working fine

<script>
    $(document).ready(function(){
        applyScript();
        var jqueryarray = <?php echo json_encode($array); ?>;
        for (i = 0; i < jqueryarray.length; i++) {
             // my logic is here
             try {
                $.ajax({
                   url: url1,
                   cache:  false ,
                   type : 'POST',
                   // dataType: "json",
                   data: data1,
                   success: function(response){
                      if (response) {
                         // some logic with response
                      }
                   }
                });
             }catch (e) { }
        };
    });
</script>

Here based on for loop its working ajax sending the request but my goal is i want send the ajax request one after another.

you can see my prob here

enter image description here

any ideas ?

like image 995
Naresh Avatar asked Jan 22 '26 23:01

Naresh


1 Answers

Create a recursive like function that's re called upon completion of one ajax request like below:

   $(document).ready(function(){
    applyScript();
    var jqueryarray = <?php echo json_encode($array); ?>;
    var $i = 0; 
    ajax_forloop( $i );
   });
    function ajax_forloop( $i )
    {
         // my logic is here
         try {
            $.ajax({
               url: url1,
               cache:  false ,
               type : 'POST',
               // dataType: "json",
               data: data1,
               success: function(response){
                  if (response) {
                     // some logic with response


                     //call another ajax request
                     $i++;
                     if( $i < jqueryarray.length ) 
                     {
                         ajax_forloop( $i );  
                     }

                  }
               }
            });
         }catch (e) { }

    }
like image 104
hi0001234d Avatar answered Jan 24 '26 13:01

hi0001234d



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!