appa
appa

Reputation: 613

Rails 3.2.6 - .js.erb does nothing

I have a fairly simply demo app to learn AJAX / jQuery.

  1. In assets/javascripts/runner.js I have the following code:

    $(document).ready(function() {
        $.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;
    
        $.ajax({
            type: "POST",
        url: "http://localhost:3000/home/index",
            data: { name: "John", age: "35" },
            dataType: 'html'
        });
    }
    
  2. This correctly calls home/index, where I have the following code in the index action:

    respond_to do |format| format.js end

  3. This seems to correctly call index.js.erb, where I have:

    alert("hi");

  4. The problem is that the alert doesnt show up! I can see in the console of FireBug that I am getting "alert("hi")" correctly in the XHR response, but the alert doesnt execute!

Any help?

Upvotes: 0

Views: 263

Answers (1)

Wade Tandy
Wade Tandy

Reputation: 4144

You aren't actually processing the result fo your ajax call. The returned javascript never gets evaluated by the browser. It should be more like this:

$(document).ready(function() {
    $.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;

    $.ajax({
        type: "POST",
        url: "http://localhost:3000/home/index",
        data: { name: "John", age: "35" },
        dataType: 'html',
        success: function(data) {
            eval(data);  // where data is the javascript generated by home#index
        }
    });
}

Keep in mind that if someone is able to control the contents of this returned javascript, you could expose yourself to a nasty script injection vulnerability.

Upvotes: 1

Related Questions