1

Whats wrong with this code or what might be causing this problem? It's not alerting "hello", but it is filling the div with The Hello and Bye World tables. I want it to alert "hello". Also I don't know jquery. Thank You

FILE1

var xmlhttp;
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){
     var reScript = /\<script.*?>(.*)<\/script>/mg;
     response = xmlhttp.responseText.replace(reScript, function(m,m1) {
     eval(m1);
     return "";
     });
    document.getElementById("div").innerHTML=response;
    }
  }
xmlhttp.open('GET','file2.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();

FILE2

  <table><tr><td>Hello World</td></tr></table>
  <script type="text/javascript">
  alert('hello');
  </script>
  <table><tr><td>Bye World</td></tr></table>
Rick Ryan
  • 125
  • 1
  • 13
  • What if you remove everything from `var reScript =` to `return ""; });`? – Fabrício Matté May 27 '12 at 02:08
  • If I did that and, assuming you want it to still load, replace response with xmlhttp.responseText. It still wouldn't run the javascript because scripts added through innerHTML won't execute. – Rick Ryan May 27 '12 at 02:15
  • Are you positive on that? All my scripts are added directly through HTML and it always worked. Give it a try, I'll remove my answer if it doesn't work. – Fabrício Matté May 27 '12 at 02:16
  • Are you using the actual HTMLDOM innerHTML attribute? I originally tried and just tested your answer, I'm only getting everything but the script. – Rick Ryan May 27 '12 at 02:19

2 Answers2

2

Try without the eval():

var xmlhttp;
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){
     /*var reScript = /\<script.*?>(.*)<\/script>/mg;
     response = xmlhttp.responseText.replace(reScript, function(m,m1) {
     eval(m1);
     return "";
     });*/
    document.getElementById("div").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //unnecessary for GET calls
xmlhttp.send(null);

Evaluing your code inside the <script...></script> is unnecessary, the javascript code will be executed as soon as it's added to the DOM.

New edit:

You have to eliminate the linebreaks \n\r in your reponseText in order for your script to be evaluated properly. Also, there was an extra \ escape character before the first < which was breaking your code. Try:

var xmlhttp;
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){
     var reScript = /<script.*?>(.*)<\/script>/mg;
     response = xmlhttp.responseText.replace(/\n|\r/g, " ").replace(reScript, function(m,m1) {
     eval(m1);
     return "";
     });
    document.getElementById("div").innerHTML=response;
    }
  }
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);

I've added a .replace(/\n|\r/g, " ") to replace all line breaks by an white space in your responseText, which will allow for your JS to be evaluated properly and cause no visible change to the end-user. You may also replace the white space " " by an empty string "" if all of your JS is properly semi-colon'd.

The above should work fine for simple scripts, now if you'd include the JQuery lib in your page's head:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Your AJAX call would be as simple as:

<script type="text/javascript">
$(document).ready(function(){
    $('#div').load('file2.php');
});
</script>

JQuery automatically parses scripts from your responseText, as noted in your linked answer.

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • If I did that and, assuming you want it to still load, replace response with xmlhttp.responseText. It still wouldn't run the javascript because scripts added through innerHTML won't execute. – Rick Ryan May 27 '12 at 02:16
  • I always execute JS echoed by PHP directly by adding it to the DOM from ajax calls like that in my applications. Did you try it yet? – Fabrício Matté May 27 '12 at 02:19
  • Try the code now, my previous example was missing the `response` var's definition. :) – Fabrício Matté May 27 '12 at 02:22
  • I just tried it one more time. Still not getting anything. If you have the time could you provide me with an example of one your scripts that is doing this effectily? – Rick Ryan May 27 '12 at 02:22
  • Most of them are a little too complex and involve JQuery, but I'll look for a simple one and post if I find any discrepancy. – Fabrício Matté May 27 '12 at 02:23
  • haha yeah I caught that when I tested it. But it doesn't work still. I've been stuck on this literally all day. AJAX is not one of my favorites. – Rick Ryan May 27 '12 at 02:24
  • Our comments are starting to run a little out of order here. Thank you Fabricio, I'd really appreciate it – Rick Ryan May 27 '12 at 02:26
  • 1
    Your AJAX function is using exactly the same structure as my older project, just that `xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');` isn't required for `GET` calls. And I have a `null` in the `xmlhttp.send(null);` but that shouldn't really matter. – Fabrício Matté May 27 '12 at 02:31
  • I just changed it to work just like yours but I just get the same response. This sucks. Thanks anyways Fabricio, I appreciate the help – Rick Ryan May 27 '12 at 02:37
  • I'd have a guess that the problem isn't in this piece of code then. There might be something else in your php or JS breaking the code. Which browser are you testing it with? You can check your browser's console for JS errors and your apache's error.log, or post a little more of your code. :P If you have firefox or chrome, you can also check the current page's source (firefox) or the DOM navigator in chrome to check if the script is being put in the page. – Fabrício Matté May 27 '12 at 02:39
  • Interesting, I'll sweep through all of my code for an error. Im testing it in chrome and IE. But wait, how can you check your browsers console for JS errors, or any errors? I had no idea that was even a thing – Rick Ryan May 27 '12 at 02:45
  • 1
    Firefox: Ctrl+Shift+K; Chrome/IE: F12 and select "Console" (chrome)/"Script" (IE) tab. :) – Fabrício Matté May 27 '12 at 02:46
  • Take a look at this page if you get the time. It says you have to use and eval http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml – Rick Ryan May 27 '12 at 02:47
  • 1
    That's from '09 but I see, even with or without evaluing, I still think that there's probably something else breaking the code. I'll check your regex. – Fabrício Matté May 27 '12 at 02:50
  • 1
    If you're still there, try my new code. :P Finally got it to work properly. – Fabrício Matté May 27 '12 at 03:31
  • WOOOOOOOOOOOO You did it Fabricio! It works!!! Thank you, I was stuck on that for an exceedingly long amount of time haha You just made my day. And Im glad you introduced me to JQuery as well, I had no idea it was that condensed. I will definitely be spending a lot of time studying that in the future. Thanks again – Rick Ryan May 27 '12 at 05:34
  • 1
    Yes, my first assumption that the script would be executed when added to the DOM was because the very first time I echoed a `script` in PHP to be fetched through AJAX was already using JQuery, so I wrongly assumed that standard JS Ajax would have the same effect. :P I learned a little more today too, you're welcome. :) – Fabrício Matté May 27 '12 at 06:04
0

Give this a try:

xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    var reScript = /<script.*?\>(.*)<\/script\>/mg.exec(xmlhttp.responseText)[1];
    var scriptElement = document.createElement('script');
    scriptElement.innerHTML = reScript;
    document.body.appendChild(scriptElement);
  }
}

Placing the code into a script element, and then appending that element to the body should cause it to execute.

Nimphious
  • 4,889
  • 1
  • 17
  • 17
  • Just tried it, the script is dieing somewhere in there. Im getting nothing from the ajax now. I also added an alert before document.body. and it's not firing. – Rick Ryan May 27 '12 at 02:43