0

I have a php file that echos an HTML with <script> element. like this:

<div>
    <button onclick="FunctionName();">Click Me</button>
</div>
<script type="text/javascript" id="script1">
    function FunctionName() {
         /* block of code here */
    }
</script>
<script type="text/javascript" id="script2">
     alert("working")
</script>

I'm inserting this code in via innerHTML method. However, I figured out that the DOM inserted <script> tag doesn't get executed unless you call it like this:

eval(document.getElementById('script1').innerHTML);
eval(document.getElementById('script2').innerHTML);

Now the problem is: the script2 is executing and it is doing an alert that says: "working", but when I click the button the console returns this error:

Uncaught ReferenceError: FunctionName is not defined

And the weird part is when I copy/paste the same JavaScript Code, put it inside an eval(); and enter it in the console, it works perfectly!

so why is that happening and how to solve it?

Alex C.
  • 4,021
  • 4
  • 21
  • 24

2 Answers2

0

This jsFiddle works perfectly with the code you have. But I can see it causing problems if you append it after the page is created, since inline scripts are not executed when appended after the page is done loading.

If you append it, refer to this post for a similar problem if you need to have it inside the html. I would however recommend using jQuery getScript instead of normal ajax, if you can move your scripts into a different file.

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
    // ...
});
Community
  • 1
  • 1
Robin
  • 1,251
  • 11
  • 18
  • Robin, I'm not sure if I can pass some variables through `$.getScript()` because I want to get the code according to the variables I pass through the POST method. – Alex C. Apr 30 '15 at 14:12
  • I'm not exactly sure what you are doing, so it's hard to for me to propose a solution. If you have the variables in the html and retrieve a script with ajax, which I assume means you will still be on the same page, you could just retrieve the variables from the forms(or wherever they are) using [jQuery val()](http://api.jquery.com/val/) from within the scripts? – Robin Apr 30 '15 at 14:16
  • yes, I'm doing so, but then I want those variables go to a PHP file. like if a user selected "a" will get a different javascript code from a user who selected "b".. and those codes has to be served from a PHP server side through ajax. – Alex C. Apr 30 '15 at 15:03
-1

I think the problem is that when the click event listener is stablished, your function isn't created yet.

Try putting your script1 before the div which has the onClick event.

Bardo
  • 2,470
  • 2
  • 24
  • 42