0

If I have a url like localhost:3000?id=2 what do I need to change to get my AJAX call to use the param?

page_controller.rb

class PageController < ApplicationController
  def index
    @pId = params[:id]
    @p = Plant.where(id: @pId)
    
    respond_to do |format|
      format.json { render json: @p.to_json }
      format.html
    end
  end
end

page.coffee

$ ->
  $.ajax
    dataType: 'json'
    url: 'index.json'
    success: (data) ->
      alert "Data #{JSON.parse(data)} ---"

development.log for one page load

Processing by PageController#index as HTML
  Parameters: {"id"=>"2"}
  Rendering page/index.html.erb within layouts/application
  [1m[36mPlant Load (1.0ms)[0m  [1m[34mSELECT "plants".* FROM "plants" WHERE "plants"."id" = $1[0m  [["id", 2]]
  Rendered page/index.html.erb within layouts/application (3.0ms)
Completed 200 OK in 80ms (Views: 69.5ms | ActiveRecord: 1.0ms)


Started GET "/index.json" for ::1 at 2017-01-26 08:07:18 -0800
Processing by PageController#index as JSON
  [1m[36mPlant Load (1.0ms)[0m  [1m[34mSELECT "plants".* FROM "plants" WHERE "plants"."id" IS NULL[0m
Completed 200 OK in 5ms (Views: 0.1ms | ActiveRecord: 1.0ms)

This is just a very basic example taken from a much more complicated piece of code. Everything in my original code works except for when I'm trying to access to param.

update 1

routes.rb

Rails.application.routes.draw do
  get 'index' => 'page#index'
  root "page#index"
end
Community
  • 1
  • 1
Ben
  • 367
  • 1
  • 5
  • 19

1 Answers1

1

Your URI for the Ajax request doesn't include the parameter. You're making a call to index.json and not index.json?id=1

Orlando
  • 1,236
  • 3
  • 12
  • 24
  • I figured it would be something easy like that. How woluld I grab the param from the URL to use in the json call? something like 'index.json?id=param[:id]' – Ben Jan 26 '17 at 16:41
  • If your goal is to get the parameters from the URL and feed it to your JS, this is a good way to do it: http://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript – Orlando Jan 26 '17 at 16:58
  • For those looking for the 'easy' answer I ended up adding the following two lines of code before the ajax call `paramsString = window.location.search.substr(1)` `searchParams = new URLSearchParams(paramsString)` I then changed the `'index.json'` to `'index.json'+searchParams` – Ben Jan 27 '17 at 15:17