Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing <script> injected by innerHTML after AJAX call

There's a div called "Content":

<div id="content"></div>

It should be filled with data from a PHP file, by AJAX, including a <script> tag. However, the script inside this tag is not being executed.

<div id="content"><!-- After AJAX loads the stuff that goes here -->
   <script type="text/javascript">
     //code
   </script>
   <!-- More stuff that DOES work here -->
</div>
like image 295
JCOC611 Avatar asked Jan 06 '11 20:01

JCOC611


People also ask

Can scripts be inserted with innerHTML?

For anyone still trying to do this, no, you can't inject a script using innerHTML , but it is possible to load a string into a script tag using a Blob and URL.

How do you execute a script tag?

The “script” tag JavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag. You can run the example by clicking the “Play” button in the right-top corner of the box above. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.

Can I add script tag inside div?

You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML.

How do I run a script in HTML?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.


4 Answers

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div
like image 68
Firas Nizam Avatar answered Oct 17 '22 22:10

Firas Nizam


JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.

like image 32
Chocula Avatar answered Oct 17 '22 21:10

Chocula


If you load a script block within your div via Ajax like this:

<div id="content">
    <script type="text/javascript">
    function myFunction() {
      //do something
    }
    myFunction();
    </script>
</div>

... it simply updates the DOM of your page, myFunction() does not necessarily get called.

You can use an Ajax callback method such as the one in jQuery's ajax() method to define what to execute when the request finishes.

What you are doing is different from loading a page with JavaScript included in it from the get-go (which does get executed).

An example of how to used the success callback and error callback after fetching some content:

  $.ajax({
    type: 'GET',
    url: 'response.php',
    timeout: 2000,
    success: function(data) {
      $("#content").html(data);
      myFunction();
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("error retrieving content");
    }

Another quick and dirty way is to use eval() to execute any script code that you've inserted as DOM text if you don't want to use jQuery or other library.

like image 15
Christopher Tokar Avatar answered Oct 17 '22 21:10

Christopher Tokar


Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

like image 11
Evgenii Avatar answered Oct 17 '22 21:10

Evgenii