0

New to AJAX, I've built a form that contains AJAX that will send the data to another page. I'm not sure if I have to include a plugin for multiple ajax-requests or if this is done automatically. The problem so far is $("#userForm")[0].reset(); will wait until it has completely successfully before clearing the input field. I'm hoping to get it to send and clear immediately, allowing the user to enter request rapidly and building up a queue for the request to be completed.

Below is my form/ajax

<html>
<head>
<title>fastPage</title>
</head>
<body>
<form id='userForm'>
<div><input type='text' name='name' /></div>
<div><input type='submit' value='Submit' /></div>
</form>

<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>

<script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
        // show that something is loading
        //$('#response').html("<b>Loading response...</b>");
        // Call ajax for pass data to other place
        $.ajax({
            type: 'POST',
            url: 'slowPage.php',
            data: $(this).serialize() // getting filed value in serialize form
        })
        .done(function(data){ // if getting done then call.
            // show the response
            //$('#response').html(data);
            $("#userForm")[0].reset();
        })
        .fail(function() { // if fail then getting message
            // just in case posting your form failed
            alert( "Posting failed." );
        });
        // to prevent refreshing the whole page page
        return false;
    });
});
</script>
</body>
</html>

the slowPage.php is just to test the ajax calls out.

<!DOCTYPE html>
<html>
<head>
<title>slowPage</title>
</head>

<?php
session_start();
echo "
    <form action='slowPage.php' method='POST'>
        <input type='text' name='name'>
        <button type='submit'>Search</button>
    </form>";
sleep(10);  
if($_POST){
    echo $_POST['name'];
}

?>

Can anyone point me in the right direction to accomplish this?

Yodavish
  • 139
  • 2
  • 14
  • Why not just disable form submissions while the ajax is processing? Or do you want them to be able to submit multiple times? – mhodges Oct 01 '18 at 20:51
  • We want them to submit mulitple times as fast as possible, the slowPage is just to replicate a server page that could be very slow to test this idea out and build up a queue for the request. – Yodavish Oct 01 '18 at 20:53
  • This answer might be helpful: [Queue ajax requests using jQuery.queue()](https://stackoverflow.com/a/4785886/924299). – showdev Oct 01 '18 at 20:54
  • @Yodavish What exactly do you mean by "queue"? It will wait for one AJAX request to finish before sending the next one to the server? – mhodges Oct 01 '18 at 20:56
  • @mhodges It will wait for one AJAX request to finish before sending the next one to the server? Yes. However, since the server page could take 30 seconds to process we want to be able to "queue" these ajax request and allow the user to input more if needed. – Yodavish Oct 01 '18 at 20:58
  • @Yodavish Posted an answer, let me know if that's what you were looking for – mhodges Oct 01 '18 at 21:29
  • @mhodges so I'm having a little trouble trying to get a response, it doesn't produce a console log like yours. I copied everything except the first block of code: "ajaxQueue.addRequest(function() {" block, I even inspected the code from the browser and it looks the same. Also, is there a way to clear the input field after we hit submit or "Enter"? Allowing the user to enter in more request rapidly? – Yodavish Oct 02 '18 at 13:13

1 Answers1

4

One way to do this is to build your own queue agent, which will immediately execute requests that are pushed onto the queue, while executing at maximum 1 request at a time. When the current request is finished processing, it will remove itself from the queue, and immediately start the next request in the queue.

The code below is a generic case with any Promise object, however, you can modify what you pass in to suit your needs like so:

ajaxQueue.addRequest(function() {
  return $.ajax({
    // my ajax options
  })
  .done(function () {
    // ...
  })
  .fail(function () {
    // ...
  });
});

$(function () {
  var ajaxQueue = {
    queuedRequests: [],
    addRequest: function (req) {
      this.queuedRequests.push(req);
      // if it's the first request, start execution
      if (this.queuedRequests.length === 1) {
        this.executeNextRequest();
      }
    },
    clearQueue: function () {
      this.queuedRequests = [];
    },
    executeNextRequest: function () {
      var queuedRequests = this.queuedRequests;
      console.log("request started");
      queuedRequests[0]().then(function (data) {
        console.log("request complete", data);
        // remove completed request from queue
        queuedRequests.shift();
        // if there are more requests, execute the next in line
        if (queuedRequests.length) {
          ajaxQueue.executeNextRequest();
        }
      });
    }
  };
  $("#myForm").on("submit", function () {
    var data = $(this).serialize();
    // reset form right after we grab the data
    $(this)[0].reset();
    ajaxQueue.addRequest(function () {
      // -- your ajax request goes here -- 
      // return $.ajax({
      //   method: "POST",
      //   url: 'slowPage.php',
      //   data: data 
      // }).done(function () { ... }).fail(function () { ... });
      
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve(data);
        }, 2000);
      });
    });
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<label>Send Data: <input name="myData"/></label><br/>
<button>Submit Form</button>
</form>
mhodges
  • 10,938
  • 2
  • 28
  • 46
  • Cool, I didn't know we could run code from within here. This is very close to what I wanted. The only thing remaining is if we hit "Enter" or the submit button. It clears out the input field allowing the user to enter in new data quickly. I'm trying to decipher your code, do all 3 blocks of code go on one page? Also, where can I point ajax URL to send the data to the other page? Sorry I'm still new to ajax – Yodavish Oct 02 '18 at 12:21
  • @Yodavish Okay, I made some edits to my post to include the changes you have mentioned in your post. As for what code to include, you will want to include everything inside the `$(function () { });` block – mhodges Oct 02 '18 at 15:48
  • @downvoter care to comment? – mhodges Oct 02 '18 at 15:49
  • thanks I'll test it out thanks for your help I greatly appreciate it. – Yodavish Oct 02 '18 at 16:01
  • Thanks it worked! – Yodavish Oct 02 '18 at 16:14
  • @Yodavish Great! Glad it worked for you `:)` – mhodges Oct 02 '18 at 16:15