Passing JSON data from Controller to JavaScript - ruby-on-rails

There is a service that when I hit it it return me JSON like this, so I think it is returning me the correct JSON I need:
Now in my client contoller I have something simple as this to call the Service and get the JSON back and if I put break points I can see that yes it does have the same JSON posted above
class PharmacyController < ApplicationController
def index
#order_summary = client.get_order_summary(10)
gon.data = #order_summary # my attempt to pass it with GON gem.
end
end
and then in my pharmacy/index.html.erb I am calling my Javascript:
<%= javascript_include_tag 'dummy.js' %>
and my dummy.js javascript file looks like this for now, just to make sure I can see the same number of elements no the array:
$( document ).ready(function() {
var data = gon.data;
console.log( data.length);
});
but what it returns is "undefined"
Do you have any other suggestions for how to achieve this?

Use jQuery Ajax
$.ajax({
url: <url>,
type: 'get',
data: {},
success: function (data) {
console.log( data);
}
});

I just should have done:
gon.data.body
.body was missing.

Related

adding extra data to ajax response

I have this piece of code:
var jqxhr = $.ajax({
url: "/customers/shipments/get_carrier_products_and_prices_for_shipment.json",
type: "POST",
dataType: "json",
data: data
})
and the last lines of controller:
if #carrier_products_and_prices.length > 0
#digest = params[:digest]
#html = render_to_string(partial: "components/customers/shipments/carrier_products_and_prices_for_shipment_table.html.haml", locals: {carrier_products_and_prices: #carrier_products_and_prices})
else
#html = render_to_string(partial: "components/customers/shipments/no_carrier_products_available.html.haml", locals: {carrier_products_and_prices: #carrier_products_and_prices})
end
Which hits a rails controller. My question is, how can I control/append extra data to the response object that rails returns? Right now, it only returns a html string, and I would like to also be able to send a response ID with it
It looks like your client is expecting a JSON body. Just create a hash of the values you want returned to the client and call render json: hash where hash contains the values you want to return to the client as JSON.
Since you're already using the JSON dataType, there's nothing stopping you from packing up your stuff in an object:
{
"html": "<div>...</div>",
"responseID": 69
}

Ajax call is returning error from action controller in rails

on change of a dropdown value i am trying to populate other dropdown list value.
Here i have added my new action in routes.rb :
resources :appointments do
collection do
get :getdata
end
end
This is my js code :
$("#appointment_department_id").change(function(){
//on change of department dropdown.
$.ajax({
url: "/appointment/getdata",
type: "GET",
data: {department_id: $(this).val()},
success: function(data){
alert(data);
}
error: function(data){
alert(data);
}
});
});
here is my action in controller file :
def getdata
#dept_id = params[:department_id]
department_name = #dept_id
#all_doctors = User.all; #will write my custom query later.
end
But on call to this action, it's returning error:
"NetworkError: 404 Not Found - http://localhost:3000/appointment/getdata?department_id=5"
(checked in firebug)
the error is in the ajax url, in the ajax request you are using 'appointment/getdata', but in routes you have defined appointments,
so use
$("#appointment_department_id").change(function(){
//on change of department dropdown.
$.ajax({
**url: "/appointments/getdata",**
type: "GET",
data: {department_id: $(this).val()},
success: function(data){
alert(data);
}
error: function(data){
alert(data);
}
});
});
Where's your respond_to in your controller?
If you're sending an Ajax request, you'll have to either define respond_to "JS" or "JSON" like this:
def getdata
respond_to do |format|
format.js
end
end
You could also do it like this:
Class Controller
respond_to :html,:js, :json
def getdata
respond_with(#custom_vars)
end
end
i think you forget "s" of "appointment" word in url: "/appointment/getdata", so try to add "s" like this :
$.ajax({
url: "/appointments/getdata",
...
...

Auto refresh <div> without reload entire page

I'm trying to update the content of "mydiv" without refreshing the entire index page.
#mydata is given by mycontroller. I need to recalculate it every n seconds and pass it to "mydiv"
With "link_to" it works!
index.html.erb
<%=
link_to('refresh', '/mycontroller/index', :remote => true)
%>
<div id="mydiv">
<%=
#mydata
%>
</div>
index.js.erb
$('#mydiv').html('<%= escape_javascript(#mydata) %>')
Now I need to refresh the content of "mydiv" automatically every n seconds (so without click on the link). I have tried solutions from:
First Link
Second Link
but no luck.
In my application.js I have writed this:
function executeQuery() {
$.ajax({
//url: '/index',
success: function(data) {
$('#mydiv').html(data)
}
});
setTimeout(executeQuery, 500);
}
$(document).ready(function() {
setTimeout(executeQuery, 500);
});
For who is facing my same problem, I solved it by replacing
$('#mydiv').html(data)
with
$('#mydiv').load('/mycontroller/index #mydiv')
Use setInterval() instead of using setTimeout().
Ref: https://www.w3schools.com/jsref/met_win_setinterval.asp
function executeQuery() {
$.ajax({
type: 'GET',
url: 'example.com/url/', // Provide your response URL here.
success: function(data) {
$('#mydiv').html(data);
}
});
}
setInterval(executeQuery(), (n * 1000)); // Replace 'n' with how many seconds you want.
This code will run the executeQuery() method in every 'n' seconds interval. So that your requirement is accomplished.
Set layout to false in the action and just pass on the relevent content, not the entire page
def action1
<your code here>
end
def action2
<your code here>
render :layout => false
end
Your view for action2 should have content pertaining only to #mydiv.
A better solution would be to use a single action and change render options based on type of request. (Ajax or non ajax)

Rendering JSON from AJAX call in Rails

I have an ajax call to fetch information from Flickr API which returns JSON data. I want to display values from JSON data in my view. I do this by editing some innerHTML with jQuery. The problem I am having is that the data is undefined, so it looks like a scoping problem.
photo.js
jQuery(function() {
$('#<%=p[:id]%>').click(function (e) {
//ajax call to fetch photo info
var fetch_id = '<%=p[:id]%>';
var fetch_secret = '<%=p[:secret]%>';
$.ajax({
type: 'GET',
url: '/photos/fetch_info',
dataType: 'json',
data: { 'id' : fetch_id, 'secret' : fetch_secret },
success: function(data){
console.log(data) //returns Object
console.log(data.title) //returns appropriate title
//edit innerHTML of basic_modal
$('.basic_modal').html(
"<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %></div><div id='photo_title'><%=data.title %></div>"
);
//load modal
$('.basic_modal').modal({
overlayClose:true
});
} //end success: function(result)
});
When I print data.title to console, I get the appropriate title. However, when I try to edit HTML and render <%=data.title %>, I get an undefined variable/method error.
Any tip on how I can display the data in my modal in the view?
Here is my controller:
def fetch_info
#info = flickr.photos.getInfo(:photo_id => params[:id], :secret=> params[:secret])
respond_to do |format|
format.json { render :json => #info }
end
end
var result = jQuery.parseJSON(data);
You donot need to do this, Because datatype:JSON already parse the data
$('.basic_modal').html(
"<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %>
</div><div id='photo_title'><%="+data.title+" %></div>"
);
this might help you

JqueryUI autocomplete in Rails3

$(document).ready ->
$('#auto').autocomplete( source: "main/search" )
the code beyond set up the autocomplete env,'#auto' is an input filed.
In my main controller I got the search action
def search
#user = User.find_by_name 'castiel'
respond_to do |format|
format.json { render :json => #user.to_json(:only => :name) }
end
end
everything seems working perfectly fine.When I type in a char,let's say a "c",so the ajax request was sent and received the json data.
In firebug, it shows the ajax request successfully get the json data below
{"name":"castiel"}
so far so good,but the json data's type is not the kind that autocomplete demanded.It demands that json data is like below.
{"id":"castiel", "label":"castiel", "value":"castiel"}
So here is problem,how to modify the josn data to the kind that I wanted.
In the success function, you need to return something like
.autocomplete({
source: function(request, response){
$.ajax({
url: "main/search",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},success: function( data ) {
response( $.map( data, function( user ) {
return {
label: user.name,
value: user.id
}
}));
Rails allows you to serve JSON in any structure from your controller. When using the jQuery autocomplete helper, you serve JSON back in the format needed by using the autocomplete library method json_for_autocomplete as follows:
# app/controllers/example_controller.rb
def autocomplete_example
items = Example.where(...)
respond_to do |format|
format.json do
render :json => json_for_autocomplete(items, 'name', [])
end
end
end
The first argument to json_for_autocomplete is your collection of objects to return. The second is the method to call on those objects to define the values in the JSON hash. The final argument is for any extra options, which can be found at:
https://github.com/crowdint/rails3-jquery-autocomplete/blob/master/lib/rails3-jquery-autocomplete/autocomplete.rb

Resources