Could someone tell me why this PUT method doesn't work please.
$.ajax({
type: "PUT",
dataType: "script",
url: '/resources/35',
data:
{
resource : { pos_y: 45, pos_x: 50 }
}
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
Server says that I have used the GET method but in my ajax request I have type: "PUT"
Started GET "/resources/35?resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&_=1344001820350" for 192.168.1.89 at 2012-08-03 15:50:20 +0200
Processing by ResourcesController#show as */*
Parameters: {"resource"=>{"pos_y"=>"45", "pos_x"=>"50"}, "_"=>"1344001820350", "id"=>"35"}
User Load (0.3ms) SELECT "users".* FROM "users"
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "35"]]
Rendered resources/show.html.erb within layouts/login (2.3ms)
Completed 200 OK in 238ms (Views: 235.9ms | ActiveRecord: 0.4ms)
resources_controller.rb
# PUT /resources/1
# PUT /resources/1.json
def update
#resource = Resource.find(params[:id])
respond_to do |format|
if #resource.update_attributes(params[:resource])
format.html { redirect_to #resource, notice: 'successfully updated.' }
format.js
else
format.html { render action: "edit" }
format.js
end
end
end
I have tried adding _method: 'put' But it's still the same
$.ajax({
type: "PUT",
dataType: "script",
url: '/resources/35',
data:
{
resource : { pos_y: 45, pos_x: 50 },
_method: 'put'
}
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
Server:
"resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&method=put&=1344004390840"
Started GET "/resources/35?resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&_method=put&_=1344004390840" for 192.168.1.89 at 2012-08-03 16:33:10 +0200
Processing by ResourcesController#show as */*
Parameters: {"resource"=>{"pos_y"=>"45", "pos_x"=>"50"}, "_"=>"1344004390840", "id"=>"35"}
User Load (0.3ms) SELECT "users".* FROM "users"
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "35"]]
Rendered resources/show.html.erb within layouts/login (0.8ms)
Completed 200 OK in 93ms (Views: 90.5ms | ActiveRecord: 0.4ms)
I'd appreciate any help.
Rails determines the put request via the parameter _method with the value 'put'.
As not all the browsers support the put method, rails cheats in the form_tag. its putting this output in a PUT form:
<input type='hidden' name='_method' value='put'>
So what you have to do is this:
$.ajax({
type: "POST",
dataType: "script",
url: '/resources/35',
contentType: 'application/json',
data: JSON.stringify({ resource:{pos_y:45,pos_x:50}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
Related
I am trying to pass an array of objects from my JS to my Rails controller so that I can loop through the array and check to see if each object exists, and if not, create it. I'm having a difficult time getting my strong params setup properly. Seems like no matter what I do, I'm getting some kind of an error about unpermitted params.
My JS that is creating and sending the data:
function addGame(gameData) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(gameData,"text/xml");
// Check categories and create any new categories that need created
var gameCategories = [];
// for each category in the JSON push into gameCategories
var x = xmlDoc.getElementsByTagName("link").length;
var i = 0
for (i = 0; i < x ; i++) {
var type = xmlDoc.getElementsByTagName("link")[i].getAttribute("type");
if (type == "boardgamecategory") {
var categoryData = {
name: xmlDoc.getElementsByTagName("link")[i].getAttribute("value"),
bgg_id: xmlDoc.getElementsByTagName("link")[i].getAttribute("id")
};
gameCategories.push(categoryData);
}
}
console.log(gameCategories);
// Try sending all of the categories at once
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: '/categories',
type: 'POST',
dataType: 'json',
data: { categories: JSON.stringify(gameCategories)},
success: function (response) {
console.log(response);
}
});
My rails controller
class CategoriesController < ApplicationController
def create
logger.debug category_params
# #category = Category.find_or_initialize_by(category_params)
# if #category.save
# logger.debug "Category Saved"
# else
# flash[:danger] = "There was a problem creating one of the game categories ¯\_(ツ)_/¯"
# redirect_to root_url
# end
end
private
def category_params
params.permit(categories: [])
end
end
Right now if I run this the server log shows
Started POST "/categories" for ::1 at 2019-09-19 21:45:33 -0400
Processing by CategoriesController#create as JSON
Parameters: {"categories"=>"[{\"name\":\"Adventure\",\"bgg_id\":\"1022\"},{\"name\":\"Exploration\",\"bgg_id\":\"1020\"},{\"name\":\"Fantasy\",\"bgg_id\":\"1010\"},{\"name\":\"Fighting\",\"bgg_id\":\"1046\"},{\"name\":\"Miniatures\",\"bgg_id\":\"1047\"}]"}
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
↳ app/helpers/sessions_helper.rb:18
Unpermitted parameter: :categories
{}
No template found for CategoriesController#create, rendering head :no_content
Completed 204 No Content in 95ms (ActiveRecord: 22.8ms)
Thanks in advance for any advice!
Try this
$.ajax({
url: '/categories',
type: 'POST',
dataType: 'json',
data: { categories: gameCategories},
success: function (response) {
console.log(response);
}
});
def category_params
params.permit(categories: [:name, :bgg_id])
end
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!
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.
});
})
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
Here is my JS.coffee codes:
fetchselect =(val) ->
$.ajax(url: '/firstpages/page', dataType: 'json', par_id: val )
$('.homeNav').find('.unactive').click ->
id = $(this).attr('id')
fetchselect(id)
and Here is my controller codes:
def page
#select = Firstpage.where(:pid=>params[:par_id])
respond_to do |format|
format.html # page.html.erb
format.js { render :layout => false }
format.json { render :json => #select }
end
end
It can't pass the params to #select ,when I click $('.homeNav') ,the log tell me:
Started GET "/firstpages/page" for 127.0.0.1 at 2012-09-07 05:27:07 +0800
Processing by FirstpagesController#page as JSON
Firstpage Load (0.2ms) SELECT "firstpages".* FROM "firstpages" WHERE "firstpages"."pid" IS NULL
Completed 200 OK in 2ms (Views: 0.1ms | ActiveRecord: 0.2ms)
Looks like the problem is in the actual ajax request. Try:
$.ajax({
type: "POST",
url: '/firstpages/page',
dataType: 'json',
data: {par_id : val})
})
For more examples, check out the jQuery $.ajax documentation.