Ajax's main concepts revolve around asynchronous HTTP requests. The HTTP request is used to establish a permanent connection between the server (where the actual script that will process the request resides) and the client where the JavaScript (for Ajax purposes) is being executed. In order to make your Ajax interoperable across the most popular browsers, we actually need to send three different XmlHttp object types.
- XMLHttpRequest(); for the purposes of Firefox
- ActiveXObject("Msxml2.request") for newer versions of IE
- ActiveXObject("Microsoft.XMLHTTP") for older versions of IE
The code looks like this:
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch(trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
Once we have opened the HTTP connection, Ajax is ready to request anything from the server while the application can be doing something else at the user's request. We then send an alert box to the browser in the event none of the above objects is supported by the browser being used. Not likely to happen really.
if (request == null)
alert("OOPS, I'm unable to process your request!");
}
Sending your request to the server:
Ok, so now that you know how to establish a connection with the server while supporting the most popular / available browsers today, you need to know how to ask the server for whatever it is that will make you update the "portion" of your page upon receiving the desired response.
The purpose of my little AJAX application is to allow users to login without updating the entire page, just the login box. Once the user has been authenticated, the login box's HTML will be replaced with the HTML returned by the server response, which includes the name of the user, and the link to updating his/her profile.
We are going to create the userAccess() function, which will:
- Declare the variable(s) that will hold the values of the form fields being submitted
- Create the server request defined before (with the XMLHTTP connection info)
- Establish the "Content Type" or format in which the data is to be posted to the server
- Send the request to the server using the script page URL and POST or GET method depending on the need
Your userAccess() function will look like the below. Don't worry if you don't understand right away, I will explain what the elements are later in this guide
function userAccess() {
var LoginEmail = document.getElementById("email").value;
var LoginPassword = document.getElementById("password").value;
var url = "login.asp";
createRequest();
request.open("POST", url, true);
request.onreadystatechange = updatePage;
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.send('Login=' + ("true") +
'&LoginEmail=' + escape(LoginEmail) +
'&LoginPassword=' + escape(LoginPassword));
Onreadystatechange() function:
This function is used to read the several steps the communication takes to get the final response from the server. You can read the state of this function and decide to take an action based on whether it changed as well as what specific state the request is. The four main states of the requests are as follow:
- Request Sent
- Request Received
- Server Response Sent
- Server Response Received
This means that your final OnReadyStateChange() is == 4 and that is when you are receiving the response from your server script. In this case we have decided to call the updatePage() function, which holds the code that will execute the action (explained in detail later)
Another very important validation we have to run is to check whether the connectivity to the server and the script pages are achieved. This is by verifying the Status method of the Http request object you created (called request). It looks like this:
if (request.status == 200) {
...ACTIONS HERE - DISCUSSED IN FURTHER PAGES
}
What the above does is verify if we get connected to the server as well as confirming the existence of your script page (discussed later). A 200 status means "OK" to the connection and to the existence of your script page. Here are some of the status codes:
- 200 - Means OK and Found
- 404 - Resource not found
- 500 - Script Error
You can validate against any of the above responses and take actions to display friendly messages based on them (out of the scope of this guide)
var request = null; function createRequest() { try { request = new XMLHttpRequest(); } catch(trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } if (request == null) alert("OOPS, I'm unable to process your request!"); } function userAccess() { var LoginEmail = document.getElementById("email").value; var LoginPassword = document.getElementById("password").value; var url = "includes/login.asp"; createRequest(); request.open("POST", url, true); request.onreadystatechange = updatePage; request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.setRequestHeader("Connection", "close"); request.send('Login=' + ("true") + '&LoginEmail=' + escape(LoginEmail) + '&LoginPassword=' + escape(LoginPassword)); } function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var serverresponse = request.responseText; var finaldisplay = document.getElementById("user"); --TAKE ACTION HERE } } else { if (request.readyState == 1) { ---TAKE ACTION HERE } } }
|
On the next pages we will learn:
- Sending Requests using GET or POST
- Setting header type so the server understands the structure of your form values
- Handling the server response (using the available properties)
- Identifying and changing your HTML to let AJAX do its thing
- Refreshing "Only" the parts of your page you want to see action on, not the entire page
- Avoid W3c Validation Issues
Keep reading.