Boucherie Boucherie - 3 years ago 157
jQuery Question

Calling Rails controller data through JS AJAX call

I'm making a rails app using this code in the controller to call an API- I initially call the

inventories endpoint
, then make separate calls to two other id endpoints
store_id, product_id
to grabs specifics pieces of data linked to the inventories. This data gets passed into a hash that becomes '@inventories / transformed results':

class InventoriesController < ApplicationController
def index
response = Typhoeus.get("http://lcboapi.com/inventories")
parsed_json = JSON.parse(response.body)

transformed_results = []

parsed_json["result"].each do |inventory|
transformed_results.push(
{
product_name: product_lookup(inventory["product_id"]),
store_name: store_lookup(inventory["store_id"]),
quantity: inventory["quantity"],
}
)
end

@inventories = transformed_results
end
private

def store_lookup(store_id)
response = Typhoeus.get("http://lcboapi.com/stores/#{store_id}")
parsed_json = JSON.parse(response.body)
return parsed_json["result"]["name"]
end

def product_lookup(product_id)
response = Typhoeus.get("http://lcboapi.com/products/#{product_id}")
parsed_json = JSON.parse(response.body)
return parsed_json["result"]["name"]
end
end


My question is how best to get my json hash through AJAX into a form I can pass through and iterate in assets/javascript.

I am aware I can build it into the view (html.erb) and have done so, but I want to make my data interact with DOM elements.

Note: I've tried doing a simple console log to show the json data in the console as a test, with no response. I'm okay with using jQuery until I get comfortable with React, but I'm not sure how to grab my @inventories data from assets/javascript/inventories.js

document.addEventListener('DOMContentLoaded', function () {
console.log("ready!");
$.ajax({
url: "/inventories",
method: "GET",
dataType: "json"
}).done(function(data){
console.log(data);
});

})

Answer Source

In one of your js files (in assets/javascript), you'll need to do something like:

storeLookupResults = $.ajax({
  url: "/inventories.js",
  type: 'GET'
})
storeLookupResults.success (data) =>
  # do stuff with your results
  # 'data' will contain your json

NOTE: I made up the route, so you'll need to make sure you use a real route

Then, in your InventoriesController, modify index to something like:

def index
  response = Typhoeus.get("http://lcboapi.com/inventories")
  parsed_json = JSON.parse(response.body).with_indifferent_access

  @inventories = parsed_json[:result].map do |inventory|
    {
      product_name: product_lookup(inventory[:product_id]),
      store_name: store_lookup(inventory[:store_id]),
      quantity: inventory[:quantity],
    }
  end

  respond_to do |format|
    format.html
    format.json {render json: @inventories, status: :ok}
  end  

end

Note that .map returns an array. So, you don't have to do:

transformed_results = []

parsed_json["result"].each do |inventory|
  transformed_results.push(
    {
      product_name: product_lookup(inventory["product_id"]),
      store_name: store_lookup(inventory["store_id"]),
      quantity: inventory["quantity"],
    }
  )
end    

@inventories = transformed_results

Also note that I did:

parsed_json = JSON.parse(response.body).with_indifferent_access

It's a purely stylistic preference. I like using symbols instead of strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download