2

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.

1 Answers1

0

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');
SalmanAA
  • 552
  • 1
  • 6
  • 13
  • thank you for response but i m still not getting javascript alert from test2.php . Can you please provide me similar working example if posssible. – Neetesh Singh Sep 10 '16 at 06:07
  • in your javascript you must call loadDoc() function, after creating it. – SalmanAA Sep 10 '16 at 06:18
  • thanks a lot , it worked for me. my another question is can i get both javascipt alert and php echo statment together from test2.php for example : alert('hello user'); and php echo "username : sam" ?> like this. Thank you again for helping – Neetesh Singh Sep 10 '16 at 07:14
  • it is possible. there are many ways to do that. but one of them is to create your html and text data in test2.php script. for example you can use: `document.write("hello user");` before alert script – SalmanAA Sep 10 '16 at 07:40