Only on Rails 6 when:
I receives a json response on pages with url like:
www.site.com/foo
and not when url is like:
www.site.com/foo?q=x
to reproduce:
rails new todo
rails scaffold Todo task:string
rails db:migrate
rails server
Create a task
In file show.json.jbuilder you'll see:
json.partial! "todos/todo", todo: #todo
Go to show page (todo/1)
Type on browser's console to se json response:
$.ajax({
url: window.location.href + ".json",
dataType: 'json',
async: false
});
When your url is "todo/1" jbuilder loads ok:
Started GET "/todos/1.json" for ::1 at 2019-10-28 13:55:54 -0300
Processing by TodosController#show as JSON
Parameters: {"id"=>"1"}
Todo Load (0.3ms) SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/todos_controller.rb:67:in `set_todo'
Rendering todos/show.json.jbuilder
Rendered todos/_todo.json.jbuilder (Duration: 1.0ms | Allocations: 125)
Rendered todos/show.json.jbuilder (Duration: 2.2ms | Allocations: 306)
Completed 200 OK in 10ms (Views: 3.9ms | ActiveRecord: 0.3ms | Allocations: 1565)
But if your url is "todo/1?q=foo" you have no data:
Started GET "/todos/1?q=foo.json" for ::1 at 2019-10-28 13:55:44 -0300
Processing by TodosController#show as JSON
Parameters: {"q"=>"foo.json", "id"=>"1"}
Todo Load (0.2ms) SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/todos_controller.rb:67:in `set_todo'
Rendering todos/show.html.erb within layouts/application
Rendered todos/show.html.erb within layouts/application (Duration: 0.7ms | Allocations: 89)
Completed 200 OK in 25ms (Views: 21.3ms | ActiveRecord: 0.2ms | Allocations: 6547)
Obs: I opened this rails github issue
In order to work in rails 6.0.0 we need to explicitly tell to use json format when the url has queries:
todos_controller.rb
change from:
def show
end
to:
def show
respond_to do |format|
format.html
format.json
end
end
This is because the request must be in the following form:
www.site.com/foo.json?q=x
If you want to pass parameters to the request, you can use the data parameter of ajax.
For instance:
$.ajax({
url: "/todos",
type: "GET",
data: {
id: 1,
q: "x"
},
success: function (response) {
console.log(response.data)
}
})
Related
I'm trying to make a simple ajax request with Rails and Axios, but its seems that I have a routing problem
My Ajax request is make with POST method
axios.post('/post', {
title: title,
pseudo: pseudo,
text: text,
topic: topic
})
.then(res => console.log(res))
.catch(e => console.log(e))
}
My controller have respond_to
respond_to do |format|
format.json { render json: {result: 'ok'} }
end
But Rails processed with the wrong controller and the wrong method, I expected Processing by PostController#create as JSON not Processing by MainController#default as HTML
Started GET "/post?title=&text=++++++++++++&pseudo=" for 127.0.0.1 at 2021-03-16 12:29:23 +0100
Processing by MainController#default as HTML
Parameters: {"title"=>"", "text"=>" ", "pseudo"=>"", "topic"=>""}
Rendering main/default.html.erb within layouts/application
Post Load (1.4ms) SELECT "posts".* FROM "posts" WHERE (topic = '') ORDER BY "posts"."updated_at" DESC LIMIT $1 OFFSET $2 [["LIMIT", 12], ["OFFSET", 0]]
↳ app/views/main/default.html.erb:40
Rendered main/default.html.erb within layouts/application (Duration: 11.2ms | Allocations: 1178)
[Webpacker] Everything's up-to-date. Nothing to do
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 192ms (Views: 188.0ms | ActiveRecord: 1.4ms | Allocations: 11445)
Here my rails routes
Prefix Verb URI Pattern Controller#Action
GET / main#default
GET /:topic(.:format) main#default
comment_index POST /comment(.:format) comment#create
new_comment GET /comment/new(.:format) comment#new
comment GET /comment/:id(.:format) comment#show
post_index POST /post(.:format) post#create
new_post GET /post/new(.:format) post#new
GET /:topic/:post(.:format) post#show
I'm new to Rails and can't seem to figure this out
Every time I click the link it doesn't delete the article, it just takes me to the show view. Not sure why this is happening. Here is my code for the link:
<%= link_to 'delete', article_path(article.id), method: :delete, data: { confirm: "Are you sure?" } %>
my rails server shows a GET request even though I specified the method (I think):
Started GET "/articles/1" for ::1 at 2020-09-07 10:05:13 -0700
Processing by ArticlesController#show as HTML
Parameters: {"id"=>"1"}
Article Load (0.7ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT ?
[["id", 1], ["LIMIT", 1]]
↳ app/controllers/articles_controller.rb:46:in `set_article'
Rendering articles/show.html.erb within layouts/application
Rendered articles/show.html.erb within layouts/application (Duration: 4.0ms | Allocations: 321)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_flashMessages.erb (Duration: 0.2ms | Allocations: 18)
Rendered layouts/_navBar.html.erb (Duration: 0.1ms | Allocations: 5)
Completed 200 OK in 123ms (Views: 96.9ms | ActiveRecord: 0.7ms | Allocations: 5344)
I can't figure out why. Any help is appreciated. Thanks!
I had the same issue in Rails 6. It seems that a wrong version of jquery can cause this. Somehow #rails/ujs stopps working correctly if you install the wrong jquery version.
If you have no errors in your code you can try to fix it by deleting the jquery gem and add jquery through yarn (my question concering this topic)
If I have a url like localhost:3000?id=2 what do I need to change to get my AJAX call to use the param?
page_controller.rb
class PageController < ApplicationController
def index
#pId = params[:id]
#p = Plant.where(id: #pId)
respond_to do |format|
format.json { render json: #p.to_json }
format.html
end
end
end
page.coffee
$ ->
$.ajax
dataType: 'json'
url: 'index.json'
success: (data) ->
alert "Data #{JSON.parse(data)} ---"
development.log for one page load
Processing by PageController#index as HTML
Parameters: {"id"=>"2"}
Rendering page/index.html.erb within layouts/application
[1m[36mPlant Load (1.0ms)[0m [1m[34mSELECT "plants".* FROM "plants" WHERE "plants"."id" = $1[0m [["id", 2]]
Rendered page/index.html.erb within layouts/application (3.0ms)
Completed 200 OK in 80ms (Views: 69.5ms | ActiveRecord: 1.0ms)
Started GET "/index.json" for ::1 at 2017-01-26 08:07:18 -0800
Processing by PageController#index as JSON
[1m[36mPlant Load (1.0ms)[0m [1m[34mSELECT "plants".* FROM "plants" WHERE "plants"."id" IS NULL[0m
Completed 200 OK in 5ms (Views: 0.1ms | ActiveRecord: 1.0ms)
This is just a very basic example taken from a much more complicated piece of code. Everything in my original code works except for when I'm trying to access to param.
update 1
routes.rb
Rails.application.routes.draw do
get 'index' => 'page#index'
root "page#index"
end
Your URI for the Ajax request doesn't include the parameter. You're making a call to index.json and not index.json?id=1
I'm unable to pass a variable to my controller using the data parameter of an AJAX call. What am I doing wrong?
show.html.erb
var parentStepID = 20;
$.ajax({
url: "/steps/create_branch",
type: 'GET',
data: {parent: parentStepID}
});
controller
def create_branch
parentStepID = params[:parent]
logger.debug("parentStepID: #{parentStepID}")
respond_to do |format|
format.js
end
end
The logger does not seem to get the parentStepID:
Started GET "/projects/20/steps/create_branch" for 127.0.0.1 at 2013-03-06 11:56:44 -0500
Processing by StepsController#create_branch as HTML
Parameters: {"project_id"=>"20"}
Project Load (0.1ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1 [["id", "20"]]
####################################################################
parentStepID:
Rendered steps/create_branch.js.erb (0.1ms)
Completed 200 OK in 16ms (Views: 10.6ms | ActiveRecord: 0.1ms)
Browser console:
20 0:412
/projects/20/steps/create_branch 0:413
Also, I believe the AJAX request is working properly; I created a file called "create_branch.js.erb"' in my steps views folder and put in an alert that is successfully called.
I have some javascript that displays some data from my database on my webpage. I also have a button that when the user clicks it some logic occurs in the controllers and then I want to have the data displayed changed. However, at the momment when they click the button nothing happens (page is not reloaded). Could you guys help me set that up? Here is what I have so far:
controller:
class QtlsController < ApplicationController
require 'json'
require 'uri'
$rollback = nil
def index
logger.debug "\nrollback is: #{$rollback}\n"
render "index"
end
def rollback
$rollback = params[:version].gsub(/"/,'')
redirect_to :action => :index
end
end
view:
<%- if $rollback.nil? %>
generates one type of table
<%- else %>
generates another type of table
<%- end %>
...some other logic and buttons etc...
jQuery(function() {
jQuery( "#rollback").button();
jQuery( "#rollback").click(function() {
var version = getSelectedText('version_selector');
jQuery.ajax({
type: "POST",
headers: {
'X-Transaction': 'POST Example',
'X-CSRF-Token': jQuery('meta[name="csrftoken"]').attr('content')
},
url: "/qtls/rollback",
data: {version: JSON.stringify(version) },
dataType: 'json',
sucess: function() { alert("Success! Rollbacked"); }
});
});
Here is what is in log files when I go to the page and when I click the rollback button:
Started GET "/qtls" for 10.64.229.59 at Tue Jul 17 16:48:52 -0500 2012
Processing by QtlsController#index as HTML
rollback is:
ROLLBACK IS NIL!!!
Qtl Load (2.0ms) SELECT `qtls`.* FROM `qtls`
Rendered qtls/index.html.erb within layouts/application (404.8ms)
Rendered shared/_user_nav.html.erb (1.3ms)
Rendered shared/_nav.html.erb (1.3ms)
Rendered shared/_footer.html.erb (0.6ms)
Completed 200 OK in 544ms (Views: 540.9ms | ActiveRecord: 2.0ms)
Started POST "/qtls/rollback" for 10.64.229.59 at Tue Jul 17 16:48:57 -0500 2012
Processing by QtlsController#rollback as JSON
Parameters: {"version"=>"\"test1\""}
Redirected to http://10.10.136.244:4000/qtls
Completed 302 Found in 3ms (ActiveRecord: 0.0ms)
Started GET "/qtls" for 10.64.229.59 at Tue Jul 17 16:48:58 -0500 2012
Processing by QtlsController#index as JSON
rollback is: test1
Rendered qtls/index.html.erb within layouts/application (37.7ms)
Rendered shared/_user_nav.html.erb (3.3ms)
Rendered shared/_nav.html.erb (4.3ms)
Rendered shared/_footer.html.erb (2.0ms)
Completed 200 OK in 99ms (Views: 97.4ms | ActiveRecord: 0.0ms)
it's a reaaaaaally bad style to use global variables like $rollback!
if you want to store user-data use your session-object.
use the jquery-rails gem to integrate with jQuery in your views and then use the :remote => :true in your form, so that rails can handle the form-submission.