Alert() from an Ajax loaded page?

If you want to make sure JavaScript added to the page and runs then
simply add the script tag to the page directly from the JavaScript (no
ajax call required).

I removed the html and body tag information. Good call on this.

Would you mind giving me an example of how I might do that in this specific case. I’m a real Javascript noob and struggle even with the terminology.

  1. Remove everything from test2.php except for:
alert(test);
  1. rename test2.php to test2.js

  2. Use the following JavaScript to add that script to the page:

var addJS = function(nm) {
  var s = document.createElement('script');
  s.type='text/javascript';
  s.src=nm;
  document.getElementsByTagName('body')[0].appendChild(s);
}

addJS('test2.js');

When that addJS() call runs the script will be added to the page and then run.

1 Like

Oh I see what you mean.

I actually need the script to run some php so I can’t just use JS like that. I’m just keeping my example script simple to figure out how to run javascript from an ajax loaded script.

Sorry if I wasn’t clear. Do you know how to achieve this result?

Don’t use innerHTML to add the content after you retrieve it from the server.

If you add the content using the JavaScript Document Object Model then any scripts you add will then be able to run.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.