...

View Full Version : Using Ajax with onClick issues



howesy
01-13-2009, 10:59 PM
I'm calling an Ajax function with an onClick command (sorry if some of this terminology is wrong) but it returns the previous querys results.

For instance when you load the page and click the button for 'item 1' it shows nothing, click again for 'item 1' and it shows. If I then click the button for 'Item 2' it shows the results for 'item 1' but if I click again it the shows the results for 'item 2'. - Still with me...

I'm calling a javascript function called show_comments with my onClick, please see below.

The code is:

xmlHttp = GetXmlHttpObject();
function show_comments(mystr)
{
if (xmlHttp == null)
{
alert ("Yo browser is rubbish man! Upgrade it");
return;
}
var url = "getnewscomments.php";
url+="?q="+mystr;

xmlHttp.onreadystatechange=stateChanged(mystr);
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} //end function showcomments

function stateChanged(mystr,mystr1)
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
txtloc = "comments" + mystr;
document.getElementById(txtloc).innerHTML = xmlHttp.responseText;
}
} //end function stateChanged

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;
} //end function GetXmlHttpObject


Any help qould be appreciated. Thanks.

rangana
01-14-2009, 05:55 AM
Try to change this part:


xmlHttp.onreadystatechange=stateChanged(mystr);


into:


xmlHttp.onreadystatechange=function(){
stateChanged(mystr);
}

howesy
01-14-2009, 11:44 PM
Perfect, thanks for the help!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum