I'm currently trying to add a form to my homepage. The survey calculates the needed impressions based on the user input.
The problem is that when I pass the value impressions for example 200 to ajax, it sends a POST request back to the form, but there I have #impressions = params[:impressions] which is nil.
Since #impressions = params[:impressions] already exists with the GET request. The POST request isn`t even showing up in the console.
Ajax code:
$.ajax({
data: 'impressions=' + impressions,
dataType: 'script',
type: 'POST',
url: "/pages/home"
});
Routes:
root to: 'pages#home'
post '/pages/home' => 'pages#home'
PagesController home:
protect_from_forgery :except => [:home]
def home
#impressions = params[:impressions]
end
What would be the right soultion? Probably I should set #impressions = 0 and change the ajax request from POST to PUT ?
Maybe format your Ajax request as Json?
$.ajax({
data: {impressions: impressions}
dataType: 'json',
type: 'POST',
url: "/pages/home"
});
Try below method.
$.ajax('/pages/home', {
type: "POST",
data: 'impressions=' + impressions,
dataType: 'script'
})
Hope this helps!!
Related
I have the following home controller:
class HomeController < ApplicationController
def index
#data = EmergencyFriend.all
#jsonData = JSON.pretty_generate(#data.as_json)
end
def about
end
def alertEmergencyContant
account_sid = "my id"
auth_token = "my token"
#client = Twilio::REST::Client.new(account_sid, auth_token)
#client.messages.create(
to: "+number 1",
from: "+number 2",
body: "hello world !"
)
end
end
Basically, in my home/index.html.erb there is only one button. When the button is pressed it shows an alert message that allows user to select an option to send an SMS to.
What I want to do is to call the alertEmergencyContant method in my home controller so that I can send the message. I also want to pass the phone_number as a parameter with that request. It has been suggested that for this I should use AJAX. I successfully installed jquery and ajax in my rails project and works as expected. What I can't understand is how to create it as a POST request.
My routes list for the home directory are :
root GET / home#index
root GET /home/about(.:format) home#about
But there is nothing on alertEmergencyContant. How to declare that in the routes and make it as a POST request? How to pass attributes from JavaScript to ruby using AJAX?
Here is my ajax request so far (This works):
$.ajax({
url: '/',
type: 'GET',
success: function(event){
alert("sending Message");
}
});
UPDATE:
def about
#thisNumber = params[:phone_number]
puts "helllloooooooooooooo " + #thisNumber
end
function ajaxRequest(){
$.ajax({
url: 'home/about/?phone_number:1244211',
type: 'GET',
success: function(event){
alert("passed");
},
failed: function(){
alert("has failed")
},
done: function(){
alert("after")
}
});
}
You need to add a route to your action
# routes.rb
post 'some_url' => 'home#alert_emergency_contact'
You can now use this in your javascript
$.ajax({
url: '/some_url', // This needs to match what you choose in routes.rb
type: 'POST',
success: function(event){
alert("sending Message");
}
});
PS: Action names are always_snake_case in Ruby, not camelCase
I created a controller, using Rails 3 generator "Controller", and only two actions: create and destroy.
So it generates for me these two lines in routes.rb:
get "mycontroller/create"
get "mycontroller/destroy"
First I change these action to POST and DELETE verbs:
post "mycontroller/create"
delete "mycontroller/destroy"
And I'm using jquery to call these actions, like this:
Calling ˜create˜:
$.ajax({
type: "POST",
dataType: "script",
data:{id: id},
url: "/mycontroller"
})
but it's not working. I need to put "/create" in the url to work:
$.ajax({
type: "POST",
dataType: "script",
data:{id: id},
url: "/mycontroller/create"
})
What is wrong?
Currently I have the following (working) code:
# app/assets/javascripts/show_group_members.js.erb
...
var gid= $(this).data("id");
...
$.ajax({
type: "GET",
url: "/groups/"+gid,
contentType: "application/json; charset=utf-8",
dataType: "json",
...
but I would like to use the routes for a single group resource, i.e.
group GET /groups/:id(.:format) groups#show
So I am trying to use
url: <%= Rails.application.routes.url_helpers.group_path %> + gid,
but I am getting
No route matches {:action=>"show", :controller=>"groups"}
missing required keys: [:id]
(in /home/durrantm/.../linker/app/assets/javascripts/show_group_members.js.erb)
[Update]
The complication here is that the view content itself is generated by a .js.erb template so I still can't use group_path(group) in it.
How can I use the route in js when there is a resource ?
btw I also tried
url: <%= Rails.application.routes.url_helpers.group_path %>,
data: { id: gid },
I think you are doing it wrong. I would forget about placing Rails code into the js and pass the url with data. Thanks to this you separate your Rails code from JS and avoid issues during assets compilation (like what is the host when no request is made?).
# view
<span data-link-url="<%= group_path(group.id) %>"></span>
# js
var link = $(this).data("link-url");
...
$.ajax({
type: "GET",
url: link,
contentType: "application/json; charset=utf-8",
dataType: "json",
...
Using <a href="your_link_to_group_here">
<%= link_to 'my link', group_path(group.id) %>
var link = $(this).attr('href');
Another way to do it, is to use js-routes.
Install the gem:
gem "js-routes"
Include it in your application.js file:
/*
= require js-routes
*/
Then you can do this:
# app/assets/javascripts/show_group_members.js
...
var gid= $(this).data("id");
...
$.ajax({
type: "GET",
url: Routes.group_path(gid),
contentType: "application/json; charset=utf-8",
dataType: "json",
...
The routes helper still needs the resource to be passed to it, even if it's a singular resource. So, your route should look like
Rails.application.routes.url_helpers.group_path(group)
group being the variable where you store your ruby object.
Although, personally, I prefer #konole 's approach.
Because of the complication that the HTML is, itself generated by js (i.e. I get the list of links for the group when I click the 'members' link, via ajax.
So in the end I used:
...
url: "<%= Rails.application.routes.url_helpers.groups_path %>" + "/" + gid,
...
This is my ajax call
$.ajax({
type: "GET",
url: '/posts/product_list.json',
data: {sub_cat_id: parseNumber(sub_category_id)},
dataType: 'json',
success: function(data) {
//$('#selection').show();
$('#selection').html(data.html);
},
error: function(data){
}
});
I have the post_list controller
respond_to :json,only: :product_list
def product_list
#products = Product.where(sub_category_id: params[:sub_cat_id])
##blah blah blah
end
My url is showing like this while inspecting product_list.json?sub_cat_id=5
But the debugger is showing request parameter as follows
{"sub_cat_id"=>"5", "action"=>"show", "controller"=>"posts", "id"=>"product_list", "format"=>"json"}
I am very much confused why this is happening can any one clear it.
It appears you don't have a corresponding route entry. You should have something like this in your routes.rb:
resources :posts do
get :product_list, on: :collection
end
If you only specify resources :posts, your GET request would match the one for GET /posts/:id (look at the output of rake routes), i.e. show action of PostsController with product_list parsed as the id parameter in the request URI. get :product_list defined after those 7 entries would make the router match the URI to the corresponding action and controller.
I have a newsletter box that submits via ajax like this:
function ajax_subscribe(){
$.ajax({
url: '/subscribe',
type: 'post',
data: ({
email: $('#email').val()
}),
success: function(msg){
$('#newsletter_form').hide();
$('#newsletter .done').removeClass('hide');
}
});
}
As you can see I'm currently using type: 'post'
Will that go to the create function in my controller automatically?
This is a great article on the default Rails routes: Rails Routing from the Outside In.
The routes will be the same regardless of whether you're using ajax or synchronous calls.