Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript Ajax Function Problem

Status
Not open for further replies.

jjacquay712

Programmer
Dec 12, 2008
1
I have a javascript function that is supposed to return a number from a php script, but when i call the function, its value is undefined. here is the function:

(function to get xmlhttp variable not shown)

function latestid() {
xmlHttp.onreadystatechange=function(){
if( xmlHttp.readyState == 4 ) {
return xmlHttp.responseText;
}

}
xmlHttp.open("get",'ajax/latestid.php',true);
xmlHttp.send(null);
}

is there any problems you see in my code? or suggestions on why it isnt working? thanks, John Jacquay
 
Hi

No problem in that short code.

What you get if you request the ajax/latestid.php "manually" by typing it in your browser's location bar ?

If that is Ok, the next step would be to check the HTTP headers with an adequate tool :
[ul]
[li]Browser:
[ul]
[li]FireFox:
[ul]
[li]Live HTTP Headers[/li]
[li]FireBug[/li]
[li]Web Developer[/li]
[/ul]
[/li]
[li]Lynx[/li]
[li]Links[/li]
[li]W3M[/li]
[li]Explorer:
[ul]
[li]ieHTTPHeaders[/li]
[li]IEWatch[/li]
[/ul]
[/li]
[/ul]
[/li]
[li]tool:
[ul]
[li][tt]netcat[/tt][/li]
[li]PuTTY[/li]
[li][tt]telnet[/tt][/li]
[li][tt]Wget[/tt][/li]
[/ul]
[/li]
[/ul]

Feherke.
 
[1] Put all your functional script operating on the supposed return responseText into a function say, operate. As an example like this.
[tt]
function operate(s) { //s supposedly the responseText
//alert(s); //for instance
document.getElementById("xyz").innerHTML=s; //for instance
}
[/tt]
[2] Modify the latestid() to contain a boolean parameter. Initially, passing false say.
[tt]
function latestid_2(brecur) {
if (!brecur) {
xmlHttp.onreadystatechange=function(){
if( xmlHttp.readyState == 4 ) {
operate(xmlHttp.responseText);
}
}
xmlHttp.open("get",'ajax/latestid.php',true);
xmlHttp.send(null);
setTimeout("latestid_2(true)",200);
} else if (xmlHttp.readyState!=4) {
setTimeout("latestid_2(true)",200);
}
}
[/tt]
[3] Replace the latestid() by taking into consideration of [1], ie, moving all the functional lines depending on responseText to the function operate(s), and put instead at the place latestid_2(false). Like this.
[tt]
//document.getElementById("xyz").innerHTML=latestid();
//replaced by
latestid_2(false);
[/tt]
And the functionality should be more of less well-prepared and ready to go.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top