Learning Ajax - Page 2



 You are in: 9Searches.org > Computers > Internet  

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:

  1. Declare the variable(s) that will hold the values of the form fields being submitted
  2. Create the server request defined before (with the XMLHTTP connection info)
  3. Establish the "Content Type" or format in which the data is to be posted to the server
  4. 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:

  1. Request Sent
  2. Request Received
  3. Server Response Sent
  4. 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.

 


Posted on 1/29/2008 3:21:22 PM by Jovanky De Los Santos

About The Author: I am the founder of 9Searches.org. An SEO certified professional, MCSE, CCNA and manager of a technical support department at LexisNexis (US). I bring lots of experience in SEO and traffic management as well as web design and development.
Resource Recommended by Author: Internet at 9Searches
 

  Other articles in this category
  Writing Articles With Purpose on 9Searches.org
  Writing Content To Generate Search Engine Traffic
  RSS, XML, Aggregators, Syndication, News readers
  Social Bookmarking - WOW!
  Syndication vs. Duplicate Content - How can I avoid being penalized?
  Website Promotion - Fundamentals
  Search Engines - Types and Features
  How can my Web pages be indexed quicker?
  Search Engine Optimization as a Marketing Tool
  Social Bookmarking Tool
  Web Writing - Best Practices for Best Exposure
  Web Hosting For Profit
  Promoting your Site with a Structure
  Building Traffic without SEO
  Writing for the Web - What you need to know
  Three Rules for Making Money With adSense
  Writing For Traffic - Content For Visitors
  Link Authority, page rank, snow balls
  Wordpress Links Translate Big Time.
  About Link Directories Today
  Wanna Learn Ajax?

  Most Recent Articles by Jovanky De Los Santos
  Writing Articles With Purpose on 9Searches.org
  RSS, XML, Aggregators, Syndication, News readers
  Social Bookmarking - WOW!
  Inspire action with your Marketing or Sales copy
  Syndication vs. Duplicate Content - How can I avoid being penalized?
  Diabetes Diet - prevention and management
  Website Promotion - Fundamentals
  Search Engines - Types and Features
  How can my Web pages be indexed quicker?
  Search Engine Optimization as a Marketing Tool
  Social Bookmarking Tool
  Web Writing - Best Practices for Best Exposure
  Web Hosting For Profit
  Writing For Your Target Audience
  Promoting your Site with a Structure
  Building Traffic without SEO
  Writing for the Web - What you need to know
  Writing Effective Headlines
  Three Rules for Making Money With adSense
  Writing For Traffic - Content For Visitors
  Link Authority, page rank, snow balls
  Wordpress Links Translate Big Time.
  About Link Directories Today
  Wanna Learn Ajax?
  Lifestyle and Relationships Today

Bookmark this article:
                     Category RSS FeedWhat is RSS?


Rated: Not Rated
Comments for this article:

There are no comments for this article

 Name
  
 Your Feedback:
 
 How do you rate this author's work?
 

Code Image - Please contact webmaster if you have problems seeing this image code Load New Code
Powered by Web Wiz CAPTCHA version 3.0
Copyright ©2005-2007 Web Wiz