Forum Moderators: open

Message Too Old, No Replies

ajax doesn't work 1st time round but works second time?

         

fintan

2:52 pm on Jun 7, 2006 (gmt 0)

10+ Year Member



Hi I have a js lib which does all of my ajax stuff. It does work but only the second time it's called. The first time returns a header and the content but doesn't print it out to the screen. Can anyone see where I'm going wrong? Here's my code

Ajax stuff

/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/

if(!xmlHttp && typeof XMLHttpRequest!= 'undefined'){
xmlHttp = new XMLHttpRequest();
}

function callServer(what_method, url, urlvar, dynamic_function) {

var url = url + urlvar;

// Open a connection to the server
if(what_method == true){
// Get
xmlHttp.open("GET", url, true);
// Get

// Send the request
xmlHttp.send(null);
}
else{
// Post
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlHttp.send(urlvar);
// Post
}

// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = dynamic_function;

}

Dynamic function

function loadCallList(){

if(xmlHttp.readyState == 4) {
var HTMLResponse = xmlHttp.responseText;
document.getElementById("content").innerHTML = HTMLResponse;
}
}

Calling the function

callServer(false, 'utils/listcalls.php', '', loadCallList());

jshanman

5:32 pm on Jun 7, 2006 (gmt 0)

10+ Year Member



callServer(false, 'utils/listcalls.php', '', loadCallList());

if you send loadCallList with (), you are actually sending the returned value of the function(which is this case is null), not a pointer to the function.

Change the function call to this:
callServer(false, 'utils/listcalls.php', '', loadCallList);

- JS

fintan

10:13 am on Jun 8, 2006 (gmt 0)

10+ Year Member



Thanks jshanman worked like a charm. Just one more thing how would I go about passing a function like this?

function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
updateCall(id);
}
}
}

so the above function would be dynamic_function. Thanks again

fintan.

jshanman

12:49 pm on Jun 8, 2006 (gmt 0)

10+ Year Member



callServer(false, 'utils/listcalls.php', '', function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200) updateCall(id);
}
});

now whenever you call "callServer", it will run the anonyomous function with whatever the current value if "id" is at the time callServer is run. id can also be a local variable, it will still see the value.

- JS

fintan

1:09 pm on Jun 8, 2006 (gmt 0)

10+ Year Member



Class, thanks you've been a great help.

fintan.