How show in select a json data on rails - ruby-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

Related

Passing in rails routes to AJAX url value

I have an app where a user has a portfolio that has many positions and each position has many movements. So the url for an associated movement index page for a particular position looks like: portfolio_position_movements. I have an index page with and the controller action looks like
def index
#movements = #position.movements.all
respond_to do |format|
format.html
format.json { render json: #movements}
end
end
My ajax call in my movements.js file is this:
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: ?,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
How can I pass in a dynamic route path so this will work with the movement index on any position object?
You can use erb tags in js files, for me i did it as the following:
#edit.js.erb
$modal = $('.modal'),
$modalBody = $('.modal .modal-body'),
$modalHeading = $('.modal .modal-heading');
$modalHeading.html("Edit <%= #student.full_name.titleize %>'s information");
$modalBody.html("<%= escape_javascript(render 'edit_student') %>");
$modal.modal();
Note: the file extension is .js.erb so rails can process it. I was calling a modal form and the edit method in students_controller.rb was:
def edit
#student = Student.find(params[:id])
respond_to do |format|
format.html # edit.html.erb
format.js # edit.js.erb
format.json { render json: #student }
end
end
Edit:
You can embed the JS code inside html.erb and use rails routes like:
<script>
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: <%= my_ajax_path %>,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
</script>
What is my_ajax_path?
Is a rails route defined in routes.rb for example i need a list of all available sections that students can apply to using ajax so i did the following:
1- defined a method in students_controllers.rb like this one:
def available_sections
batch_id = (params[:batch_id].nil? || params[:batch_id].empty?) ? 0 : params[:batch_id].to_i
if batch_id == 0
#sections = [].insert(0, "Select Section")
else
batch = Batch.find(params[:batch_id])
# map to name and id for use in our options_for_select
#sections = batch.sections.map{|a| [a.section_name, a.id]}
end
end
2- added a route to it in routes.rb
resources :students do
collection do
get :available_sections
post :create_multiple
end
end
3- Inside new.html.erb:
<script type="text/javascript">
$(document).ready(function() {
$('.student_section_id').hide();
$('#student_batch').change(function() {
$.ajax({
url: "/students/available_sections",
data: {
batch_id : $('#student_batch').val()
},
dataType: "script",
success: function () {
if (+$('#student_batch').val() > 0)
{
$('.student_section_id').fadeIn();
}
else
{
$('.student_section_id').fadeOut();
}
}
});
});
});
</script>
Forget about that messy code :D as it was my first steps but you get the point, and for this line url: "/students/available_sections" it should be using rails routes you can get it by calling rails routes from the command line to get a list of all your application routes

Rails ajax request response

I am using Rails CoffeeScript to call an action in my controller, which is fine, but I can not get the response to work.
I have a form with a list of budget lines. I want to allow the use to add a new line using CoffeeScript so I don't need to reload the question.
I have got the following in CoffeeScript:
$("button[id^='new_budget_line']").on 'click', (event) ->
category_id = $(this).attr('name')
child_economy_id = $('#child_economy_id').val()
$('#form_id').submit ->
valuesToSubmit = $(this).serialize()
$.ajax
type: 'POST'
url: $(this).attr('action')
data: valuesToSubmit
dataType: 'JSON'
$.ajax({
type: 'GET'
url: '../child_economy_lines/create_line'
data:
child_economy_id: child_economy_id
category_id: category_id
cost_type: 'direct'
dataType: JSON
}).done (response) ->
alert "Hey"
$('#test_append').html("Hey you now!!")
And the following in my controller
def create_line
logger.debug "Hejsa fra create line - category id #{params[:category_id]}"
#child_economy_line = #child_economy.child_economy_lines.build(:child_economy_category_id => params[:category_id], :cost_type => params[:cost_type])
if #child_economy_line.save
respond_to do |format|
format.js {render nothing: true}
format.json {render :json => "test"}
end
end
end
The action in the controller i called fine, and the new line is created, but I can not the actions after the ajax call to work. The part from .done ...
Can anybody help me identify where it is going wrong?

how to set session variable with ajax request on rails?

I need to set session variable on ajax call on rails. I have following ajax code:
$.ajax({
url: '/dashboard/set_session',
type: 'GET',
data: {
site_id: site_id
},
dataType : 'json'
}).done(function(data){
console.log(data);
});
And on rails end:
def set_session
puts params[:site_id]
session[:site_id] = params[:site_id]
puts session[:site_id]
respond_to do |format|
format.json { render json: 'success'}
end
end
The first and second puts print same value. That means the session is set. But when I navigate to other pages or reload the page, the session value of site_id is cleared.
How to fix this issue?

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