Evaluating the javascript code returned by AJAX (Prototype)

This Article address the common problem with AJAX calls, when AJAX response contains the javascript functions along with HTML.

Problem Description: Javascript Returned by AJAX response doesn't work.

Problem Cause: When any web page loads in to the browser , all javascript on that page gets loaded by browser and you can only call the javascript functions that is already loaded.

Problem Solution: You can handle this scenarios in multiple ways but choose whichever is most suitable for you

Approach 1:  If your AJAX response contains only the javascript functions you can use the java script "eval" method to run the scripts return by the AJAX response .




Ex: simply call eval(document.getElementById('divID').innerHTML);


But if your AJAX response contains both HTML and Javascript , you need to parse the response and find out the <script> blocks and do eval on that.

Ex: Assume your ajax response will replace a div then put your response in a div or something and use the div id to grab the tag with a name = to script


divID.getElementByTagName("script")
loop through them and run
eval(script.innerHTML);


Approach 2: another way to do this use  Prototype AJAX.update method call to evaluate your javascript functions.


Example :
new Ajax.Updater(divID,URL,{asynchronous:true,evalScripts: true});


divID = innerHTML of this divID get replaces with AJAX response
URL =  server side URL to handle the AJAX response
evalScripts = true means it evaluates the script elements inside the AJAX response

If you use evalScripts: true, any <script> block will be evaluated. This does not mean it will get included in the page: they won't. Their content will simply be passed to the native eval() function. There are two consequences to this:
  • The local scope will be that of Prototype's internal processing function. Anything in your script declared with var will be discarded momentarily after evaluation, and at any rate will be invisible to the remainder of the page scripts.
  • If you define functions in there, you need to actually create them, otherwise they won't be accessible to the remainder of the page scripts. That is, the following code won't work:
// This kind of script won't work if processed by Ajax.Updater:function coolFunc() {
  // Amazing stuff!}

You will need to use the following syntax:
 // This kind of script WILL works if processed by Ajax.Updater:
coolFunc = function() {
  // Amazing stuff!}

Click Here for more detail on Prototype AJAX update function
 


No comments:

Post a Comment