Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript from ajax doesn't get proper execution

Using Ajax, I've created a sort of console that allows me to execute some PHP functions dynamically.

It looks like this screenshot

The problem is that after a bunch of commands, the console becomes hard to read. So I've created a javascript function, named "wipe();", which clears the <div> containing the console.

I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.

But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.

I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a <script>function</script> from another <script></script> block.

So why is it failing to do that ?

here is the php code :

    echo '<script>wipe();</script>';

and here is the the first <script> block:

        var xmlhttp = new XMLHttpRequest();
        var span = document.getElementById("screen");

     function send(data) {
        window.setInterval(function() {
        var elem = document.getElementById('screen');
           xmlhttp = new XMLHttpRequest();
           xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
           xmlhttp.onloadend = function() {
             span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
           }
           xmlhttp.send();
         }

    function wipe(){
             span.innerHTML = '';
        }
like image 524
Rackover Avatar asked Nov 08 '22 08:11

Rackover


1 Answers

To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a <script> tag inserted via innerHTML should not execute.

A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.

var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");

function send(data) {
  window.setInterval(function() {
      var elem = document.getElementById('screen');
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
      xmlhttp.onloadend = function() {
        span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
        evalJSFromHtml(span.innerHTML);
      }
      xmlhttp.send();
    }

    function wipe() {
      span.innerHTML = '';
    }

    function evalJSFromHtml(html) {
      var newElement = document.createElement('div');
      newElement.innerHTML = html;

      var scripts = newElement.getElementsByTagName("script");
      for (var i = 0; i < scripts.length; ++i) {
        var script = scripts[i];
        eval(script.innerHTML);
      }
    }

  }
like image 95
Vladu Ionut Avatar answered Nov 14 '22 23:11

Vladu Ionut