PDA

View Full Version : Calling content with AJAX


Nykac
12-05-2009, 09:30 AM
Dear Ajax-users,

I'm using this very basic ajax function, to call certain content when clicking on certain hyperlinks. A similar idea is already up and running on another website, but this time is seems not wanting to work! For three days I'm struggling with this simple matter, and it's getting a little anoyed right now, as I'm getting behind schedule :) The code is as follows, I hope you can help me out! Thanks in advance..

Nykac

HTML

In the HEAD tag I'm calling the JavaScript
<script type="text/javascript" src="file.js"></script>

Somewhere in the body I inserted the hyperlinks (as example 1):
<a href="#" onclick="select('1a')"><img src="thumb/1a.jpg" /></a>

Finally the box where the new content should load without refreshing the page:

<div id="show">box</div>

At last but not least, the famous JS code is as follows:
var xmlHttp

function select(str)
{
if (str.length==0)
{
document.getElementById("show").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="file.php";
url=url+"?q="+str;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("show").innerHTML=xmlHttp.responseText;
}
}

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;
}

hdewantara
12-08-2009, 10:26 AM
Add xmlHttp.status==200 check in stateChanged() function,
but that's minor. I don't see anything wrong with your script.

And perhaps error was caused by your file.php? Or perhaps you have forgotten to declare your HTML page version info? Did your browser show you about any errors?

Regards,
Hendra.