Did you find this useful?
Socialize it today.


Ajax XMLHttpRequest Request Data

Monday, July 23, 2012

The XMLHttpRequest object is used to send and receive data with between a web browser and web server. In this article, we are going to look at how to send data to a web server. To send a request to a server, we will need to use the open() and send() methods of the XMLHttpRequest object.


HTML Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

  // ... JavaScript code

</script>
</head>
<body>
 <img id="img1" onclick="loadAjax()" src="go.png" /> ; 
 <div id="div1"> <!-- Some Content --> </div>
</body>
</html>


Syntax

xhr.open(method,url,async);
xhr.send(string);

open() and send() Methods

MethodDescription
open(method,url)Specifies the method and URL (GET, POST, HEAD)
open(method,url,async)The async parameter specifies whether the request async or sync. True = async, async is default.
open(method,url,async,userName)Specifies the username to connect
open(method,url,async,userName,password)Specifies the password to connect
send(string)send(string) Sends the request off to the server
setRequestHeader(header,value)Specify header name and value


Method

GET is far simpler and faster when compared to POST. In most cases, GET will be sufficient. POST should be used in situation such as:

  • You want to avoid cached files
  • You need to send large amounts of data to the web server
  • You need additional security over GET

If you are using GET and want to avoid cached results, append a querystring parameter that is unique to ensure that the client browser avoids cached results. This is important if your back-end data is dynamic. You want to make sure that dynamic data is being presented to the user.


xhr.open("GET","/demo/ajax_load.aspx?q=" + Math.random(),true);
xhr.send();

As you can see, you can use the GET method to send parameters via a querystring. You can also use the POST method to send form data without the use of a querystring. Here are two examples; using POST and POST sending form data.


xhr.open("POST","/demo/ajax_load.aspx",true);
xhr.send();


xhr.open("POST","/demo/ajax_load.aspx",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("firstname=John&lastname=Smith");

URL

Within the open() method, the url parameter is used to specify the address to a file on a web server


xhr.open("GET","/demo/ajax_load.aspx",true);

You can specify different types of files such as .txt, .asp, .aspx, .php, and .xml.


Async

Sending asynchronous requests is a huge improvement for web applications. Before Ajax, each request would require a page reload to display new data to the user. With Ajax, JavaScript can send a request to the server and continue to execute other scripts. As soon as the response is received from the server, the JavaScript code would work with the response data. This is much more efficient when dealing with multiple scripts within a document. The default setting for async is TRUE. However, if you require that the JavaScript code execute synchronously, then set this property to FALSE.


xhr.open("GET","/demo/ajax_load.aspx",true);

  (OR) 

xhr.open("GET","/demo/ajax_load.aspx",false);


Example

    function loadAjax() {
        var xhr = false;
        if (window.XMLHttpRequest) {
            // IE7+, Firefox, Chrome, Opera, Safari
            xhr = new XMLHttpRequest();
        } 
        else {
            // IE5/IE6
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xhr) {
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("div1").innerHTML = xhr.responseText;
                }
            }
            xhr.open("GET", "/demo/ajax_load.txt", true);
            xhr.send(null);
        }
    }


click here
Click the icon to load data via Ajax!


Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Ajax for Dummies The Complete Reference Ajax Bulletproof Ajax