skip to Main Content

i want send ajax call with loop parameter named [id] in url starts request.php?id=1 ends id=9
and send every call after 3 second .
I’m a beginner in the JavaScript, I don’t know where to start the idea, this is my code:

        $.ajax({
            type: 'POST',
            url: 'request.php?id=1',
            data: {apiId:actionBtn},
            dataType: 'json',
            cache: false,
            beforeSend: function(){
                $('.submitBtn').attr("disabled","disabled");
                $('#addApi').css("opacity",".5");
            },
            success: function(response){

            }
        });

2

Answers


  1. // create a loop
    for (let i = 0; i <= 9; i += 1) {
      // create a timeout
      setTimeout(() => {
        $.ajax({
                type: 'POST',
                // set the id
                url: `request.php?id=${i}`,
                data: {apiId:actionBtn},
                dataType: 'json',
                cache: false,
                beforeSend: function(){
                    $('.submitBtn').attr("disabled","disabled");
                    $('#addApi').css("opacity",".5");
                },
                success: function(response){
    
                }
            });
      }, i * 3000)
    }
    
    Login or Signup to reply.
  2. First, make the id into a variable let id = 1;. Then you can use the JavaScript setInterval (https://developer.mozilla.org/en-US/docs/Web/API/setInterval) function to make a function-call every x seconds.

    let id = 1;
    
    // you can use a "fat-arrow" function or a function reference, look at the docs
    const interval = setInterval(() => {
      // your code here...
      // use the variable "id" and increment it
      i++;
    
      // stop the interval when id is greater 9
      if (id > 9) {
        clearInterval(interval);
      }
    }, 3000); // 3000 is the time in milliseconds
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search