Thursday, September 7, 2017

jQuery Submit Form with Ajax

Hello,

In this blog we are going to take a look at how we can submit for with Ajax using jQuery.

First of all add jQuery file in your head section of HTML page.

<script src="jquery.min.js"></script>

Now we will have following form.

<form action="">
      <input id="text" autocomplete="off" placeholder="Type here" />
</form>

If you want to submit this form with Ajax using jQuery, first you have to do is add submit event handler.

$(function () {
$('form').submit(function(){
var formData = JSON.stringify($('form').serializeArray());
$.ajax({
type: "POST",
url: "YOUR_API_URL",
data: formData,
success: function(data){

},
failure: function(errMsg) {
}
});
return false;
    });
});

So first we have added submit event handler and used return false so it does refresh the whole page and just use the Ajax request.  Inside event handler we are using HTML 5 FormData to get form data first and then using Ajax request to send data to server in APIs.

Hope this helps you.

No comments:

Post a Comment