"Simplicity is the ultimate sophistication." - Leonardo da Vinci

How do I execute scripts in the content retrieved using Ajax?

Ajax enables Web application developers to build highly responsive Web interfaces. Ajax also comes with a lot headaches. One such problem arises when the content returned by an Ajax call contains JavaScript. By default this script won’t be executed by the browser and any JavaScript functions in the Ajax content won’t be available to the main page.

So how to execute JavaScript in the Ajax content?

When you use Ajax, you first make an asynchronous call to server and the content returned is then assigned to a div tag using the innerHTML property as shown below.

document.getElementById("divId").innerHTML = ajaxContent;

In order to execute scripts inside the variable “ajaxContent”, we need to extract the script blocks and then pass to the JavaScript engine. So we will rewrite the above as follows,

setAjaxContent("divId", ajaxContent);

Here is the pseudocode for the setAjaxContent method,

1. Extract JavaScript method block by scanning for <script> tag.

2. Pass the JavaScript method block to browser JS engine by calling eval method.

3. Set the Ajax content to the div tag using innerHTML property.

function setAjaxContent(divId, html) { 
  var temp = html;
  while(true) {
    var sindex = temp.indexOf("<script"+">");
    if(sindex < 0) break;
    var eindex = temp.indexOf("</"+"script>",sindex);
    var js = temp.substring(sindex+8,eindex);           
    eval(js);
    temp = temp.substring(eindex+9);
  }     
  document.getElementById(divId).innerHTML=html; 
}

The above code scans for <script> blocks and then passes the script block to JavaScript engine using eval(). Finally the content is added to the innerHTML of the div you want to refresh.

This assumes that all the JavaScript’s in the content retrieved by Ajax is inside <script> and </script> tags (without spaces or other attributes). For example, you will have to modify the function if you have the starting script tag as <script type=”text/javascript” >.

April 27, 2008 | Posted in JavaScript

Related Articles

  1. Getting started with Ajax - build your own smallest ajax framework
  2. Creating a Website menu using unordered list and CSS
  3. Confirm closing of browser window using onbeforeunload

Leave a Comment


Got any comments/queries about this article? You can post them above and I will get back to you. You can also subscribe to the RSS feed to get latest updates on this site. Got a good coding tip? Send it to me with your name and I will publish it here.