Chetan Soni
Chetan Soni

Reputation: 854

Update form status by changing submit button text

I've small JS code which is not working as per my need.

Actually my backend PHP code contains so many functions which i want to process by pressing submit button and meantime i also want to show the status "Scanning" in place of submit button and when the data got fully processed, then i want to show "Completed" Status in place of submit button.

<script>
  $(function () {
    $('form').on('submit', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'post',
        url: 'post.php',
        data: $('form').serialize(),
        success: function () {
          $(#response).show();
          $(#form).hide();
        }
      });
    });
  });
</script>

Upvotes: 1

Views: 878

Answers (2)

Syamsoul Azrien
Syamsoul Azrien

Reputation: 2752

You can use beforeSend...

beforeSend is a pre-request callback function that can be used to modify the jqXHR..

You can refer here for more detail.

And you can follow my code below for your ease.

..

Javascript:

<script>
  $(function () {
    $('form').on('submit', function (e) {
      e.preventDefault();

      let submitBtnEl = $(this).find('button[type="submit"]'); //submit button element

      $.ajax({
        type: 'post',
        url: 'post.php',
        data: $('form').serialize(),
        beforeSend: function( xhr ) {
            submitBtnEl.html('Scanning'); //the submit button text will change after click submit
        },
        success: function () {
            $(#response).show();
            $(#form).hide();
            submitBtnEl.html('Completed'); //the submit button text will change after the form is completely submit
        }
      });
    });
  });
</script>

.

.

HTML:

<form>
    <input type="text" name="input1" />
    <button type="submit">Submit</button>
</form>

.

.

For your ease, you can try the code on this fiddle

Upvotes: 2

Muhammad Usman
Muhammad Usman

Reputation: 10148

You can simply show whatever you want when user clicks the button. And when you get the response you can change to whatever you want. Something like.

This is just an example of mocking your ajax request.

var $button = $("#btn");

$button.click(function() {

    $button.text("Scanning...");

    var promise = new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve('foo');
        }, 5000);
    });
    
    promise.then(function(){
     $button.text("Done");
    })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn"> Submit </button>

Upvotes: 2

Related Questions