Saturday, May 31, 2008

AJAX tutorial for begginers

So ajax is a buzz word around the whole web 2.0 scene. It stands for Asynchronous JavaScript And XML. Basically it's just using some javascript to call a function called xmlHttpRequest(); .Anyway it's usually some pretty standard not changing code which you can get from the W3CSchools. I have made some slight modifications, that I find make the AJAX code work a little better.
What I did was write a simple stupid recursive function(smarm, I had been reading to much QC that week) that has a wait in it and a header thing, which I had to put in there due to some weird IE thing I still don't quite understand.
So this ajax code only does one little thing, it prints a diffrent page in a div every 5 seconds. Now the reason you would do this is if you had ever changing data in that html/php file, you put in the div. You also need onLoad="smarm()" in the body tag.


function ajaxFunction()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById('stable').innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST","ajax2.php",true);
xmlHttp.send(null);
}
function smarm()
{
ajaxFunction();
var t=setTimeout("smarm()",5000);
http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
}



So like ajax2.php might look something like this:

$handle = fopen('info.txt', 'a+');
$shiznit = fread($handle,600);
fclose($handle);

Or you could dump a mysql database table into an html table if that database was changing a lot.

Yeah and don't forget to add the div, in my example the div I used was "stable". So to do that you would just add div brackets with a class and id named stable. Also make sure you put the javascript in script brackets and the php in php brackets of course.

One caveat is that unless the page you are inserting into the div is somehow otherwise linked to your site, the content within it most likely well not be viewed by a search engine. So if you are building SEO intensive sites, be aware.



No comments: