0

Inserting JavaScript in the .innerHTML does not cause it to run.

I have what I call a mini-feed in which a user submits a post. This initiates an ajax call which saves the user data to the mysql table. From there PHP generates the xhtml. From there the the PHP generated xhtml is sent back to javascript as response text. This xhtml contains embedded javascript used to display "pretty time".

Now if the PHP generatd xhtml/javascript is send to the client in a non-ajax way this works. But when I send it as responseText and then update the DOM using .innerHTML it does not function. Whatever mechanism that picks up javacript with in the XHTML does not seem to like the embedded javascript written into the .innerHTML property of the enclosing div tag.

Is there an easy fix for this? Or do I have to construct the UI with in the javascript with out just inserting it all in as innerHTML...in a previous post someone mentioned that .innerHTML was not good practice. Perhaps this is what they meant.

Shog9
  • 156,901
  • 35
  • 231
  • 235

2 Answers2

3

You're right, innerHTML will not do that, if you want to dynamically create a script tag, you will need to use document.createElement to create a script tag, but that has all of the same wonderful security bonuses associated with eval.

Here's another idea, though. Wouldn't it be better to have some function defined in the main page which, after appending anything new, sets the date to "pretty" mode without needing to have the AJAX response know anything about it?

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
1

The following code should work:

function onSuccess() {
    src = document.createElement('script');
    src.innerHTML = this.responseText;
    document.body.appendChild(src);
}

But I would agree with cwallenpoole that why not have all that javascript code (for pretty-fying the date) be already written in advanced in the main page? (or script included or something).

Alexander Bird
  • 38,679
  • 42
  • 124
  • 159
  • @HiroProtagonist, unfortunately, I'm not sure what it is you want me to update. Could you elaberate what you want me to add/edit? Thanks. – Alexander Bird Jun 04 '12 at 01:29