ingh.am
ingh.am

Reputation: 26742

Running javascript in a page loaded by xmlhttprequest

In my javascript method I'm calling a xmlhttprequest to grab some data and display it in a div called 'myDiv' (index.php)

function combo_change(theid)
{
  if (window.XMLHttpRequest)
  { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange=function()
  {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","anotherpage.php?id=" + theid,true);
  xmlhttp.send();
}

Now, I'm trying to call some javascript within the page "anotherpage.php", but it does not want to work. As a test I'm just doing a document.write('hello');. If I load the page directly it will show, but when using the code via xmlhttp open it will not.

I can assume that when loading like this, the javascript is not being run. So, is there anyway I can make it run?

Upvotes: 0

Views: 2761

Answers (2)

Have a look at this: http://zeta-puppis.com/2007/05/27/javascript-script-execution-in-innerhtml-another-round/

Short version: document.write() has issues, try alert() instead to see if your script runs.

Upvotes: 1

Sandeep Manne
Sandeep Manne

Reputation: 6092

Write your JavaScript code inside

if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
  document.getElementById(\"myDiv\").innerHTML=xmlhttp.responseText;
  //Your js code 
}

Upvotes: 2

Related Questions