Search code examples
javascriptjqueryruby-on-railsajaxruby-on-rails-2

Ajax is not defined on remote_form_for


I encountred an error on form submission. This form is defined as :

<% remote_form_for @my_object do |f| %>
  ...
<% end %>

The generated HTML is :

<form action="/my_objects" id="new_my_object" method="post"
   onsubmit="new Ajax.Request('/customers', {
      asynchronous:true,
      evalScripts:true,
      parameters:Form.serialize(this)
   }); return false;">
   ...
</form>

I encountred this JS error :

Uncaught ReferenceError: Ajax is not defined 

I read somewhere it's a Prototype error, but I don't understand the mistake I made.

My configuration is Rails 2.3.16, Ruby 1.8.6, jquery 1.9.1 and jquery-ui 1.10.2.


Solution

  • By default rails 2.x (and earlier versions), generate JS code for Prototype (cf javascript_helper and prototype_helper.

    To generate jQuery code in Rails 2.x, add jrails plugin for rails 2.x., and you will able to use the same rails helpers like remote_form_for or link_to_remote and jQuery.

    This part of jrails.js may be obsolete with jquery 1.9 :

    (function($) {
      $.ajaxSettings.accepts._default = "text/javascript, text/html, application/xml, text/xml, */*";
    })(jQuery);
    

    replace it by this code :

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) { 
      options.beforeSend = function () {
        jqXHR.setRequestHeader("accept", '*/*;q=0.5, ' + $.ajaxSettings.accepts.script);
        if ($.isFunction(originalOptions.beforeSend)) originalOptions.beforeSend();
      };
    });
    

    to have ajax request detection working in a controller :

    def my_action
      respond_to |format|
        format.js { ... }
        format.html { ... }
      end
    end