In this tutorial, we will see how to make simple ajax call using jQuery. jQuery is widely used in almost all type of web development platform to make a flow of an application simpler and faster.

how to make simple ajax call using jQuery

AJAX these days, is very popular technique specially used when we don't want to reload site or want to avoid redirect after form submission or want to load specific section on the page. It is a very easy technique that can do many thing/tasks.
In this tutorial, we will learn to make an ajax call on form submit event. But to understand ajax, you need to have a basic understanding of JavaScript and html as we are going to use both the technologies to explain.
Please see below code carefully.

HTML Code

HTML file - registration.html
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>

<body>
<form id="registration_form" name="registration_form" action="registration.php" method="POST">

   <label>Full Name: </label>
   <input type="text" name="full_name" id="full_name" placeholder="Please enter Name" />

   <label>Email: </label>
   <input type="text" name="email" id="email" placeholder="Please enter an Email" />

   <label>Mobile: </label>
   <input type="text" name="mobile" id="mobile" placeholder="Please enter Mobile" />

   <label>Address: </label>
   <textarea name="address" id="address" placeholder="Please enter an Address" /></textarea>

</form>


<script src="js/jquery.min.js"></script> <!-- Master jQuery to make the functions work -->
<script src="js/custom.js"></script> <!-- Custom js file for custom functions like ajax call etc -->

</body>
</html>

Custom JavaScript Code

JavaScript file - custom.js
/***** This code defines the ajax call *****/
$("#registration_form").submit(function(){
   $.ajax({
     url: $("#registration_form").attr("action"), /* gets the URL of form */
     data: $("#registration_form").serialize(), /* serialize function collects the form data */
     type: "POST", /* sets the form submission method */
     dataType: "JSON", /* this is useful to get the response in an ajax format */
     success: function(response){
        /* an action on the successful response */
     }, 
     error(xhr,status,error){
        /* an action on error */
     }
   });
});

In this way, we can make a call to the server page using AJAX to interact with it and get the task done without reloading the page. AJAX method is faster than the normal form submit as it only submits the form data and get the response but does not reload the page, hence no need to load all the files again which automatically make the action faster.

So, in this tutorial, we learnt how to make simple ajax call using jQuery. If you liked it, please share it with your friends.