Rails 4: Ajax 400 Bad Request - javascript

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!

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: Unpermitted parameter

I have a model Picture where I take a photo with webcam and save it. I upload the images with carrierwave, and generate the image with the gem carrrierwave-data-uri The image is sent by ajax
the function on my PicturesController.rb is:
def upload_image
photo = params[:picture][:photo]
#picture = Picture.new(picture_params)
#picture.user_id = current_user.id
#picture.photo = photo
#picture.save
end
private
def set_picture
#picture = Picture.find(params[:id])
end
def picture_params
params.require(:picture).permit(:photo, :comment, :user_id )
end
end
My Ajax
function save_photo() {
Webcam.snap( function(data_uri) {
$.ajax({
type: 'POST',
url: '/pictures/upload',
async: true,
data: { picture: {photo: data_uri} }
})
.done(function () {
console.log(photo);
});
Webcam.reset();
} );
}
When I send the image, it is registered on database, but not the image. I getting the console error:
Unpermitted parameter: image
But if I add the parameter :image on my strong parameters, I get the Completed 500 Internal Server Error
The data uri is printed on my console, but I can't put it in a image variable
Thanks by help!
You get 500 Internal Server Error when permitting image because you don't have an image attribute in the model. You have photo instead, so you should use it as the parameter to send data_uri in the ajax method.
Change image in the AJAX call to photo:
data: { picture: { photo: data_uri } }
Also make change in your controller method like this:
def upload_image
#picture = Picture.new(picture_params)
#picture.user_id = current_user.id
#picture.save
end

How to work with rails render with ajax javascript request

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.

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

Use ajax to post back to same page

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

Categories