1

Have called another page through XMLHttpRequest. But the called page can't return JavaScript content.

In below code it's not returning addition of 5+7.

Have gone through various google stuff but nothing seems to be working.

it would be helpful if anyone could crack that....

request_xml.php

<!DOCTYPE html> <html> <body> <p id="demo">Here</p> <script> window.onload = function() { loadDoc(); }; 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", "call_page.php", true); xhttp.send(); } </script> </body> </html> 

call_page.php

<!DOCTYPE html> <html> <body> <p>why is js not working?</p> <script> document.write(5+7); </script> </body> </html> 

Edit:

JavaScript is working when page directly loaded

Also, JS working inside onclick in call_page.php

3
  • it's probably escaped, so it isn't parsed as <script>. please include a console.log() for this.responseText so we could see... Commented Jun 25, 2017 at 10:30
  • @vsync it's showing nothing on console Commented Jun 25, 2017 at 10:33
  • shows nothing? then roll up your sleeves and investigate :) Commented Jun 25, 2017 at 10:50

1 Answer 1

2

The JavaScript is loaded on page load by the browser. But here you're loading the page with AJAX, which just makes a HTTP request and returns the server's response. Since it's never loaded by browser's rendering engine, the JavaScript doesn't ever load.

You can try injecting the response into a dummy element created with document.createElement but most modern browsers won't allow you to execute JavaScript like that. So your best bet is to either find another loading vector or open that other page as a popup or an iframe.

Sign up to request clarification or add additional context in comments.

2 Comments

but inside onclick its working
Because that's a user initiated event. Browsers act differently based on if the event was user triggered (like onclick) or browser triggered (like onload).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.