jquery ajax error handling

How to handle ajax errors using jQuery ?

jQuery is the most awesome javascript library that made easy for asynchronous ajax calls.it has global ajax function and some pre defined ajax functions like $.get, $.post, load .etc. but we don’t find any error messages by default with this library. we can see the errors with firefox’s addon firebug or with IE developer toolbar.So we manage most common ajax errors in our application with global ajaxSetup function which come with jQuery by default. We can set many options,to see available ajaxsetup options please check here.

most ajax errors we get errors are server response errors and some JSON parse errors. To know more about the HTTP errors details please check here. To test this error handling just copy and paste it to your head section of HTML document.

Javascript Code for setting global error handling.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$().ready(function(){
	$.ajaxSetup({
		error:function(x,e){
			if(x.status==0){
			alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
			alert('Requested URL not found.');
			}else if(x.status==500){
			alert('Internel Server Error.');
			}else if(e=='parsererror'){
			alert('Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
			alert('Request Time out.');
			}else {
			alert('Unknow Error.\n'+x.responseText);
			}
		}
	});
});

In the above example we handle following common error and show response text for other rare errors.

  • 0-xhr status ,is it initialized or not that means user is offline.
  • 404-page not found
  • 500-Internel Server error.
  • request timeout – jQuery custom error.
  • parseerror-jQuery custom error when parsing JSON data.
  • we just throw other errors with response error

Example1

1
2
params={name:'mahesh'};
$.get(url,params,function(){})

In above example,jQuery automatically raises all available errors,except parse error. because we didn’t give any return type format.

Example2

1
2
3
params={name:'mahesh'};
$.get(url,params,function(){},'json');
$.getJSON(url,params,function(){});

In above example,jQuery automatically raises all available errors,because we added return type format at end. $.getJSON automatically adds the return type of parameter to “JSON”

Example3

1
2
params={name:'mahesh'};
$.get(url,params,function(){},'xml');

In the above example 3 ,we gave xml type return parameter, here also jQuery automatically raises all errors even parse error also.

stop browser cache

How to stop the web browser caching the document

All web documents, media and other web resources retrieved by a Web browser, are often saved, or cached, locally on the user’s hard drive. The next time that media or web resources is requested the Web browser may load the file from the cache instead of downloading it over the internet. This might be desirable for a some web document content doesn’t change often but undesirable for documents are updated frequently with new content or information.
All web servers sends to the browser with some basic information about the document before it sent .in the above example we can see some of them.for full details please refer here . we can use this server side headers to prevent browser caching .we learn here only PHP related headers.

preventing browser cache with javascript.

Here i am showing basic jQuery plugin that appends a random time to each links in document.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(function($){
	$.fn.nocachelink=function(options){
	//itereate trough each element in given element collection
		return this.each(function(){
			var href=$(this).attr('href');
			if(href.lastIndexOf('?')!=-1){ //if query string is set or not for link
			href=href+'?'+new Date().getTime();
			}else{
			href=href+'&'+new Date().getTime();
			}
			$(this).attr('href',href); // update new href attribute
		});
	}
})(jQuery);

An example how to use it

$().ready(function(){
	$('.nocache').nocachelink();
});

preventing browser cache with meta tags.

to prevent cache by means of html meta tags add following tags to document head section.

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">

preventing browser cache with server side headers.

we can also use HTTP headers by php also as below,remember you must add this lines to start of code.

//  @-silenced or error suppress operater
	@header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
	@header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
	@header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
	@header( 'Pragma: no-cache' );

preventing browsers cache with ajax calls.

we can also set headers with ajax response headers.

preventing browser cache with other methods.

By default all browser don’t cache SSL layered documents.
below example document won’t cached by browsers.

https://www.yourdomain.com

introduction to javascript framework jquery

jquery introduction

What is jQuery?

JQuery is a JavaScript framework that makes writing advanced JavaScript very easy.
You can learn easily jQuery even you know basic knowledge in JavaScript. It has many useful JavaScript function to support cross browser JavaScript compatibility.

Where can you get it?

The official jQuery website (http://jquery.com) is always the most up-to-date resource for code and news related to the library. To get started, we need a copy of jQuery, which can be downloaded right from the home page of the site. Several versions of jQuery may be available at any given moment; the latest uncompressed version will be most appropriate for developers like you. You can find documentation here (http://docs.jquery.com).

How to install and run jQuery?

Since jQuery is a pre built function library in JavaScript, we can include normal external JavaScript files after downloading it from core jQuery web site.

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//do magic with jQuery here
});
</script>
</head>
<body>
</body>
</html>

What you can do with jQuery?

Easy Dom selectors (css, javascript, xpath, Dom).
Ajax.
Easy Dom manipulation
Easy Dom traversing
Use pre programmed number of jQuery plug-ins.
Cross browser supported event handling.
Utility functions.
Flash like animation.
And you can develop complex web applications with less coding….more.

How to use Magic method of jQuery $().ready or $(document).ready?

Generally browser loads external CSS and JavaScript files first and after loads the document element model and assigns corresponding objects by loading from server.
This loading of all objects called window load and when it completed browser triggers window.load event. But we can manipulate the document after the document element model. This event occurs before window.load event. Some A grade browsers supports this DOM ready event. So cross browser compatibility jQuery added this magic method to find the Dom ready event.
We call this method as below

1
2
3
$(document).ready(function(){
alert(‘Dom loaded’);
});

Document parameter is optional, if no parameter given jQuery assumes the document.

1
2
3
$().ready(function(){
alert (‘Dom loaded’);
});

Generally we call the window load event with jQuery as below,

1
2
3
$(window).load (function () {
alert (‘window loaded completely’);
});