Search code examples
javascriptruby-on-railsruby-on-rails-4google-earth

Rails: submitting a form without reloading the page


My app (https://showthatview.herokuapp.com/) has two parts:

  • A Google Earth pane, where a view is shown
  • A form, where the user sets the address / height where he wants the camera to be set

When the user submits the form, I want the RoR back end to store the parameters set by the user, and the JS front end to update the view. I got the two separate parts working.

When the user submits the Rail forms, it reloads the page and "resets" the camera

Ideally I want the form to submit the data to the back end without reloading the page - is this possible? Or maybe I'm doing this completely wrong?


Solution

  • Posting some of your code would help, but try adding "remote: true" to your form. That will tell your page not to refresh upon submitting.

    Furthermore, you will need to create a new method in your controller to forward to that responds to your submission and a page in your views folder (probably a js.erb file) that reloads the data. Without seeing your code, a quick example of the steps:

    app/assets/views/google_earth/index.html.erb

    <%= form_for(@pane_view, url: camera_path, remote: true) do |f| %>

    In your routes file:

    get 'camera' => 'google_earth#cameraUpdate', as: 'camera'
    

    app/assets/views/google_earth/camera.js.erb

    $('#camera-pane').html("<%= escape_javascript(render partial: 'camera_view', :locals => { x_coord: @x, y_coord: @y }) %>");
    

    This is assuming you have a partial view for your pane, I recommend doing it as a partial if you haven't already: app/assets/views/google_earth/_camera_view.html.erb

    Finally, in your controller you will want:

    def cameraUpdate
      @x = params[:x_coordinate]
      @y = params[:y_coordinate]
      respond_to do |format|
        format.html
        format.js
      end
    end