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!")
Related
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>
I'm using Rails to create a page with the ability to submit contact information and create a contact object. The controller for the Contact creation is:
def create
#contact = Contact.new(contact_params)
if #contact.save
render json: #contact, status: :created
else
render json: #contact.errors.full_messages, status: :unprocessable_entity
end
end
with contact_params of:
def contact_params
params.require(:contact).permit(:name, :email, :phone, :company, :message)
end
The form submits and creates objects fine if I handle everything a redirect but I want to handle the creation with JS. I've used this method before on form submission with no problems but for some reason when I run:
$(document).ready(function(){
$('#new_contact').on('submit', function(ev){
ev.preventDefault()
$.post({
url: $(ev.target).attr('action'),
data: new FormData(ev.target),
processData: false,
contentType: false,
success: function(data){
$('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm- offset-3"><h3>Thanks for contacting me,' + data.name + '. I will get back to you as soon as I can.</h3></div>')
document.getElementById('new_contact').reset()
$('#new_contact input[type="submit"]').prop('disabled', false)
},
error: function(error){
$('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm-offset-3"><h3>Sorry, I need at least a name and valid e-mail.</h3></div>')
$('#new_contact input[type="submit"]').prop('disabled', false)
}
})
})
})
It hits the post request and my server returns with the error:
ActionController::RoutingError (No route matches [POST] "/[object%20Object]"):
I've never encountered this error before and I'm not sure how to go about fixing it. Any help is appreciated.
Try using Rails' remote option for the form, which is a built-in method of handling forms with AJAX.
Your form (in your view) should look like this:
<%= form_for #contact, url: url_for(:controller => :contacts, :action => :create), remote: true, 'data-type': :json do |f| %>
<!-- insert the rest of your form here -->
<% end %>
Your controller can stay as it is (it just needs to return JSON to the form's AJAX requests, which it's already doing), and your JS should change to this:
$(document).ready(function() {
$("form#new_contact").on('ajax:success', function(event, data, status, xhr) {
// The returned JSON structure is available in data.
$('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm- offset-3"><h3>Thanks for contacting me,' + data.name + '. I will get back to you as soon as I can.</h3></div>');
document.getElementById('new_contact').reset();
$('#new_contact input[type="submit"]').attr('disabled', false);
});
$("form#new_contact").on('ajax:error', function(event, xhr, status, error) {
console.log("AJAX request failed.");
// Do something about the failure so the user knows it happened.
});
});
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'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
I'm trying to do a form submission through AJAX in Rails and I am not too sure what is wrong here. I got everything to work using "remote: true" but I want to gain a better understanding of how the AJAX works with jQuery. This is my javascript code:
$(document).ready(function(){
$("#new_user_friendship").on("submit", function(event){
event.preventDefault();
var friendId = $("#user_friendship_friend_id").val();
var _this = $(this);
$.ajax({
url: "/user_friendships",
data: _this.serialize(),
method: "POST",
dataType: "json",
success: function(data){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
}
});
});
});
I am suspecting this line url: "/user_friendships/new?friend_id="+friendId containing the url is the culprit of my errors. I wrote this because a hidden field is being passed as a person's friend id but it throws a "404 error", I've also tried url: "/user_friendships" which doesn't return any errors but it also doesn't properly execute the Javascript as I expected.
This is the corresponding form_for that the AJAX request is sent to:
<div class="friend-request-form">
<%= form_for current_user.user_friendships.build(friend_id: #user), id: "new_user_friendship", method: :post do |f| %>
<%= f.hidden_field :friend_id, value: #user.id %>
<%= submit_tag "Send friend request", class: "button radius tiny", id: "friend-request-button" %>
<% end %>
</div>
What this form does is it sends a friend request to another user using a hidden field.
And in my user_friendships_controller.rb I have this code:
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
#friend = User.find(params[:user_friendship][:friend_id])
#user_friendship = UserFriendship.request(current_user, #friend)
respond_to do |format|
if #user_friendship.new_record?
format.html do
flash[:error] = "There was a problem creating that friend request."
redirect_to user_path(#friend)
end
format.json {render json: #user_friendship.to_json, status: :precondition_failed}
else
format.html do
flash[:success] = "Friend request sent"
redirect_to user_path(#friend)
end
format.json {render json: #user_friendship.to_json, status: :precondition_failed}
end
end
else
flash[:error] = "Friend required"
redirect_to root_path
end
end
If anyone can provide any suggestions or feedback that'd be great!
UPDATE:
Now that I added in data: _this.serialize() and changed the url to: url: "/user_friendships" I'm now getting a 412 (Precondition Failed) error. Despite this error the data is actually being saved into the database. Does anyone know why I'm getting this 412 (Precondition Failed) error?
There is something I do not understand, with the dataType json, you said that you had a precondition failed status right ?
But you wrote
format.json {render json: #user_friendship.to_json, status: :precondition_failed}
So I don't think there is any problem, indeed, it seems to work fine, as you explicitly passed the status in your render command, try removing it and I think you will have a 200 (success) status instead.
Of course, you can keep the previous post ajax request, or use this short version
$.post(
/user_friendships',
{ user_friendship: { friend_id: friendId } },
function(){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
},
'json')
Add a data attribute to the post params instead of passing it in the url:
$.ajax({
url: "/user_friendships",
data: { user_friendship: { friend_id: friendId } }, // <<< Updated
method: "POST",
dataType: "json",
success: function(data){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
}
});
Update
The url should be /user_friendships, assuming that you're using RESTful actions. Have a look to this article about REST in Rails.
Also, when you do an AJAX request like this, your are not sending the rails authenticity tokens that are crated by the form helper. This may be the cause of your 412 (Precondition Failed) error.
See: Understanding the Rails Authenticity Token