Home > database >  how can send ajax call with looping id number parameter in url
how can send ajax call with looping id number parameter in url

Time:08-08

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){

            }
        });

CodePudding user response:

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

CodePudding user response:

// 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)
}
  • Related