Error I get: undefined variable article_id.
What I am trying to achieve : Define the correct route in AJAX and Rails.
What I need: The structure articles/1/comments/2.
Goal: Note that my goal is to only load comment using AJAX, not article.
In the AJAX script below what I currently have undefined is article_id, for which I wrote the following:
var getArticle = function () {
return $('.article-title').each(function() {
var article_id = $(this).data('article-id');
});
};
$(document).ready(getArticle);
AJAX:
var loadComment = function() {
return $('.comment-content').each(function() {
var comment_id = $(this).data('comment-id');
return $.ajax({
url: "/articles/" + article_id + "/comments/" + comment_id,
type: 'GET',
dataType: 'script',
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Worked OK!");
}
});
});
};
$(document).ready(loadComment);
$(document).on('page:change', loadComment);
Index:
- #articles.each do |article|
%article-title{ :class => "article-title", "data-article-id" => article.id }= article.title
- article.comments.each do |comment|
%comment-content{ :id => "comment-#{comment.id}" }
Add this to your routes.rb
resources :articles do
resources :comments
end
And add the following controller:
class CommentsController < ApplicationController
def show
#article = Article.find(params[:article_id])
#comment = #article.comments.find(params[:id])
render json: #comment
end
end
Running something like:
curl http://localhost:3000/articles/123/comments/456.json
will set the params[:article_id] to 123 and the params[:id] to 456, the id is intended to be used as a comment id.
Related
please help me i newbie on rails and jquery i try get all values from array #mychannels id element on html in my view.
JS AJAX
$(document).ready(function() {
$('#mychannels').change(function () {
$.ajax({
type: "GET",
contentType: "dados/json",
url: "/suporte/chamados?empresa_id=91194",
success: function(data){
alert(data);
}
});
});
});
Controller
def get_data
#company = Company.find(params[:company_id])
#servers = Server.find(:all, :conditions => ["company_id = ? AND action != 3", #company.id])
#channels_list = Channels.where("channel = 't' and company_id = 91194")
My View
<%= select_tag "mychannels",options_for_select(#channels_list.map { |e|
[e.name+" - "+e.server.name, e.id]}) %>
I am trying to read the data that comes from the controller throw to an array and display it in the select_tag of the view.
could you help me with the code
You need to update your controller action adding the render method and adding the values you want to get in your jQuery success callback.
Controller
def get_data
#company = Company.find(params[:company_id])
#servers = Server.find(:all, :conditions => ["company_id = ? AND action != 3", #company.id])
#channels_list = Channels.where("channel = 't' and company_id = 91194")
render json: { company: #company.to_json, servers: #servers.to_json, channels_list: #channels_list.to_json }
end
I tried to make dynamic select boxes(One boxes choosing info in another), but have some troubles.
routes.rb
get "students/new/update_tutors" => 'students#update_tutors', as: 'update_tutors'
students_controller.rb
def update_tutors
admin = Administrators.find(params[:administrator_id])
##tutors = admin.tutors.map{|t| [t.info.name, t.id]}
debugger
#tutors = Tutor.where(administrator_id: params[:administrator_id])
respond_to do |format|
format.js
end
end
def new
#user = Student.new
#is_super_adm = is_super?
if #is_super_adm
#tutors = Tutor.all.map { |t| [t.info.name, t.id] }
#admins = Administrator.where(is_super: false).map { |adm| [adm.info.name, adm.id] }
else
#tutors = Tutor.where(administrator_id: session[:type_id]).map { |t| [t.info.name, t.id] }
end
end
new.html.erb
<%= form_for #user, remote: true do |student_form| %>
<!--....-->
<%= label_tag :administrator_id, "Choose local administrator" %><br/>
<%= select_tag :administrator_id, options_for_select(#admins), {id: 'administrator_selection'} %><br/>
<!--....-->
<%= student_form.label :tutor_id, "Choose Tutor" %><br/>
<%= student_form.select :tutor_id, options_for_select(#tutors), {} , {id: 'tutor_selection'}%>
students.coffee
$ ->
$(document).on 'change', '#administrator_selection', (evt) ->
$.ajax 'update_tutors',
type: 'GET'
dataType: 'script'
data: {
administrator_id: $("#administrator_selection option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
update_tutors.coffee
$("#tutor_selection").empty()
.append("<%= escape_javascript(render(:partial => #tutors)) %>")
I tried to insert alert('msg') into students.js.coffee, and event worked, so I am sure that the problem is in $.ajax but this is first time I am working with ajax and I can't find the bug.
Update
I guess problem is in routing, but i didn't understand why it calls students/update_tutor instead students/new/update_tutor
Log
Started GET "/students/update_tutors?administrator_id=3&_=1459590346845" for 127.0.0.1 at 2016-04-02 11:47:01 +0200
Processing by StudentsController#show as JS
Parameters: {"administrator_id"=>"3", "_"=>"1459590346845", "id"=>"update_tutors"}
Fixed
I changed update_tutors in $.ajax to 'new/update_tutors' and fixed error in update_tutors method in Administrators.find(...) to Administrator.find(...).
Change your Ajax request as per given below,
$ ->
$(document).on 'change', '#administrator_selection', (evt) ->
$.ajax '<%= update_tutors_path %>',
type: 'GET'
dataType: 'script'
data: {
administrator_id: $("#administrator_selection option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
I have the following HAML form:
.row
.col-lg-6
.panel.panel-default
.panel-heading
%h1.box-title
%i.fa.fa-calendar.fa-fw
Availability
.panel-body
= form_tag dashboard_kid_availabilities_url(current_kid), :method => 'post', id: "save-availability", remote: true do
.form-group
= _("Date")
= select_date(Time.now + 1.day, order: [:day, :month, :year])
%br
= _("Hour")
= select_hour(Time.now )
.form-group
= submit_tag _('Save'), class: 'btn btn-blabloo btn-xs'
With the following ajax request:
:javascript
$("#save-availability").submit(function () {
var availability_day = $("#date_day").val();
var availability_month = $("#date_month").val();
var availability_year = $("#date_year").val();
var availability_hour = $("#date_hour").val();
var calendar = $("#calendar").fullCalendar();
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: {"date_day" : availability_day, "date_month" : availability_month, "date_year" : availability_year, "date_hour" : availability_hour},
success: function(result){
alert("salvada disponibilidad");
},
error: function(xhr, textStatus, error) {
console.log("Impossible to connect");
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
And this is the code of my controller:
def create
#availability = Availability.new()
#availability.availability_date = (params[:date][:day] + "/" + params[:date][:month] + "/" + params[:date][:year] + " "+ params[:date][:hour]).to_str
#availability.end_availability_date = (params[:date][:day] + "/" + params[:date][:month] + "/" + params[:date][:year] + " "+ (params[:date][:hour].to_i + 1).to_s).to_str
#availability.kid = current_kid
if #availability.save
flash[:notice] = 'Availability created successfully'
respond_to do |format|
format.json { render json: #availability.to_json, success: :ok, error: false }
end
else
flash[:error] = 'Availability not created'
end
end
Everything work great (the record is saved), but the success code on my javascript code it's never execute, instead the error code it's executed.
I'm getting this error on my console:
POST http:// localhost:3000/dashboard/kids/jean_oso/availabilities 500
(Internal Server Error) application.js?body=1:8707send
application.js?body=1:8707jQuery.extend.ajax
application.js?body=1:8137(anonymous function)
edit:1808jQuery.event.dispatch
application.js?body=1:5096elemData.handle application.js?body=1:4767
Impossible to connect edit:1816 Internal Server Error edit:1817 error
edit:1818 Internal Server Error
What I'm doing wrong.
Thanks in advance
I would like to post the result of an ajax request back to the same page that it was requested from. Here are the interacting parts:
AJAX in Jquery
var ids = 1
$(document).ready(function(){
$('#showbtn').on('click', function() {
$.ajax({
url: "http://localhost:3000/teamplayers.json",
data: {'resolution':ids},
type:"post",
dataType: "json",
cache: true,
success:function(){
$('#test3').val(1);
alert("test 3");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
});
});
This is supposed to set a variable here:
Teamplayer Controller
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
#teamplayer2 = 1
tid = params[:resolution] <-It should set here per the data section above
#ids = tid
end
unfortunately it calls this section of the same controller
# POST /teamplayers
# POST /teamplayers.json
def create
#teamplayer = Teamplayer.new(teamplayer_params)
respond_to do |format|
if #teamplayer.save
format.html { redirect_to #teamplayer, notice: 'Teamplayer was successfully created.' }
format.json { render action: 'show', status: :created, location: #teamplayer }
else
format.html { render action: 'new' }
format.json { render json: #teamplayer.errors, status: :unprocessable_entity }
end
end
end
So what do I do to make it post to the same page.
You are POSTing the ajax, which means the create action will be hit, not the index action. You should be able to see this in your server log output when you hit the page.
If you want to hit the index action, you need to do an GET ajax request with the resolution data set so you can get the data you want.
Additionally, you probably maybe don't want to cache this ajax request if it is actually dynamic data, but it is up to you.
Edit from comments:
You need to add your parameter as a query string for a GET, not as generic "data".
Try something like this:
$.ajax({
url: "http://localhost:3000/teamplayers.json?resolution="+ids,
type:"GET",
dataType: "json",
success:function(){
$('#test3').val(1);
alert("test 3");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
});
Another edit from comments:
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
#teamplayer2 = 1
tid = params.fetch(:resolution) { 0 } # make sure we got something
#ids = tid.to_i # coerce string param to integer
end
Using Rails 3.2. I wonder how can we push the error from Rails to show in the Ajax alert. Here is my code:
# posts_controller.rb
def update
#post = Post.find(params[:id])
if #post.update_attributes(params[:name] => params[:value])
render :nothing => true
else
render :text => #post.errors.full_messages[0], :status => :unprocessable_entity
end
end
# _form.html.erb
$("#status_buttons button").click(function() {
$.ajax({
type: 'POST',
url: "<%= post_path(#trip) %>",
data: { _method: 'PUT', name: this.name, value: this.value },
error: function() {
alert(" *****************Rails error message here**********************");
}
});
});
The conventional validation error message should appear in the alert(). Any idea?
Thanks.
one way to determine is to pass at least 3 arguments to the callback function and checking the console (or an alert) for whatever argument passes the error.
error: function(a,b,c) {
alert('a contains ' + a);
alert('b contains ' + b);
alert('c contains ' + c);
}
one of them should contain the error message :) Good luck!
error: function( jqXHR, textStatus, errorThrown ) { ...