ajax cheatsheet

Fri. July 18, 2008
Categories: Development
Tags: , ,

Other Languages:


1. Create XMLHttpRequest object

1
2
3
<script language="javascript" type="text/javascript">
var xmlHttp = new XMLHttpRequest();
</script>

2. Get and set form field values with JavaScript

1
2
3
4
5
// get the value of "phone" field and write it to phone variable
var phone = document.getElementById("phone").value
//set values in form using response array
document.getElementById("order").value = response[0];
document.getElementById("address").value = response[1];

3. Working with Microsoft browsers

Microsoft Internet Explorer browser uses MSXML alalyzator for XML processing. That is why you need to create the object with special way, if you want your AJAX-application to work in Internet Explorer. However it’s not so easy. There are two different verions of MSXML on the market. The version depends on which version of JavaScript interpretator is installed in Internet Explorer. So, you need to write code, which going to work in both versions:

1
2
3
4
5
6
7
8
9
10
var xmlHttp = false;
try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
        xmlHttp = false;
    }
}

You see now that there are three ways to create XMLHTTPRequest object:

1
2
3
var xmlHttp = new XMLHttpRequest();
var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

3. Merge together

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Create the new XMLHttpRequest object to communicate with web-server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version &gt;= 5)
try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
        xmlHttp = false;
    }
}
@end @*/
if (!xmlHttp &amp;&amp; typeof XMLHttpRequest != ''undefined'') {
    xmlHttp = new XMLHttpRequest();
}

4. Send the request

Now you have the greatest XMLHttpRequest object; let’s make it useful. First, we need the JavaScript-method, which our web page can call (for example, when user enters the text or choose an item from menu). Next, we need to follow the next scheme almost in all your Ajax applications:

  1. Get any data from web-form.
  2. Create an URL for connection.
  3. Open the connection with server.
  4. Create a callback function, which will be called after server response.
  5. Send the request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function callServer() {
    // Get city and state from web-form
    var city = document.getElementById("city").value;
    var state = document.getElementById("state").value;
    // Continue if we have both values
    if ((city == null) || (city == "")) return;
    if ((state == null) || (state == "")) return;
    // Create URL for connection
    var url = "/scripts/getZipCode.php?city=" + escape(city) + "&amp;state=" + escape(state);
    // Open connection with server
    xmlHttp.open("GET", url, true);
    // Create the callback function
    xmlHttp.onreadystatechange = updatePage;
    // Send request
    xmlHttp.send(null);
}

5. Processing the response

Now we should care about server’s response. You should know two things:

  • Don’t do anything until xmlHttp.readyState property equals to 4.
  • Server will store its response in xmlHttp.responseText property.
1
2
3
4
5
6
function updatePage() {
    if (xmlHttp.readyState == 4) {
        var response = xmlHttp.responseText;
        document.getElementById("zipCode").value = response;
    }
}

6. Start Ajax-process

1
2
3
4
5
<form>
<p>City: <input type="text" name="city" id="city" size="25" onChange="callServer();"/></p>;
<p>State: <input type="text" name="state" id="state" size="25" onChange="callServer();"/></p>
<p>Zip Code: <input type="text" name="zipCode" id="zipCode" size="5" /></p>
</form>

One Response to “ajax cheatsheet”

  1. saunsesew Says:

    Спасибо за пост! Добавил блог в RSS-ридер, теперь читать буду регулярно..

Comments