• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

AJAX for beginners ...

The advent of AJAX (Asynchronous Javascript and XML) has opened up new doors to web developers, allowing for interaction with and display of database and other external data in a web document, without the need to load a new page.

This is my tutorial for beginners wanting to use AJAX on their websites.

xmlHttpRequest

AJAX is made possible by a DOM API by the name of xmlHttpRequest, which allows HTTP or HTTPS requests to be initiated and handled from within Javascript.

Below is the function to place in your .js file for the current document.

function xmlRequest(){
 var xmlHttp=null;
 if (window.XMLHttpRequest) {
   // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlHttp=new XMLHttpRequest();
 }
 else if (window.ActiveXObject) {
  // code for IE6, IE5
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 } else {
  alert("Your browser does not support XMLHTTP!");
 }
 return xmlHttp;
}

Grabbing and Displaying a Record-set

Suppose you wanted to display data on your website that is updated every 10 seconds, showing a list of recent entries into a shout-out wall table, looking a bit like this:

Louis: Love the site!

Disregarding the process beyond the scope of this tutorial (of entering the data into the database), we will need to take these steps to achieve this outcome:
1. Write the query and output server-side script (php for this tutorial)
2. Write some javascript to request the server-side script, and output the response to a designated area of the site.

The Shout-out Table

In the database, we will have a table called “shoutouts” with the following structure:
soID(int,auto_increment),userName(varchar 50),shoutOutMsg(varchar 255)

The PHP script

The script below will show you how to query the database and output the results. The query uses a limit to display only the most recent shout-outs.

getShoutOuts.php

include "connect.php";
$sql="SELECT * FROM shoutouts ORDER BY soID DESC LIMIT 5";
$result=mysql_query($sql);
if (mysql_errno()){
 echo "ERROR|".mysql_error();
} else {
 echo "OK|";
 for ($row=mysql_fetch_assoc($result)){
  echo "<strong>".$row[userName]."</strong>: ".$row[ ishoutOutMsg]."";
 }
}

We use “ORDER BY soID DESC” to make the latest posts show up first, and “LIMIT 5″ to select the first 5 out of this reversed order set. The script then loops through each of the 5 records and outputs a row of html that displays the user name and message.

The HTML

We need a place within our document to put the shouts. You can create elements with javascript, but for beginners it may be easier to simply add a placeholder element in the source document. Either way, the element must have an ID that can be called upon later by the javascript function, looking like this:

The Javascript

Our Javascript will consist of a function that will request the data and subsequently insert it into the document. You should take note that the function called upon by this script “xmlRequest” was shown at the beginning of the tutorial.

function getShoutOuts(){
 var xmlObject=new xmlRequest();
 xmlObject.open("GET","getShoutOuts.php",true);
 xmlObject.send(null);
 xmlObject.onreadystatechange=function(){
  if (xmlObject.readyState==4){
   var returnString=xmlObject.responseText.split("|");
   if (returnString[0]=="OK"){
    //query was successful
    var returnedHTML=returnString[1];
    document.getElementById( ishoutContainer).innerHTML=returnedHTML;
   } else if (returnString[0]=="ERROR"){
    //query failed in php and reported an error
    alert(returnString[1]);
   }
  }
 }
 var t=setTimeout(getShoutOuts,10000);
}

Simply invoke the function getShoutOuts() on the loading of your document, and the 5 most recent shoutOut entries will be displayed on your page within the shoutContainer div element.

General note about the Ajax Request:

There’s a lot I could say about dealing with these AJAX requests, but something that is often not noticed when starting to use them, is that the onreadystatechange function you construct, will not execute until data is returned. So even though it is above the script below it, it will not execute before it but after it at some point undetermined because of the delay in communications.

What this means… is if you set a variable using data returned from an AJAX request, don’t expect it to be available until xmlObject.readyState==4 and the code within that has been executed.

 Original Source:
http://www.cloudwisp.net/programming/ajax-for-beginners/

AddThis Social Bookmark Button

Posted at 11:38:59 am | Permalink | Posted in Ajax  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Top Stuff

MessengerFX

e-messenger

ILoveIM

Top 20 Ruby CMS

eBuddy

MSN Web Messenger



About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (164)
  • Ajax (83)
  • Ajax Games (10)
  • Articles (95)
  • Bookmarking (35)
  • Calendar (20)
  • Chat (45)
  • ColdFusion (3)
  • CSS (75)
  • Email (23)
  • Facebook (83)
  • Flash (19)
  • Google (54)
  • Html (27)
  • Image (11)
  • International Calls & VOIP (7)
  • Java (54)
  • Javascript (266)
  • jQuery (159)
  • JSON (61)
  • Perl (2)
  • PHP (156)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (8)
  • Ruby (31)
  • Storage (4)
  • Toolkits (103)
  • Tutorials (217)
  • UI (11)
  • Utilities (174)
  • Web2.0 (18)
  • XmlHttpRequest (28)
  • YUI (12)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange