Jump to content

Ajax Question


henryhenry

Recommended Posts

Have a question about Ajax.I'm just learning from the w3schools example - interacting witha php page. The php page checks the DB and returns 'none' or 'inline' to display a message to the user.I also want to change some other things and I have the variables 'b' and 'c' set already. The trouble is I can't pass them into the stateChanged function. I don't really understand why it doesn't have the '()' after it in the example. I tried adding it but this breaks the Ajax mechanism somehow.Can anyone help me out?Thanks!!!Here's the java script:

function showUser(a, b, c) {  xmlHttp=GetXmlHttpObject()  if (xmlHttp==null) {	alert ("Browser does not support HTTP Request")	return  }  var url="./lib/ajax.php";  url=url+"?q="+a;  url=url+"&sid="+Math.random();  xmlHttp.onreadystatechange=stateChanged; // w3schools has it like this  // xmlHttp.onreadystatechange=stateChanged(b, c); // I want to pass two variables like this  xmlHttp.open("GET",url,true);  xmlHttp.send(null);}function stateChanged(b, c) {  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {	document.getElementById("ajaxTxt").style.display=xmlHttp.responseText;	if (xmlHttp.responseText=='inline') { 	  //do stuff with b and c	}  }}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;}

Link to comment
Share on other sites

Well I managed to find a work around - I just got the variables another way within the stateChanged function itself but it would be great if anyone understands the reason the parenthesis aren't there on the xmlHttp.onreadystatechange=stateChanged line. Any ideas greatly appreciated!ThanksHenry

Link to comment
Share on other sites

That's how event handling works in javascript - rather than calling the function (with the parentheses), you pass what is called a reference to that function (without the parentheses).It's really similar to a variable. The difference is that rather than passing a simple value, you are passing (a reference to) all the code that makes up a function. Take the following example:

function someFunction(text){	alert(text);}

Now, to call that function, you would simply do "someFunction('Here is some text.')". But, you can also pass a reference to that function to other java script:

alert(someFunction);

Or as a parameter to a function which then calls it:

function someOtherFunction(text, func){	// "func" is a function reference that we pass as a parameter	// we can call it like this:	func(text);}someOtherFunction('Here is some text.', someFunction);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...