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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.