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
Related
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.tip_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
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
I want send selected drop down menu value to controller by ajax
panel_controller.rb
class PanelController < ApplicationController
def insert
#city_ids = params[:city]
end
end
panel.js.erb
$(document).ready(function() {
$('#f_city_id').change(function() {
var city_js_id = this.value
$.ajax({
url: '/panel/insert',
type: 'GET',
data: {"city": city_js_id},
success: function (data,status)
{
alert(this.url);
}
});
return false;
});
});
routes.rb
get '/panel/insert' => 'panel#insert'
views/panel/insert.html.erb
<%= #city_ids %>
but #city_ids dont respond value after chenge drop down menu
You need to respond back from your insert method.
Try doing this
class PanelController < ApplicationController
def insert
#city_ids = params[:city]
respond_to do |format|
format.html { render partial: 'insert.html.erb' }
end
end
end
Create a partial file with the new content _insert.html.erb
<%= #city_ids %>
In you panel.js.erb try catching the response and append it in your DOM wherever necessary. Your updated value will be on the page.
$(document).ready(function() {
$('#f_city_id').change(function() {
var city_js_id = this.value
$.ajax({
url: '/panel/insert',
type: 'GET',
data: {"city": city_js_id},
success: function (res){
$("#somediv").html(res);
//You will get the partial's content with the new data and you'll only need to append it to your page.
}
});
return false;
});
});
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",
...
...
In the controller a response to an AJAX Request is following:
#response = {resp: "ack"}
render json: #response
JS which handles AJAX is:
$('#some_btn').click(function() {
var valuesToSubmit = $('#some_form').serialize();
var url = $('#some_form').attr('action');
console.log("VALUE: " + valuesToSubmit);
console.log("URL: " + search_url);
$.ajax({
type: 'POST',
url: url, //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON",
success: function(data) {
console.log("saved");
console.log(data);
}
});
return false;
});
But the problem is that I don't get console messages, instead the page reloads and I get json as text on a new page. How to prevent this "non-true-AJAX" behaviour?
So, I had almost the same problem. In my case, I was using the folliwing link to send the request:
<td>
<%= link_to add_item_path(item),
class: 'ui icon button',
id: "add-item-#{item.id}",
method: :post do %>
<%= fa_icon 'shopping-cart' %>
<% end %>
</td>
My js to send the ajax was:
$(document).ready(function() {
$("a:regex(id,add-item-[0-9]+)").click(function(event) {
event.preventDefault();
var link = $(this).attr("href");
$.ajax({
url: link,
method: "POST",
dataType: "json",
success: function(data) {
console.log(data);
$('#notice-modal').modal('show');
}
});
})
});
and my rails controller action was:
def add
#item = Item.find(params[:item_id])
current_cart << { item_id: #item.id, quantity: 1 }
render json: {quantity: 1}
end
So the problem was I using only event.preventDefault() but wasn't enought. For working fine, I need to use event.stopPropagation(). Like this:
$("a:regex(id,add-item-[0-9]+)").click(function(event) {
event.preventDefault();
event.stopPropagation();
var link = $(this).attr("href");
$.ajax({
url: link,
method: "GET",
dataType: "json",
success: function(data) {
console.log(data);
$('#notice-modal').modal('show');
}
});
})
The event.stopPropagation() is needed because rails component (rails-ujs I think) sent the request elsewhere. You can also remove the method: :post, and will work fine.
Hope I helped!
Do you need to prevent the default form submit action?
$('#some_btn').click(function(event) {
event.preventDefault();
//...
});
I had this problem myself. Turns out, I'd just forgotten to add "//= require jquery_ujs" to my application.js file. As soon as I added it, everything worked fine.