Using JQuery AJAX to communicate with server

Most classic way to pass data to the server from the webpage is to submit a form, and the browser will submit data to the server and the server will return the result after processing the request. In this approach our page will get refreshed by the browser and any static content on the page might be lost on page refresh

There is a solution for this to maintain page state on refresh but, instead there is an elegant and user friendly way to handle this, It’s using JQuery AJAX. In this, server communication will be handled by javascript and so all processes happen in the backend asynchronously without affecting our page. More details about AJAX can be found here https://learn.jquery.com/ajax/

During communication with the server, generally data will be transferred in form of key value pair but json format is more preferable when dealing with REST APIs.

So, In our example we will use JSON data format while performing API calls to the server.

How to convert form data into JSON object

jQuery provides a very simple method that helps in creating JSON data objects. This method is serializeArray(). To use it, we are going to create a new JavaScript function and pass in our form reference.

(function ($) {
	$.fn.serializeFormJSON = function () {
 
    	var o = {};
    	var a = this.serializeArray();
    	$.each(a, function () {
        	if (o[this.name]) {
            	if (!o[this.name].push) {
                	o[this.name] = [o[this.name]];
            	}
            	o[this.name].push(this.value || '');
        	} else {
            	o[this.name] = this.value || '';
        	}
    	});
    	return o;
	};
})(jQuery)

Performing AJAX request (POST)

We have seen the function that converts our form data into JSON object, Now let’s use that function and perform an AJAX request

HTML :

<form action="#" method="post" id="codersHanbookForm">
    <div>
   	 <label for="name">Name</label>
   	 <input type="text" name="name" id="name" />
    </div>
    <div>
   	 <label for="email">Email</label>
   	 <input type="text" name="email" id="email" />
    </div>
    <div>
   	 <label for="password">Password</label>
   	 <input type="password" name="password" id="password" />
    </div>
    <div>
   	 <label for="password">Phone</label>
   	 <input type="text" name="phone" id="phone" />
    </div>
 
    <p>
   	 <input type="submit" value="Send" />
    </p>
</form>

JS :

$('#codersHanbookForm').submit(function (e) {
	e.preventDefault(); // Prevent standard submit action by browser as we are handling it manually
	var data = $(this).serializeFormJSON(); // Converting form data to JSON
	console.log(data); // View Output in Console Log OUTPUT
	$.ajax({
		type: "POST", // Type of request, generally it will be POST or GET
        url: "coders_handbook_demo_submit.php", // Your submit page/route here
        data: data,
        dataType: "json", // Set data type to JSON
		success: function(result) {
		// If server returns HTTP 200 success response
		console.log(result); 
	},
	error: function(err){
	// If server returns error response
	console.log(err);
	}
	});
});

Console Log OUTPUT (Our data in JSON format):

{
  email: "[email protected]",
  name: "John Doe",
  password: "codersHandbookDemo",
  phone: "demo_phone_no"
}

Performing AJAX request (GET)

We have seen how to perform POST requests above, Let see one example of how to perform GET requests with some query parameters.

$.ajax({
    type: "GET", // Type of request, generally it will be POST or GET
    url: "coders_handbook_get_demo_submit.php?key1=value1&key2=value2", // Your submit page/route here
	success: function(result) {
	// If server returns HTTP 200 success response
	console.log(result); 
},
error: function(err){
// If server returns error response
console.log(err);
}
});

Leave a Reply

Your email address will not be published. Required fields are marked *