A complete sample program in AJAX

By: Ram Baskar Emailed: 1644 times Printed: 2109 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Here is a complete AJAX example with a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." and then we'll alert() the contents of thetest.html file.

<script type="text/javascript" language="javascript">

    

    function makeRequest(url) {

        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { alertContents(http_request); };
        http_request.open('GET', url, true);
        http_request.send(null);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
</script>
<span
    style="cursor: pointer; text-decoration: underline"
    onclick="makeRequest('test.html')">
        Make a request
</span>

In this example:

  • The user clicks the link "Make a request" in the browser;
  • This calls the makeRequest() function with a parameter – the name test.html of an HTML file in the same directory;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.

Note: The line http_request.overrideMimeType('text/xml'); above will cause Javascript Console errors in Firefox 1.5b as documented at https://bugzilla.mozilla.org/show_bug.cgi?id=311724 if the page called by XMLHttpRequest is not valid XML (eg, if it is plain text).

If you get Syntax Error or Not Well Formed Error on that browser, and you're not trying to load an XML page from XMLHttpRequest, remove that line from your code.

Note 2: if you are sending a request to a piece of code that will return XML, rather than to a static XML file, you must set some response headers if your page is to work in Internet Explorer in addition to Mozilla. If you do not set header Content-Type: application/xml, IE will throw a Javascript error 'Object Expected' after the line where you try to access an XML element. If you do not set headerCache-Control: no-cache the browser will cache the response and never re-submit the request, making debugging 'challenging'.

Note 3: if the http_request variable is used globally, competing functions calling makeRequest() may overwrite each other, causing a race condition. Declaring the http_request variable local to the function and passing it to the alertContent() function prevents the race condition.

Note 4: To register the call back function onreadystatechange, you cannot have any argument:

http_request.onreadystatechange = function() { alertContents(http_request); };  //1 (simultaneous request)
http_request.onreadystatechange = alertContents(http_request); //2 (does not work)
http_request.onreadystatechange = alertContents;  //3 (global variable)
Method 1 allows to have several requests done in simultaneously, method 2 will not work, method 3 is used if http_request is a global variable

Ajax Home | All Ajax Tutorials | Latest Ajax Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

i created report. but i move to second page all details clear. is there solution for it.
--
Thanks.


View Tutorial          By: nadeekadn at 2012-04-30 10:11:42

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ram Baskar
Hello World sample program in C#
Comments in C#
Preprocessor directives in C#
Boxing and unboxing in C#
Categories of datatypes in C#
Major features of C#
Which version of C# to use?
History of C#?
Why it was named C#?
Design Goals of C#
What is C#?
A complete sample program in AJAX
Handling the Server Response in AJAX
How to Make an HTTP Request in AJAX

More Tutorials in Ajax
How to Make an HTTP Request in AJAX
Handling the Server Response in AJAX
A complete sample program in AJAX
XML vs JSON in AJAX
Creating JSON objects using Java in AJAX
The History of AJAX
To use or not to use AJAX

More Latest News
Most Viewed Articles (in Ajax )
A complete sample program in AJAX
The History of AJAX
To use or not to use AJAX
XML vs JSON in AJAX
Creating JSON objects using Java in AJAX
How to Make an HTTP Request in AJAX
Handling the Server Response in AJAX
Most Emailed Articles (in Ajax)
A complete sample program in AJAX
The History of AJAX
To use or not to use AJAX
XML vs JSON in AJAX
Creating JSON objects using Java in AJAX
Handling the Server Response in AJAX
How to Make an HTTP Request in AJAX