Jump to content

[SOLVED] Problem using responseText in different <div>s


Michan

Recommended Posts

Hi,

 

I'm stuck on a bit of code. I have more than one <div>, and depending on which "comic" you choose, I'd like to load content into the specified <div>.

 

How would I get about doing it? The code pretty much explains itself below.

 

<script type="text/javascript">

	var xmlHttp

	function selectcomic(str,div)
	{ 
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	  {
	  alert ("Your browser does not support AJAX!");
	  return;
	  } 
	var url="comics.php";
	url=url+"?getresult="+str;
	xmlHttp.onreadystatechange=stateChanged(div);
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	}

	function stateChanged(div) 
	{ 
	if (xmlHttp.readyState==4)
	{ 
	document.getElementById(div).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;
	}

	</script>

Comic: <a href="" onclick="selectcomic(\'1\',\'div1\'); return false">Comic 1</a> <a href="" onclick="selectcomic(\'2\',\'div2\'); return false">Comic 2</a> <a href="" onclick="selectcomic(\'3\',\'div3\'); return false">Comic 3</a>

<div id="div1">None selected!</div>
<div id="div2">None selected!</div>
<div id="div3">None selected!</div>

 

Thanks in advance!

Wrong:

xmlHttp.onreadystatechange=stateChanged(div);

 

That line is assigning the return value of stateChanged(div), not assigning the function to the handler.

 

Right:

xmlHttp.onreadystatechange=stateChanged;

 

Notice the problem?

You cannot pass variables this way.

 

Try this:

xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4){ 
document.getElementById(div).innerHTML=xmlHttp.responseText;
}
};

 

This way you are assigning the code itself as a function type property (or something like that) and still within the scope of the selectcomic function.

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.