Jquery Ajax – an example of its use

Jquery ajax

The Jquery library is a javascript library (here the link to its website), maybe the most famous one. Jquery Ajax is the method that is used to send an Http request.

Jquery Ajax method triggers a request and gets the result, without having to refresh the entire page, i.e. in an asynchronous way. This approach is becoming very popular, mainly in frameworks that are single-page applications (Angular for example) oriented.

How does it work?

To be able to use Jquery library first you need either to include it in your webroot or to use it through a CDN, as shown below:

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

The AJAX method can be then called throughout the web application.

Example on form submission

I will show you know a simple example of the AJAX method use. In this example, I want to submit a form asynchronously. I have a form with 2 inputs one for the code and one for the description.

<form id="truongtong-form">
    <input type="text" id="code" name="code" placeholder="Code" />
    <input type="text" id="description" name="description" placeholder="Description" />

    <button type="submit">Save</button>
</form>

If I just use the below code in an HTML page, the expected behaviour will be a refresh of the page once I would click on the Save button.

To send the information that the user typed in the input fields without a refresh I would need to call the Jquery AJAX method on the submit event. Here the code:

( "#truongtong-form" ).submit(function( event ) {
	// we create a form data object to send the code and the description
	var form = new FormData();
	form.append("Code", $('#code').val();
	form.append("Description", $('#description').val();
	
		//we send the request 
		  $.ajax({
			  method: "POST"
			  ,url: "your_post_action"
			  ,success: function(result){
				$("#div1").html(result);
				}
			,data: form
			});
		//we prevent the default event (that is the refresh of the page)
		event.preventDefault();
});

The above example shows the use of Jquery AJAX using a POST method. When submitting information to the database we usually go with this method, instead of the GET.

In the code we’re creating a FormData object first. It will contain a list of pairs. In our case the code and the description.

The parameters we use in the Ajax method are the url, the success and the data.

URL parameter tells which action on the server-side needs to be called. The data parameter contains the form data. The success parameter is optional and it used to show to the user the output of the server response.

Be the first to comment

Leave a Reply

Your email address will not be published.


*