Skip to content
Tim edited this page Jul 14, 2015 · 11 revisions

Many ways to get interaction between JS and Rails

####Option 1. - pass data from Rails --> JS Rails - routes.rb

get 'locations/api' => 'locations#api'

Rails - app/controllers/<entity>s_controller.rb

  def api
    @locations = Location.all
    render json: @locations.to_json
  end

Javascript - app/assets/javascripts/<entity>s.js

var url = '/locations/api'
  $.getJSON(url, function (data) {
    allMarkers = data
  })

####Option 2. - Use URL parameters, pass data from JS --> Rails

  • only allows you to pass to the new page and not the create page

Javascript - app/assets/javascripts/<entity>s.js

window.open("/locations/new?posa=" + marker.position.A + "&posf=" + marker.position.F + "&address=" + result + "&film=" + film, "_self")

Ruby

 def new
    #variables collected from the params
    lat = params[:posa]
    lng = params[:posf]
    address = params[:address]
    location = Location.create(latitude: lat, longitude: lng, address: address, user_id: current_user.id)
    film = params[:film]
end

####OPtion 3. JS-->Rails JavaScript

$(document).ready(function() {

  $('.endorsements-link').on('click', function(event){
      event.preventDefault();

      var endorsementCount = $(this).siblings('.endorsements_count');

      $.post(this.href, function(response){
        endorsementCount.text(response.new_endorsement_count);
    })
  })
})

There's a lot going on here, so let's break it down line by line.

  • $(document).ready is a jQuery method that makes sure the page is fully loaded before the JS fires.
  • $('.endorsements-link').on('click', – when the user clicks on an HTML element with the class 'endorsements-link'...
  • var endorsementCount – make a new variable called endorsementCount...
  • $(this).siblings('.endorsements_count') – and tell that to refer to the HTML element with class 'endorsements_count' that's next to the current element (we need to do this weirdness because we're getting a span element that's next to the link being clicked)...
  • $.post – and then make a post request...
  • this.href – to the very same URL specified by the link that just got clicked...
  • response.new_endorsement_count – and grab the response of that request...
  • endorsementCount.text(response.new_endorsement_count) – and overwrite the endorsementCount element we defined before with that response (which will be the number of endorsements).
  def create
    @review = Review.find(params[:review_id])
    @review.endorsements.create
    render json: {new_endorsement_count: @review.endorsements.count}
  end

####Option 4 JS -->> Ruby Unproven method

Ruby

params[:data_value]

Javascript

var array = [1, 2, 3, 4, 5];

$.ajax({
        url : "/customurl",
        type : "post",
        data : { data_value: JSON.stringify(array) }
    });

Clone this wiki locally