简体   繁体   中英

How do I get this Rails 3 AJAX (JQuery) post to respond properly to a successful save?

I'm having trouble with my very first AJAX + Rails 3 micro app. I haven't coded JS in about 10 years so I'm completely clueless with JQuery, etc.

Here is the method on the controller

def create
  @prospect = Prospect.new(params[:prospect])
  if @prospect.save
    logger.info "seems to save"
  else
    logger.info "does not save"
  end
  @prospects = Prospect.all
end

Here is the output from the log

Started POST "/prospects" for 127.0.0.1 at 2011-02-03 11:29:29 -0500
  Processing by ProspectsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"qzHvz5uBbmF8JIns1YAt4HlXyb34LWxbsIzZprnMeXM=", "email"=>"zach@zach.zach", "body"=>"here you go: ford.ca, america.com\n"}
does not save
  Prospect Load (0.7ms)  SELECT "prospects".* FROM "prospects"
Rendered prospects/create.js.erb (0.4ms)
Completed 200 OK in 93ms (Views: 23.7ms | ActiveRecord: 0.7ms)

Note two things: 1. "does not save" is outputted to the log 2. create.js.erb is rendered.

The first problem is that even though it logs "does not save" it in fact does save. I'm able to pull this information up on a separate page.

The second problem is that create.js.erb only has the following in it:

$(alert('in create');)

This alert does not happen.

So I must be doing something wrong in either my form, my AJAX request, or my create.js.erb. My form is:

<%= form_for(Prospect.create, :name => "pros", :remote => true) do |f| %>
    <%= f.label :email, "Your email (we'll be good)" %>
    <%= f.text_field :email, :name => "email" %>
    <%= f.label :body, "Your comment" %>
    <%= f.text_area :body, :name => "body" %>
    <%= image_submit_tag("signup.png", :id => "image_submit_button") %>
<% end %>

And my JS is:

$.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Accept", "text/javascript");
        },
            cache: false
            });


$(function() {
        $('#image_submit_button').click(function(){
                alert('yarrrrrrr');
                $.ajax({
                        data:
                        { prospect: {email: $("#prospect_email").val(), body: $("#prospect_body").val()} },
                            url: '/prospects',
                            type: 'POST',
                            dataType: 'json',
                            success: function(response)
                            {
                                // $('div-you-want-to-replace').replaceWith('<div>Holy shit dude, you are teh awesome</div>');   
                                alert('it works captian');
                            },
                            error: function(xhr, ajaxOptions, thrownError) {
                            alert('noooo');
                        }
                    });

            });
    });

Note that I do NOT get the alert "it works captain" from my AJAX POST, I get "nooooo". So I'm clearly doing something wrong there too.

So 3 questions:

  1. What should I do to make my controller realize that @prospect saves?
  2. What should I do to get create.js.erb to run when it does? (I assume this is where I should have a lightbox pop up thanking the prospect for their comments)
  3. What should I do to get my AJAX code not execute the error alert when there is a successful post that has happened?

Not sure if here is your problem but this code:

<%= form_for(Prospect.create, :name => "pros", :remote => true) do |f| %>

is already saving the prospect due the Prospect.create. Maybe you could put Prospect.new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM