Page 1 of 1

diving into ajax

Posted: Thu Feb 22, 2007 2:49 am
by s.dot
I've read a couple of tutorials. And copy/pasted and then tinkered a simple working AJAX application.

Code: Select all

<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<script type="text/javascript">
function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}
function get_time(format)
{
	xmlHttp = GetXmlHttpObject();
	xmlHttp.onreadystatechange=stateChanged;
	
	if(format == 'regular')
	{
		xmlHttp.open("GET","time.php?rand="+Math.random(),true);
	} else if(format == 'formatted')
	{
		xmlHttp.open("GET","time.php?format=1&rand="+Math.random(),true);
	}
	
	xmlHttp.send(null);
}

function stateChanged() 
{ 
	var state = xmlHttp.readyState;
	if(state != 4)
	{
		document.getElementById("time").innerHTML = 'please wait while we process your request...';
	} else
	{
		document.getElementById("time").innerHTML = xmlHttp.responseText;
	}
} 

</script>
<a href="javascript:void(0);" onclick="get_time('regular');">click here to get the time</a><br />
<a href="javascript:void(0);" onclick="get_time('formatted');">click here to get the formatted time</a><br /><br /><br /><br /><br />
<div id="time" style="width:300px; height: 300px; background-color: #aeaeae; padding: 3px; text-align: center;"></div>
</body>
</html>
Is this pretty much all there is to ajax? Where does the XML come in?

Posted: Thu Feb 22, 2007 9:01 am
by TheMoose
The XML comes in if you want to have more than just plain text returned from your time.php page. You can use xmlHttp.responseXml to get an XML object and then parse through child nodes and the like to get the data pieces you want.

Posted: Thu Feb 22, 2007 10:32 am
by Kieran Huggins
Welcome to the chic world of [s]buzzw..[/s] ajax!

Now that you have a decent understanding of how it works, do yourself a favour and jump on the jQuery express bus:

Code: Select all

<a href="#" onclick="$('#time').load('time.php',{rand: Math.random()});">click here to get the time</a>
<a href="#" onclick="$('#time').load('time.php',{rand: Math.random(),format:'1'});">click here to get the formatted time</a>
<div id="time"/> 

Posted: Thu Feb 22, 2007 2:33 pm
by jyhm
Man you love that jquery, are you trying to sell it? :D

Posted: Thu Feb 22, 2007 2:38 pm
by Luke
I love it too... Kieran showed me the light.

Posted: Fri Feb 23, 2007 5:03 am
by Kieran Huggins
"jQuery sells itself, sweetheart! It chops, grates, slices, dices... twice as fast as any framework -- isn't that amazing? Act now!"
The Ninja Space Goat wrote:I love it too... Kieran showed me the light.
There's plenty of kool-aid for everyone, get your blue jumpsuits at the door.