Dynamic select boxes with Rails 4 - javascript

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!")

Related

Ruby on Rails:Can not call ajax callback from form_tag

In my view (/app/view/media/index.html.erb) , i have an ajax function and a form_tags:
My AJAX function:
<script type="text/javascript" charset="utf-8">
$(document).ready(
function () {
$("#my_ajax").bind("ajax:success",
function (evt, data, status, xhr) {
console.log(data);
}
).bind("ajax:error", function (evt, data, status, xhr) {
console.log("doh!")
});
});
</script>
.
And my form_tags:
<%= form_tag '/delete_media', method: :delete do %>
<%= submit_tag 'Delete', class: 'btn btn-danger', disabled:#media_contents.empty? , :remote => true, :id => "my_ajax" %>
Our goal : when i get response from server after submit, my_ajax function will be run.
How to do it ??? I can not trigger "my_ajax" function ? I always get JSON response from server
EDIT:
My controller :
def delete_media
#medias=Media.where(id: params[:media_contents]).destroy_all
render json: #medias
end
You should not write js handle ajax like that.
Properly way to implement ajax in rails is:
In /app/view/media/index.html.erb:
form_tag ..., remote: true
In media Controller:
def destroy
# do your job
respond_to do |format|
format.js {}
end
end
In /app/view/media/destroy.js.erb:
// your js handle code
More information: http://guides.rubyonrails.org/working_with_javascript_in_rails.html
maybe try something like this:
<script>
$(document).ready(function(){
$("#my_ajax").on('ajax:success', function(e, data, status, xhr){
console.log(data);
}).on('ajax:error',function(e, xhr, status, error){
console.log('doh!')
});
});
</script>

Defining routes in AJAX and Rails

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.

Rails applications layout features to use application_controller in any view

