Handling success, error and complete events during Ajax operation using jQuery

by Jagadish Pulakhandam on 10/25/2012 7:22:35 AM
Rated 0 from 0 votes
Brief: Demonstrates on working with jqXHR object to handle Ajax responses of jQuery in a better fashion.
Posted to: Ajax programming using JQuery - Tutorials/Videos
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached source code/video demonstrates the following:
  • How to use jQuery AJAX ($.ajax) to fetch information using HTTP GET operation
  • How to handle "success" event once the jQuery request is successful
  • How to handle "errors" during jQuery Ajax
  • How to handle "complete" event after jQuery request is processed (whether or not it is success)

Source Code:

01.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04.    <title></title>
05.    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
06.    <script type="text/javascript">
08.        //using jqXHR object for error, complete, success - works from v1.5
09.        function GetWebPageContent() {
10.            var req = $.ajax({
11.                url: "/default1.aspx", //TRY THIS WITH CORRECT AND WRONG URL
12.                type: "GET", //type of request - default is GET - optional
13.                cache: false //whether to cache the response of this request - default is true - optional
14.            });
16.            req.success(function (data) {
17.                var ContentFrames = $("#ContentIframe");
18.                //get document object of IFRAME
19.                var doc = ContentFrames[0].contentWindow.document;
20.                //get body element of IFRAME
21.                var body = $('body', doc);
22.                //modify HTML content of IFRAME
23.                body.html(data);
24.                ContentFrames.css("display", "inline");
25.            });
27.            req.error(function (err) {
28.                alert("wrong URL or data could not be retrieved: " + err.statusText);
29.            });
31.            req.complete(function () {
32.                //gets executed whether or not the request is success
33.                alert("GET Request is complete");
34.            });
36.        }
38.    </script>
41.    <input type="button" value="Show News" onclick="GetWebPageContent();" /><br>
42.    <iframe id="ContentIframe" style="display:none">
43.    </iframe>

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following