Home > Software design >  send ajax requests per line of textarea and wait 5 secon between each request
send ajax requests per line of textarea and wait 5 secon between each request

Time:08-15

Please, I want a solution. I tried all the solutions I searched for, but I didn't find a solution. I try to send each line in textare in ajax request and betwe Between each request it waits 5 seconds and sends the next request.

I wrote this code and it works correctly but when I used it in any file in main directory of my project it send only first line in textarea and not send the next request

My Js Code :

<script type="text/javascript">
$(document).ready(function(e){
    $("#sendForm").on('submit', function(e){
    e.preventDefault();    


var lines;
const time=2000;

function sendline(i=0) {
if (i==0)
lines = $("#emails").val().split('\n');
if (i>=lines.length)
return
if (lines[i].replace(" ","")=="")
{
sendline(i 1);
return;
}
$.ajax({
url: "ajax-send.php",
type:"POST",
data:{emails: lines[i]},
success: function(data){
                                //    $('#response').append(data "<br/>");
 $(data).appendTo($("#response")).before("");
     $('#response').animate({scrollTop: $('#response').prop("scrollHeight")}, 500);
$("#num-msg-1").html($('#response p.alert-success').length);
$("#num-msg-2").html($('#response p.alert-danger').length);

       // $("#response").html(data);    
if (i>=lines.length)
return ;
setTimeout(sendline,time,i 1);
}
}//success
);
}
sendline();




 });


 });

</script>

CodePudding user response:

You can use this snippet to fetch one at a time using a clever callbacks trick.

var textarea = document.querySelector("textarea");
var content = textarea.value;
var lines = content.split("\n").filter(line => !!line);

do_one(lines, function() {
  console.log("all done")
})

function do_one(lines, final_callback) {
  if (lines.length) {
    var line = lines.shift();
    console.log("fetching "   line);
    fetch("url", line, function() {
      console.log("waiting 3 seconds");
      setTimeout(function() {
        do_one(lines, final_callback)
      }, 3000)

    })
  } else {
    final_callback();
  }
}

function fetch(url, data, callback) {
  setTimeout(callback, 500);
}
<textarea rows="4">
line 1
line 2
line 3
</textarea>

  • Related