How to Force Javascript to Execute within HTML Response to Ajax Request

Noah Goodrich picture Noah Goodrich · Nov 10, 2008 · Viewed 28.1k times · Source

We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:

function ajaxModify(controller, parameters, div_id)
{
    var div = $(div_id);

    var request = new Ajax.Request 
    (
        controller, 
        {
            method: "post",
            parameters: parameters,
            onSuccess: function(data) {
                div.innerHTML = data.responseText;
            },
            onFailure: function() {
                div.innerHTML = "Information Temporarily Unavailable";  
            }
        }
    );
}

However, I occasionally need to execute Javascript within the HTML response and this method appears incapable of doing that.

I'm trying to keep the list of functions for Ajax calls to a minimum for a number of reasons so if there is a way to modify the existing function without breaking everywhere that it is currently being used or a way to modify the HTML response that will cause any embedded javascript to execute that would great.

By way of note, I've already tried adding "evalJS : 'force'" to the function to see what it would do and it didn't help things any.

Answer

Diodeus - James MacFarlane picture Diodeus - James MacFarlane · Nov 10, 2008

The parameter is:

evalScripts:true

Note that you should be using Ajax.Updater, not Ajax.Request

See: http://www.prototypejs.org/api/ajax/updater

Ajax.Request will only process JavaScript if the response headers are:

application/ecmascript, application/javascript, application/x-ecmascript, application/x-javascript, text/ecmascript, text/javascript, text/x-ecmascript, or text/x-javascript

Whereas Ajax.Updater will process JS is evalScripts:true is set. Ajax.Request is geared toward data transport, such as getting a JSON response.

Since you are updating HTML you should be using Ajax.Updater anyways.