简体   繁体   中英

Rails responding to different formats with AJAX request

I'm trying to understand AJAX requests in Rails. I have a form that I currently submit using remote: true. I want to respond with an HTML redirect if the request is successful, and run an error message with Javascript if it is unsuccessful. However, no matter what the outcome is, the request seems to expect a .html as the return.

respond_to do |format|
  if conversation
    format.html { redirect_to(conversation_path(conversation)) }
  else
    format.js
  end
end

This is called after I save the conversation call on AJAX. On a successful save, the path HTML is correctly sent back, but is not rendered on the client. But on an unsuccessful save, it expects the .html and throws an error. How do I accept .js as a response? My goal is to just pop up an error if the call is unsuccessful and redirect_to on a successful call.

Edit: My form_for:

<%= form_for :conversation, url: :conversations, remote: true, html: { class: "conversation-form" } do |f| %>

Here's a suggested alternative to your end-goal - in the controller, drop the format.html entry in your respond_to block. Also, set conversation to an instance variable that the view template can access:

class YourController < ActionController::Base
  def your_action
    # awesome code doing stuff with a conversation object goes here

    @conversation = conversation

    respond_to do |format|
      format.js # your_action.js.erb
    end
  end
end

Then, put the redirect logic in your javascript view template (for the above example: app/views/.../your_action.js.erb ):

<% if @conversation.errors.any? # or whatever condition you want to show a popup for %>

  // put your javascript popup code here
  alert('Errors happened!');

<% else %>

  // this is how you do a redirect using javascript:
  window.location.href = "<%= conversation_path( @conversation ) %>";

<% end %>

Hope this helps!

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