adding extra data to ajax response - ruby-on-rails

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
}

Related

How show in select a json data on rails

Hey im trying to make an cascading select with AJAX.
The problem is the response in format JSON doesn't appear in select list
these is my controller:
def fallas
#falla = Tipos.select("tip_id, tip_titulo").where("tip_id_padre = ?", params[:item])
respond_to do |format|
format.html
format.js
format.json { render json: #falla}
end
end
The CoffeeScript where i make the AJAX call:
jQuery ->
$('#solicitudes_tip_id_item').change ->
data = $('#solicitudes_tip_id_item :selected').val()
$.ajax({
type: "POST",
url: "/solicitudes/fallas",
dataType: 'json'
data: item:data,
success:(data) ->
$('#solicitudes_tip_id_falla').append(data)
error:(data) ->
return false
})
and these is the js.erb file when i show the answer (maybe here is the problem)
$("#solicitudes_tip_id_falla").empty()
$("#solicitudes_tip_id_falla").append("<%= render :json(:partial => #falla) %>")
The console show me this:
[{"tip_id":14,"tip_titulo":"Monitor encendido pero sin imágen"}]
but in the select nothing.
How i show the json data or how i can do the cascading select?
Edit:
If i use the function JSON.parse i got the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Now, i remove the coffeescript and i made it with Jquery:
$("#solicitudes_tip_id_item").change(function(){
var data = $("#solicitudes_tip_id_item :selected").val();
$.ajax({
url: "solicitudes/fallas",
data: {item : data},
dataType:'json',
type:'GET',
success: function(resp){
/*$.each(resp, function(idx, obj) {
$('#prueba').append($("<option></option>"‌​).attr("value",obj.t‌​ip_id).text(obj.tip_‌​titulo));
});
*/
var lol= JSON.stringify(resp);
console.log(lol);
var lel = JSON.parse(lol)
console.log(lel);
}
});
And in the console log of var lol and lel, show this:
Var lol:
[{"tip_id":14,"tip_titulo":"Monitor encendido pero sin imágen"}]
Var lel:
Array [ Object ]
Only need convert that information into a string to parse to the select

Can we pass additional parameters along with render method in rails

Controller method:
def add
#project = Project.find(1)
render xml: #project #wish to pass one more variable like this here
end
ajax call :
endpoint = ROOT_PATH + '/projects/add/'+data_type;
$.ajax({
url : endpoint,
type : "get",
dataType : "xml",
success : function(xml) {
id = $(xml).find('id').text();
title = $(xml).find('title').text();
// wish to display the sent additional parameter here.
}
});
I am able to get project instance parameters 'id' and 'title' in the ajax call.But I wish to send one more parameter along with the #project and wish to use the value of this parameter inside the ajax call. Could some one help me out pls. Thanks!
One of the ways could be:
render xml: #patient.as_json.merge({:YOUR_KEY => YOUR_VALUE})
if you want to send the requested params or nil #patient then:
requested_params = params.except(:controller, :action)
render xml: #patient.present? ? #patient.as_json.merge(requested_params) : requested_params`

Passing JSON data from Controller to JavaScript

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.

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