So I want to have dynamic select boxes for navigation in every view, now they work fine in localhost:3000 and in localhost:3000/diys/ but for example in http://localhost:3000/diys/new and in http://localhost:3000/diys/25 they don't.
Part with select boxes in views/layouts/application.html.erb
<div class="side_select_box">
<%= form_tag search_path, :method => :get do %>
<%= select_tag "side_make_select", options_for_select(#side_makes.collect { |make|[make.make_name, make.id] }), include_blank: "Select make" %>
<%= select_tag "side_model_select", (render "make_models/make_model") %>
<% end %>
</div>
..assets/javascripts/applications.coffee, i think that issue may be on "$.ajax..." line
$ ->
$(document).on 'change', "#side_make_select", (evt) ->
$.ajax 'update_side_make_models',
type: 'GET'
dataType: 'script'
data: {
side_make_id: $("#side_make_select option:selected").val(),
side_model_div_id: "#side_model_select"
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic side make select OK!")
../views/application/update_side_make_models.coffee, issue might be also that this file should be somewhere else, but where?
$("<%= #sidemodelsid %>").empty()
.append("<%= escape_javascript(render "make_models/make_model") %>")
and from there it renders "make_models/make_model" and uses
application_controller.rb
...
def side_select_boxes
#side_makes = Make.all
#models = MakeModel.where("make_id = ?", 0)
end
def update_side_make_models
#models = MakeModel.where("make_id = ?", params[:side_make_id]).order(:make_model_name)
#sidemodelsid = params[:side_model_div_id]
end
...
So when on homepage or index view I select make in makes select box, it renders models fine, printing this in rails console
Started GET "/update_side_make_models?side_make_id=15&side_model_div_id=%23side_model_select&_=1456934054006" for :: 1 at 2016-03-02 17:56:38 +0200
Processing by ApplicationController#update_side_make_models as JS
Parameters: {"side_make_id"=>"15", "side_model_div_id"=> "#side_model_select", "_"=>"1456934054006"}
...
but in show view and in new view, when i select make in makes select box, nothing happens with models select box, and this is printed in rails console
Started GET "/diys/update_side_make_models?side_make_id=15&side_model_div_id=%23side_model_select&_=1456934054008" for ::1 at 2016-03-02 18:01:09 +0200
Processing by DiysController#show as JS
Parameters: {"side_make_id"=>"15", "side_model_div_id"=> "#side_model_select", "_"=>"1456934054008", "id"=>"update_side_make_models"}
...
ActiveRecord::RecordNotFound (Couldn't find Diy with 'id'= update_side_make_models):
app/controllers/diys_controller.rb:128:in `set_diy'
So for some reason it puts "/diys/" in front of "/update_side_make_models", and processes it by "DiysController#show", but should process by "ApplicationController#update_side_make_models"
Oh, just needed to point to ajax to go one directory up in
..assets/javascripts/applications.coffee
$ ->
$(document).on 'change', "#side_make_select", (evt) ->
$.ajax '../update_side_make_models',
type: 'GET'
dataType: 'script'
data: {
side_make_id: $("#side_make_select option:selected").val(),
side_model_div_id: "#side_model_select"
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic side make select OK!")

Capybara redirecting to JSON response

I've got a form in my rails application that sends data remotely to a controller action. There is then JavaScript that waits on a successful AJAX response and then updates segments of the page.
When testing with Turnip, Rspec and Capybara, the current_page is redirected to the JSON response instead of staying on the page like I expect.
Here is some of the code:
The controller action being hit
def update
#conversation.update(conversation_params)
#conversation.save
render json: #conversation, serializer: ConversationSerializer
end
The form
= simple_form_for(convo, remote: true, method: :json) do |f|
- f.fields_for :messages, Message.new(conversation: f.object) do |msg|
= msg.input :text, label: 'Message'
= msg.submit 'Post Message', id: 'message-submit'
The Coffeescript listening for success
$(document).on 'ajax:success', 'form[data-remote]', (xhr, data, status) ->
new_message_id = data.conversation.conversation_messages.pop().id
$.get '/conversation_messages/'+new_message_id+'/partial', (data) ->
$('#conversation .message').last().after(data)
$(document).on 'ajax:success', 'a[data-remote]', (xhr, data, status) ->
location.reload()
$(document).on 'ajax:success', 'form[data-remote]', (xhr, data, status) ->
location.reload()
The test that is showing the wrong content
step 'I say :message' do |message|
fill_in 'Message', with: message
click_on 'Post Message'
end
step 'I see the conversation message :message from :username' do |message, username|
expect(page).to have_selector('.conversation-message-sender', text: username)
expect(page).to have_selector('.conversation-message-text', text: message)
end
You need to be using a JavaScript capable driver for ajax submissions to work - see https://github.com/jnicklas/capybara#drivers

ActionController::UnknownFormat in CareersController#create for rails 4

i am trying to intigrate js file for "success message" as pop up when I submit my form.
its says, ActionController::UnknownFormat in CareersController#create
In my controller:
def create
#career = Career.new(career_params)
respond_to do |format|
if #career.save
format.js {render :template => 'careers/create', :locals => { :career => #career} }
else
format.html { render :new, :locals => { :career => #career} }
end
end
end
and my create.js.erb file:
$(document).ready(function(){
$("#new_career").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
format: 'js',
success:function(data, textStatus, jqXHR)
{
alert("Form has been submitted");
},
error: function(jqXHR, textStatus, errorThrown){
alert("Network connection problem");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
})
Here is my server Error log :
Started POST "/careers" for ::1 at 2015-06-15 21:54:32 +0600
Processing by CareersController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"3NOJnGQZsFuYtd4JdNGl4wVmIh7at3laQDfjYyp1iPxt/xUdokGqSaAQiWOb+zEh2yvrW6IE3CrnPXQhwBADTg==", "career"=>{"full_name"=>"mezbah", "email
"=>"mezbahalam26#gmail.com", "phone_number"=>"01742626262"}, "commit"=>"SUBMIT APPLICATION"}
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "careers" ("full_name", "email", "phone_number", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["full_name", "mezbah"], ["email", "mezbahalam26#gmai
l.com"], ["phone_number", "01742626262"], ["created_at", "2015-06-15 15:54:32.107023"], ["updated_at", "2015-06-15 15:54:32.107023"]]
(172.2ms) commit transaction
Completed 406 Not Acceptable in 178ms (ActiveRecord: 173.2ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/careers_controller.rb:21:in `create'
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (48.0ms)
Cannot render console with content type multipart/form-dataAllowed content types: [#<Mime::Type:0x42c5208 #synonyms=["application/xhtml+xml"], #symbol=:html, #string="text/html">, #<
Mime::Type:0x42c4458 #synonyms=[], #symbol=:text, #string="text/plain">, #<Mime::Type:0x4267e48 #synonyms=[], #symbol=:url_encoded_form, #string="application/x-www-form-urlencoded">]
what am i doing wrong ? please help
ActionController::UnknownFormat in CareersController#create
You have defined format as json instead js. Change it to like this
def create
#career = Career.new(career_params)
respond_to do |format|
if #career.save
format.js {render :template => 'careers/create', :locals => { :career => #career} }
else
format.html { render :new, :locals => { :career => #career} }
end
end
end
Update
You should also have to define format as js in your ajax
#create.js.erb
$(document).ready(function(){
$("#new_career").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
format: 'js', #here
success:function(data, textStatus, jqXHR)
{
alert("Form has been submitted");
},
error: function(jqXHR, textStatus, errorThrown){
alert("Network connection problem");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
})

Categories