Rails submitting a form through ajax and updating the view

前端 未结 4 505
青春惊慌失措
青春惊慌失措 2020-12-15 11:10

I want to update a form submit through ajax without reloading the page and update the view according to it. I tried the different methods and failed as i m new to rails.

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 12:15

    your code is good,but for ajax,

    1. you need to add remote=true to your form.

      <%= form_for(@image,:html=>{:id=>"your_form_id",:multipart => true,:remote=>true}) do |f |%>

    2. Moreover at your server side,you need to create a js.erb file in views/users/show_updated_view.js.erb to reply back to browser as its a js call and NOT html call and hence need to show the user that something happened(success/error) after form submission (if its users_controller),

    so inside your action,you need something like:-

            respond_to do |format|  
                format.js { render 'users/show_updated_view'}
            end  
    
    1. And in show_updated_view.js.erb,you should update your view for the users to know that the view has been updated or form has been successfully submitted by either hiding the entire form/resetting the form or replacing the form with new div saying that data is updated..or anything that is intuitive.There are many ways though :).

      //here i am replacing your entire form with div having a message

      $("#your_form_id").html("

      You have submitted the form successfully.

      ");

    The name of the view can be anything but you need to take care of both success and failure.

提交回复
热议问题