Perform AJAX using jQuery’s $.ajax() Function

AJAX is used to perform some operations in a background without loading entire page which is known as asynchronous operation. We can perform AJAX operation with normal JavaScript too. It’s syntax is large because each browsers are using different way for this specially Microsoft Internet Explorer. Therefor i am using jQuery’s $.ajax() function.

The jQuery’s $.ajax() function is used to perform an asynchronous HTTP request. using ajax() we can perform operation on POST, GET, and any other HTTP requests. ajax() function takes various options for operation by parameter. Some important are described below:

Options
url: A string containing the URL to which the request is sent
data:The data to send to the server when performing the Ajax request
dataType: The type of data expected back from the server
error: A function to be called if the request fails
success: A function to be called if the request succeeds
type: The type of request to make, which can be either “POST” or “GET”
Click here to open official documentation for read more.

Example

$(document).ready(function(){
	$('#btn').click(function(event){
		$.ajax({
			url: 'https://api.github.com/users/nilay123',
			type: 'GET',
			error: function() {
				$('#result').html('An error has occurred');
			},
			success: function(data) {
				$('#result').html(data.name);
			}
		});
	});
});

Click here to download above example as HTML file.
In above Example i am retrieving my name from github’s API. i am selected github api because it is publicly open no need to verify or login.

Leave a Reply

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