Category Archives: JavaScript

Executing embedded JavaScript after Ajax-call

A nasty problem jumped up and bit me in the ass a few days ago at work. I was making a widget of a piece of code formerly part of the web page now hosting the widget. The widget code consisted of some HTML and a couple of embedded JavaScript tags. The widget needed to be loaded into a div the hosting web page with an Ajax-call, after which the embedded JavaScript needed to be executed. Something like this (I’m using YUI3 here):

Y.io("/foo/bar/some_widget", {
  method: 'GET',
  on: {
    complete: function(id, respdata) {
      thediv.innerHTML = respdata.responseText;
      initWidget(); // this function is embedded in the responseText
                    // and doesn't get evaluated. I.e. it doesn't exist.
    },
    failure: function(id, respdata) {
      alert('Feed failed to load!');
    }
  }
});

If a search engine sent you here, you probably know that this doesn’t work. JavaScript embedded in a piece of HTML code loaded with Ajax and injected in a web page doesn’t get evaluated. If you’re wondering why, you’re in the wrong place. If you want to know how to make it execute, read on.

Continue reading

5 Comments

Filed under Geek speak, JavaScript