Where am I going wrong with my programming logic here?
I have 2 php files. File 1 includes File 2. File 1 calls a php function from File 2. Inside the php function there is a bunch of html. The html works perfectly. At the end of the function I have this javascript....
<script type="text/javascript">
alert('hello');
</script>
This javascript isn't alerting "hello". What am I doing wrong?
Thank you in advance.
EDIT: New question because I skrewed the last one up.
In theory would the code below run properly? (yes/no)
<?php function AlertHelp(){
?><script>
alert('help');
</script><?
AlertHelp();
?>
-
3can we see the other related code? how does the html souce llok like in the end?Joseph– Joseph2012年05月26日 20:36:50 +00:00Commented May 26, 2012 at 20:36
-
1yes, please. Use pastebin.com if necessary, and post the link back so we can help.pixeline– pixeline2012年05月26日 20:38:08 +00:00Commented May 26, 2012 at 20:38
-
Please consider adding a code which reproduces your problem. What you have described in your question is too generic and probably nobody could answer your question. Also point out if you're using any libraries - php/javascript?tftd– tftd2012年05月26日 20:40:38 +00:00Commented May 26, 2012 at 20:40
1 Answer 1
Long shot on a wild guess here with the limited information you gave.
My assumption is that you are not "including" the file via PHP's include, require, include_once or require_once functions, but are in fact using AJAX to load in the page's content.
If this is the case, then I shall also assume you're using innerHTML to put the content on the page.
Suddenly the solution is obvious: <script> tags added by innerHTML are not parsed and run. You could probably do something like this:
// assume `result` is the variable containing the AJAX response and `elem` the element it goes in
elem.innerHTML = result; // this doesn't change
result.match(/<script[^>]*>([\s\S]*?)<\/script>/i,function(m) {eval(m[1]);});
Please note however that eval should be avoided if possible. Consider redesigning your layout to use callbacks instead.
5 Comments
<?php function AlertHelp() {echo "<script>alert('help')</script>;} AlertHelp(); ?> but that only echoes the script to the browser, to be run when the page loads.