Portal Home > Knowledgebase > Programming > AJAX for Beginners


AJAX for Beginners




Ajax for Beginners

What is Ajax?

So what is this fancy object that everybody wants a piece of? In brief, it's a solution to one of the big annoyances of web interfaces. Generally, the user inputs some data or makes a choice, and clicks a button that sends the data to the server. The server takes a look at the data and sends back a whole new web page, which is loaded into the browser. Reloading a page every time you want to do something is annoying, disjunctive and time-consuming for the user. XMLHttpRequest moves that browser-server interaction to behind the scenes, so the user can just keep on playing with the same page, even while elements on the page are talking to the server! Go take a look at Google Suggest if I've lost you -- it's a nice, eloquent example of this.

JavaScript has always been able to sneakily trigger a server-side script without anything happening in the browser by using a few classic tricks. This one, for example:onSubmit='runascript = new Image(); runascript.src="http://www.wired.com/images/archiveyscript.php?" + this.value'. That sort of chicanery is good, maybe, for caching form data to a file on the server, but it doesn't return any information to the JavaScript that calls it, so its usefulness is limited. Ajax, on the other hand, can get a full parcel of data back from the script it calls. Hence the "XML" part of the name - which really is just there for looks, kind of like the "Java" part of JavaScript, because the returned data can be plain text or whatever you like, if XML is overkill or just not your cup of tea.

This opens up millions of exciting possibilities. Every form submission, every JavaScript event, and heaven knows what else, can now interact with server-side databases and processing power. Data retrieval, password authentication, image generation - you name it, Ajax can trigger it.

Making Your Own

The potential of Ajax-enhanced web apps is limited only by your imagination - and by browser support. Mozilla-based browsers can do it, and Safari, and newer versions of Explorer, and Opera 8 but not Opera 7. It's best to incorporate a fallback way of doing things for users who aren't as cutting edge as you'd like them to be. Also, Explorer does things somewhat differently (of course) from all the other browsers, so it's necessary to fork the code to account for the irritating little 80-odd percent of the population who use IE.

Let's build a simple application that accepts input from the user, passes it to some PHP on the server that checks it against a database, and returns the result to the browser. It comes in three parts. First, we need an HTML form. This you've seen before:

<html>
<head>
<title>Report</title>
<script type='text/javascript' src='xhr.js'></script> </head> <body> <form action="fallbackpage.php" method="post">
<p>Welcome, student. Please enter your essay here:<textarea name="essay" id="essay">
</textarea> <input type="submit" name="submit" value="Submit" onClick="return
grade(this.form.essay.value);">
</p>
</form>
</body>
</html>

Note that, for users without support for our script (named xhr.js), the form will just submit to the fallback page at fallbackpage.php.

Next comes the JavaScript. This is the exciting part, so we'll take it slow.

function grade(essay) {

First, we initialize the object. We have to do it two ways, for different browsers.

// Mozilla version
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
// IE version
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

Then, we escape the user input to make it URL-safe:

essay=encodeURIComponent(essay);

and use the open method of the object to open a connection to the PHP script:

xhr.open("POST","grade.php");

The method requires two arguments:first, the HTTP method (GET or POST); second, the URL of the script.

A quick HTTP header prepares the script for what it's getting, and then the send method transmits the actual request:

xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay);

This last step isn't necessary for GET requests, wherein all the data can be contained in the query string of the URL.

Getting Results

Now we're ready to see if the HTTP request worked. The readyState property counts up from zero during the request, and shows 4 when the server page has loaded successfully.

xhr.onreadystatechange=function() {
if (xhr.readyState==4) {

If the request worked, then we can get the output of the server-side script by querying the responseText property, which contains a string. For more complex server script output, a responseXML property, which can hold a full document object of XML data, is also available.

grade = xhr.responseText;
alert ("Nice essay. Your grade is " + grade);
}
return false;
}

Want to see all that in a pastable block? Here it is in a separate file.

Finally, the third component is the PHP script, which lives on the server and waits patiently for the JavaScript to pass it some juicy data. This example uses PHP, but any language you like -- Ruby, Perl, C, ASP -- can do as well. The core of this example script is a natural-language function called grade_essay() that grades student essays from 1 to 100, but I will redact that part to conserve space.

function grade_essay($essay) {
return strlen($essay);
}
$essay = urldecode(implode(file('php://input')));
$grade = grade_essay($essay);
echo $grade;
?>

The php://input grabs the POST data, which gets put into a string, decoded and passed to the ingenious grading algorithm. The algorithm returns a numeric grade. Lastly, we just output the grade with echo - ordinarily, this would display in the browser, but since the PHP script is running "behind the scenes," the string output is simply returned to the JavaScript that called it. If you need structured data, an XML document would be output with an echo statement in just the same way, but the content-type of the output page must be set to text/xml.

What the user sees is this:She types her essay into the text area in the browser, clicks Submit, and within instants an alert box pops up giving her a final grade on the essay. Invisibly, the essay has been sent to the server, read and evaluated by a team of PHP gnomes, and returned with a grade, without ever reloading the page. The user can modify her essay and resubmit it endlessly.

And that's the gist of the almost magical XMLHttpRequest object! The example is simple, but the uses of the object can be elaborately, multifariously clever. If you need further inspiration and edification, a burgeoning number of examples are dotted around the Web:

  • Social news site Digg


But what data you send and receive with Ajax is up to you.

 

Article Source: http://www.webmonkey.com/tutorial/Ajax_for_Beginners




Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read