Quick Sample To Use jQuery Global AJAX Events

Sometime we write AJAX based application which has many ajax call. If an AJAX called, we add loading image indicator to show that request being processed. For simply way we use AJAX beforeSend() and complete() events for show and hide loading image indicator. See code below:

// call an AJAX request
$.ajax({
	url: 'sample/url/target.php',
	beforeSend: function() {
		//call loading image indicator here
		showImageLoading();
	},
	success: function(result) {
		// do when success AJAX called successfully
	},
	complete: function() {
		//call function to hide loading image indicator here
		hideImageLoading();
	}
});

// call an another AJAX request
$.ajax({
	url: 'sample/url/another_target.php',
	beforeSend: function() {
		//call loading image indicator here
		showImageLoading();
	},
	success: function(result) {
		// do when success AJAX called successfully
	},
	complete: function() {
		//call function to hide loading image indicator here
		hideImageLoading();
	}
});

When we write much of AJAX call, we waste our time to write beforeSend() and complete() events for each AJAX calls. It’s also affect on total lines of code.

The better solution, we can use AJAX global events which always called when an AJAX request fired. Let’s try to modify code above:

// This event is triggered if an Ajax request is started
// and no other Ajax requests are currently running.
$(document).ajaxStart(function() {
	$(this).showLoading();
});

// This global event is triggered if there are no more
// Ajax requests being processed.
$(document).ajaxStop(function() {
	$(this).hideLoading();
});

// call an AJAX request
$.ajax({
	url: 'sample/url/target.php',
	success: function(result) {
		// do when success AJAX called successfully
	}
});

// call an another AJAX request
$.ajax({
	url: 'sample/url/another_target.php',
	success: function(result) {
		// do when success AJAX called successfully
	}
});

That’s, we just define global AJAX events once, and call many AJAX request. We can also disable global event for a particular AJAX request by passing global option to false on an AJAX request like below:

$.ajax({
	global: false,
	success: function(result) {
		// do when success AJAX called successfully
	}
});

The complete list of global and local jQuery AJAX events can be found at http://api.jquery.com/Ajax_Events/

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s