Neetesh Singh Neetesh Singh - 3 months ago 21
Ajax Question

call script tag by using ajax

i am trying to call script alert using ajax for example

i have created two files
test1.php and test2.php

here is my code:

test1.php

Change Content

Let AJAX change this text



<script>

<pre><script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test2.php", true);
xhttp.send();
}
</script>


</pre>
</script>


test2.php

<pre>
<script>alert('hello');</script>

echo "Hello User";
</pre>


the problem is my script tag is not getting called by ajax and is showing blank response .
please need your help.
Thank You again.

Answer

easily, remove <script> and </script> from test2.php, then in test1.php change:

document.getElementById("demo").innerHTML = this.responseText;

to

eval(this.responseText);

here is full sample code:

test1.php:

<html>
<body>
<script>
function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            eval(this.responseText);
        }
    };

    xhttp.open("GET", "test2.php", true);
    xhttp.send();
}

loadDoc();
</script>
</body>
</html>

and test2.php:

alert('hello');