0

Is it possible to using ajax call in a loop?
Here I want, when I single click on button then the ajax call will called 10 times. below is my code. Don't know is it good practice or not.

But I need this type of solution. How can I do it? thank you.

HTML:

  <button>Click</button>

AJAX :

  $(document).ready(function(e) {
            $('button').click(function(){
                  for(var i=1;i<=10;i++){        //is it possible ?
                    $.ajax({
                        type:'POST',
                        url : "a.php",
                        data:'a='+$('.div1').text(),
                        success: function(result){
                                $('.div1').html(result);
                            }                               
                    });
                  }
                });
        });

a.php :

        <?php
             if(!isset($_POST['a']) || $_POST['a'] == ""){
                $a = 0;
             }
             else{
                $a = $_POST['a'] + 1;   
             }
             echo $a;
             exit();
         ?>
3
  • It is. Why do you need it? What are you going to handle at server side? Commented Jul 20, 2014 at 5:20
  • What is your problem with your current code? Commented Jul 20, 2014 at 5:22
  • 1
    Why would you want to do that? You're calling the same thing over and over. Are you sure you don't want to run a $('.div1').each() with AJAX inside it? Still, you could just Array.join() the .text() from $('.div1').each() and send once to the Server with AJAX. Commented Jul 20, 2014 at 5:23

1 Answer 1

1

try this:

$(document).ready(function(e) {
        var ajaxCalled=0;
        $('button').click(function(){
                $.ajax({
                    type:'POST',
                    url : "a.php",
                    data:'a='+$('.div1').text(),
                    success: function(result){
                            $('.div1').html(result);
                            ajaxCalled++;
                            if(ajaxCalled<=10){
                                $('button').trigger('click');
                            }
                            else{
                                ajaxCalled=0;
                                return false;
                            }
                        }               
                });
            });
    });
Sign up to request clarification or add additional context in comments.

3 Comments

you're welcome, please accept the answer by clicking the check-mark beside my answer, if this answer is in fact what you were looking for. ;)
is it OK to run 1000 times like this?
Do you mean in a loop?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.