简体   繁体   中英

How to submit form via ajax using rails bootstrap modal

I followed the tutorial here to add ajax form to my rails app. Everything works except I don't get error messages on invalid form. When I inspect google chrome console I get

Uncaught SyntaxError: Unexpected token :   
   at processResponse (rails-ujs.self-661556f….js?body=1:246)
   at rails-ujs.self-661556f….js?body=1:173
   at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-661556f….js?body=1:230)

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)

Uncaught SyntaxError: Unexpected token :
   at processResponse (rails-ujs.self-661556f….js?body=1:246)
   at rails-ujs.self-661556f….js?body=1:173
   at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-661556f….js?body=1:230) 

POST http://localhost:3000/people 422 (Unprocessable Entity) 

I think it is related to unexpected response format from the server because you render json with format.js

I suggest that you move your script that handle errors to a file called app/views/people/create_errors.js.erb and add the following line to it, instead of binding ajaxError event in app/assets/javascripts/people.js

$('form#new_person').render_form_errors(<%= @person.errors.to_json.html_safe %>);

In app/controllers/people_controller.rb change create method to:

def create
@person = Person.new(person_params)

respond_to do |format|
  if @person.save
    format.html { redirect_to @person, notice: 'Person was successfully created.' }
    format.json { render action: 'show', status: :created, location: @person }
    # added:
    format.js   { render action: 'show', status: :created, location: @person }
  else
    format.html { render action: 'new' }
    format.json { render json: @person.errors, status: :unprocessable_entity }
    # added:
    format.js   { render 'create_errors', status: :unprocessable_entity }
  end
end

end

I hope this solve your issue.

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