简体   繁体   中英

Rails Application sending HTML responses instead of JS

I have a standard rails application. I am trying to perform simple AJAX for adding an object. The code is code that I've used before so I'm hoping there is something I'm just doing wrong in this instance.

Anyway, I am trying to upload document using carrierwave .

My controller action looks like this:

documents_controller

def create
  @document = @user.documents.build(document_params)
  @document.user_id = @user.id
  @result = @document.save
  if @result
    respond_to do |format|
      format.js
      format.html { raise "submitted as html" }
    end
  else
    render :back
  end
end

My document.html.erb layout.

<!DOCTYPE html>
<html class="backend">
  <head>
    <%= javascript_include_tag 'documents' %>
    <%= csrf_meta_tags %>

    <%= render 'shared/fonts'%>
    <%= render 'shared/css'%>

  </head>
  <body>
    <%= yield %>
  </body>
</html>

And documents.js file.

//= require jquery
//= require jquery_ujs
//= require jquery.validate.min
//= require validation

A test for JQuery on the documents/index.html.erb view.

<script>
  if (typeof jQuery != 'undefined') {
    alert("jQuery library is loaded!");
  }else{
    alert("jQuery library is not found!");
  }
</script>

And lastly, the documents/create.js.erb file.

$('#document-table > tbody').append('<%= j render(@document) %>');
$('#document-table > tbody').append('<%= j render 'documents/share', document: @document %>');
$('#document-form')[0].reset()
$('#edit_document_<%= @document.id %>').submit();

The form:

<%= form_for [@user, @document], html: {id: 'document-form', data: {remote: true}} do |f| %>
  <%= f.text_field :name, class: "form-control" %>
  <%= f.text_area :description, class: "form-control" %>
  <%= f.file_field :file %>

  <%= button_tag class: "btn btn-primary pull-right" do %>
    <i class="ico-file-upload2 text-white mr5"></i> Upload Document 
  <% end %>
<% end %>

The document table and document form are ids I've given to those objects. I don't think there is anything irregular about any of this --- and it works on other sites, but when I click submit, the response is:

Processing by DocumentsController#create as HTML

Let me know if there is anything I could missing.

Use :remote => true outside html option, try below one

form_for [@user, @document], :remote => true, html: {id: 'document-form'} do |f| %>

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