Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 666
Noah Goodrich Avatar asked Nov 10 '08 15:11

Noah Goodrich


1 Answers

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.

like image 60
Diodeus - James MacFarlane Avatar answered Oct 24 '22 06:10

Diodeus - James MacFarlane