why
why

Reputation: 24851

Ajax can not work with Rails3.2.1

My form

<%= form_tag load_link_path, :remote => true, :html => { :'data-type' => 'html', :id => 'load_link_form' } do %>
<fieldset> 
    <%= url_field_tag(:url) %>
    <div class="validation-error"></div>
    <%= submit_tag %>
</fieldset>
<% end %>

My action

def load
  format.js 
end

My js view(load.js.erb)

alert(0);

When submit the form, alert isn't firing. The console outputs:

Processing by LinksController#load as JS
  Parameters: {"utf8"=>"✓", "commit"=>"Save changes", "url"=>"http://www.alfajango.com/blog/rails-3-remote-links-and-forms/", "authenticity_token"=>"KWwfZH+sivCrWdlVBUPM0MBRPHzcDhmbB96ckLQ82Dg="}
  Rendered links/load.js.erb (0.4ms)
Completed 200 OK in 2822ms (Views: 9.9ms | ActiveRecord: 0.0ms)

Upvotes: 1

Views: 292

Answers (1)

stephenmurdoch
stephenmurdoch

Reputation: 34613

Try adding respond_to at the top of your controller and then wrapping your format.js call in a respond_with block

class LinksController < ApplicationController
  respond_to :html, :js

  def load
    respond_with do |format|
      format.js
    end
  end
end

I'd recommend reading this article, it's the best guide to ajax with rails3 imo.

UPDATE:

I got it working after making a few small changes:

The default method for an ajax call in rails is "GET" so if you want to do a "POST", you need to include this with :data-method=>"post". I also removed the html hash from your form tag and set the data-type to script, see below:

<%= form_tag load_link_path, :remote => true, :id => 'create_link_form', :data => {:type=>"script", :"method"=>"post"} do %>

Also, you need to uncomment the alert from your js.erb file, so change from:

//alert(0);
$('#message').val('ok');

to:

alert(0);
//$('#message').val('ok');

Hope this helps, let me know if it doesn't and i'll push my code to github:)

Upvotes: 3

Related Questions