How to work with rails render with ajax javascript request - javascript

I have action in controller
def login
#message = params[:mess]
#user = 1
render :rend_log_form
end
the view - rend_log_form.js.erb
l = $("#log_form");
console.log(<%= #message %>);
l.html("<%= j(render(partial: 'login/log_form', locals: {user: #user})) %>");
and some javascript code
$.ajax({
type: "POST",
url: "/login",
data: {mess:"eee"},
success:function(data) {
console.log("SUCCESS POST");
console.log(data);
},
error:function(data) {
console.log("ERROR POST:");
console.log(data);
}
});
action and controller works ok if use link_to with remote: true, but with my javascript code I have in browser console:
ERROR POST:
Object
the Object.responseText - the code of rend_log_form.js.erb
How to render the form with javascript?

Thanks to Hary Bomrah, adding dataType:"html" to ajax call in js code has helped.

Related

Gon variable not passing to js from rails controller during Ajax request

I'm trying to create a jackpot betting site (just as a challenge). I have a method in my controller to update the pot when a user adds money to the pot. I display the pot total on the homepage and would like to update it with Ajax as soon as someone adds money to the pot. I'm using the gon gem to pass variables such as the pot total from my controller to my javascript. It works when the page is reloaded but not when the update method is called with ajax.
Heres my PagesController:
def home
#jackpot = Jackpot.last
gon.pot = #jackpot.pot
end
JackpotsController:
def update
#jackpot = Jackpot.find(params[:id])
if params.has_key?(:amount)
#jackpot.update(pot: #jackpot.pot + params[:amount].to_f)
gon.pot = #jackpot.pot
end
respond_to do |format|
format.js
end
end
Javascript: (In the url the :id is hardcoded for now)
$("#bet-btn").click(function() {
$.ajax({
type: "POST",
url: "/jackpot/update/21",
datatype: "json",
success: function() {
console.log("Pot size: " + gon.pot);
updatePot();
},
error: function() {
console.log("error")
}
});
});
This updates the donut progress bar for the pot
function updatePot() {
updateDonutChart('#jackpot-donut', gon.pot , true);
}
Button to place bet: (amount also hardcoded)
<%= link_to "Place Bet", update_pot_path(#jackpot, :amount =>
0.1), method: :post,:remote => true, id: "bet-btn", class: "btn btn-info btn-lg" %>
I'm pretty new to rails and especially javascript/ajax so any help would be appreciated. Thanks!
In the controller, simply respond to JSON:
respond_to do |format|
format.json { render json: { pot: #jackpot.pot } }
end
Specify the dataType when posting with $.ajax. Notice that the new data is bieng passed to the success function, so it's not gon.pot, but data.pot.
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data) {
console.log('pot', data.pot);
}
});

Rails 4: Ajax 400 Bad Request

I'm trying to upload a data_uri image from my webcam by ajax with rails uising this gem
For that I have a custom function on my PicturesController.rb:
def upload_image
data_uri = params[:data_uri]
#picture = Picture.new(picture_params)
#picture.user_id = current_user.id
if data_uri
#picture.photo = data_uri
end
#picture.save
end
and the javascript on my page:
function save_photo() {
Webcam.snap( function(data_uri) {
$.ajax({
type: 'POST',
url: '/pictures/upload',
async: true,
data: { data_uri: data_uri }
})
.done(function () {
console.log(data_uri);
});
// shut down camera, stop capturing
Webcam.reset();
} );
}
I'm also use the gem rack-cors to solve cross domain problems.
My route.rb
resources :pictures do
collection do
post 'upload', :action => :upload_image
end
end
But when I call the ajax function I getting the 400 (Bad Request)
The console show the error:
ActionController::ParameterMissing - param is missing or the value is empty: picture:
Has anyone had this problem before?
Thanks!

Rails: Simple Ajax post to filter index results

I have a checkbox on my trailers index page that, when checked, should filter the results.
trailers_controller:
class TrailersController < ApplicationController
respond_to :html, :js
def index
trailers = Trailer.last(40).sort_by(&:published_at).reverse
trailers = trailers.select { |t| t.budget == "blockbuster" } if params[:show_indie] && params[:show_indie] == "false"
#trailers = Kaminari.paginate_array(trailers).page(params[:page]).per(6)
end
end
And my view:
<div class="trailers">
<%= render #trailers %>
</div>
And my js:
<script>
$(function(){
$('.checkbox-inline').on('change', function() {
var show_indie = $(this).find('input').prop('checked')
$.ajax({
url: '/trailers/filter',
type: "post",
async:true,
dataType: "html",
data: {show_indie},
success: function() {
console.log ("filtered")
},
error: function(){
console.log ("error with ajax")
}
});
})
});
</script>
routes:
post 'trailers/filter' => 'trailers#index'
And my index.js.erb:
console.log('index js loaded')
$('.trailers').html("<%= escape_javascript render(#trailers) %>");
Everything seems to work, the AJAX is posting okay. But the index.js.erb is not rendering. I have a feeling it's because my dataType is "html" instead of JSON or something.. But not really sure how that works, or how to fix it.
What am I doing wrong?
Is this the best way to handle this kind of filtering?
You need to specify dataType as "script"
$.ajax({
method: "GET",
url: "test.js",
dataType: "script"
});
To add to the answer, you need to remember not to store your javascript in your views directly. To make your application run efficiently & properly, you need to use the unobtrusive javascript pattern:
#app/assets/javascripts/application.js
$(document).on('change', '.checkbox-inline', function() {
var show_indie = $(this).find('input').prop('checked')
$.ajax({
url: '/trailers/filter',
type: "post",
dataType: "script",
data: {show_indie},
success: function() {
console.log ("filtered")
},
error: function(){
console.log ("error with ajax")
}
});
});
This will not only free up your views, but also allow you to factor the JS into your asset pipeline, making it more efficient.

How to pass Rails variable to AJAX response function?

In AJAX I write:
$.ajax({
URL: '/new_avatar',
type: 'POST',
data: { username: 'alizade' },
success: function(response){
alert(response);
},
})
Route.rb:
post '/new_avatar' => 'avatars#new_avatar'
Avatar.rb model:
self.new_avatar(username)
Avatar.where(username: username).select('avatar').last
end
Avatars_Controller:
def new_avatar
#username = params[:username]
#result = Avatar.new_avatar(#username)
end
So, how can send #result to AJAX response function and alert the database selection result?
Assuming you need only response from this service, you can use following way to get the result.
def new_avatar
#username = params[:username]
render :json => Avatar.new_avatar(#username)
end
you need to use render :text in your controller method
def new_avatar
#username = params[:username]
#result = Avatar.new_avatar(#username)
render :text => "#{#username} has this result:- #{#result.inspect}"
end

What am I doing wrong with this AJAX request using a form_for in Rails 4?

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

Categories