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.
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 am trying to use ajax to get information from my controller. Basically I want to know if a data already exists in the DB or not, so my controller will return either true or false.
At the moment I am just trying to set the basic ajax call
in my js file I have the following ajax call, as you can see at the moment I am not really doing any logic because my data is just a placeholder. Later I will add the information I want to query
$.ajax({
type: "GET",
url: "/locations/exists",
dataType: "JSON",
data: { 'locition_exist': loc_exit },
success: function(data) {
console.log(data);
}
});
In my controller I have
def exists
location_exists = true
respond_to do |format|
format.html
format.json {render json: location_exists }
end
end
Later value will go into a method in the model that will query the DB and return true/false.
In my routes I have
resources :locations
get 'locations/exists', to: 'locations#exists'
This code results in the following error
The action 'show' could not be found for LocationsController
I am new to rails and ajax , and I based my code on different examples that I read here, so I am probably just doing a stupid noob mistake.
Thank you very much for your help
When using get or match in routes, you need to define the controller method mapped
get 'locations/value', to: 'locations#value'
update
You saw the same error after updating routes. There are two reasons of this error:
You defined resources :location at first. The url locations/exists itself matches "show" method within resources, with Routes taking 'exists' as the id in #show.
You have not defined show within LocationsController
So, Routes will firstly map the url to locations#show with the :id as 'exists', then hits the controller and found #show does not exist.
The solution after your updating
Of course you can put get 'exists'... before resources but that looks ugly.
Since 'exists' requires no id, it is a collection method. So you can use Routes built-in ways to do that.
resources :locations do
collection do
get 'exists'
end
end
By this all your resources and 'exists' can live.
I've rewritten my question to be more accurate. I have a bankaccounts controller / model.
I have the following method on my controller
def search
##ledgeritems = Ledgeritem.where("bankaccount_id = ? and transactiondate >= ? and transactiondate < ?", params[:bankaccount_id], params[:startdate], params[:enddate])
#bankaccount = Bankaccount.find(params[:bankaccount_id])
respond_to do |format|
format.js { render :partial => "bankaccount/bankledger" }
end
end
I've made two attempts to call this.
Attempt 1
Route for attempt 1
resources :bankaccounts do
post "search"
end
This shows the following route when I do a rake
bankaccount_search POST /bankaccounts/:bankaccount_id/search(.:format) bankaccounts#search
Javascript for calling attempt 1
$.ajax({
type: "POST",
url: "/bankaccounts/" + bank_account_id + "/search.js",
data: $('#edit_bankaccount_' + bank_account_id).serialize(),
success: function (result, status) {
$('#bank_ledger_div').html(result);
}
});
This calls the correct route on my controller, but the server sees it as a PUT instead of a POST and returns a 404.
Attempt 2
Route for attempt 2
resources :bankaccounts do
collection do
post "search"
end
end
This shows the following route when I do a rake
search_bankaccounts POST /bankaccounts/search(.:format) bankaccounts#search
Javascript for calling attempt 2
$.ajax({
type: "POST",
url: "/bankaccounts/search.js",
data: $('#edit_bankaccount_' + bank_account_id).serialize(),
success: function (result, status) {
$('#bank_ledger_div').html(result);
}
});
This calls the update route but still showing as a PUT command. In Firebug I see a 500 error with the following result
Couldn't find Bankaccount with id=search
Usually this error means you're making a GET request instead of a POST request.
For example:
GET /bankaccounts/search is assumed to be requesting the SHOW page for a bankaccount with ID = search
While
POST /bankaccounts/search would correctly hit your action.
Edit:
resources :bankaccounts do
collection do
post "search"
end
end
Is correct as well. Now I'm noticing that you are doing this to get your data:
data: $('#edit_bankaccount_' + bank_account_id).serialize()
that form likely has a hidden field in it, put there by rails, with name='_method' and value='PUT'. That is what is convincing rails that your POST is really a PUT. You'll need to remove that from the serialized data in order to correctly post the form.
If you want the /search url to be used without specifying an id, you should declare it as a collection action :
resources :bankaccounts do
collection do
post "search"
end
end
You can check the routes defined in your app with the rake routes command, to ensure that you defined what you meant.
The URL is expecting the format
/bankaccounts/:bankaccount_id/search
Is the error coming from this method? Could /bankaccounts/search be matching another route?
I have ArtistProduct model. User enters the product details, user can view the entered details in modal window by clicking the preview link before saving the details.
I'm trying to save the data using AJAX by passing all the details like params when it is validated, but it not saving the database.
In view I'm calling AJAX:
var theVal=id+'/'+artist_id+'/'+name+'/'+desc+'/'+price+'/'+story+'/'+artist_name+'/'+dimension+'/'+material+'/'+contact
var theURL = '/add_temp/' + theVal;
$.ajax({
url: theURL
});
In controller I'm handling it like so:
def add_temp
#pro_id=ArtistProduct.where("id=?",params[:id])
if #pro_id.nil?
#artistprod = ArtistProduct.new(:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
#artistprod.save
end
end
UPDATE
Thanks for your reply.
Now am getting Routing error.
In my Router I have like:
match 'add_temp/:id/:artist_id/:name/:desc/:price/:story/:artist_name/:dimension/:material/:contact'=> 'artist_products#add_temp'
UPDATE
Routing Error404 Not Found
No route matches [POST] "/add_temp/P58018/58/Prod/swsx/50/sfdf/null/null/0"
UPDATE
Ya i identified it and corrected it but still also values are not saving into the database. Please help me
In Controller i am doing like so:
def add_temp
if !(ArtistProduct.where("id=?",params[:id]).exists?)
#artistprod=ArtistProduct.new(:id=>params[:id],:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
#artistprod.save
respond_to do |format|
format.html { redirect_to #artistprod.addproduct }
format.js
end
end
end
Hi dbkooper, Thanks for your answer. I tried answer given by u but am getting Routing error
In view am calling like:
var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'product_name='+name+'description='+desc+'product_price='+price+'product_story='+story+'artist_name='+artist_name+'dimensions='+dimension+'material='+material+'contact_number='+contact;
The big problem I see is that your $.ajax call is missing some options. By default, $.ajax defaults to a GET request if no type is specified.
You should change it to:
$.ajax({
type: 'POST',
url: theURL,
success: function (json) {
// handle your success here
},
error: function (response) {
// handle your errors here
}
});
This way, you specify that it will be a POST request and you also have callback methods for handling success and error
I think your routes should be
resources artist_products do
member do
post 'add_temp'
end
end
use rake :routes to get the correct routes
most probab it will be "artist_products/:id/add_temp"
For ajax request it will be you can send the val param's using ? to the url
like
var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'so on..';
$.ajax({ url: theURL });
Inside your controller
you can access params as usual
I have the following in my view:
$('#anID tr').click(function () {
$.ajax({
type: 'GET',
url: '/tickets/extended_info',
dataType: 'script',
data: { id: $(this).find('td:first').html() }
});
});
and this in my tickets controller:
def extended_info(id)
puts ">>>>>>>>>>>>>>> " + id.to_s
end
But I always get 404 not found from the ajax request.
I think I'm missing something in my routes file... I tried several things, but nothing.
Any ideas?
>>>>>>>>>>>>>>>>>>>>> RESOLVED <<<<<<<<<<<<<<<<<<<<<<<<<
I had to add:
map.extendedInfo '/extended_info/:id', :controller => 'tickets', :action => 'extended_info'
to my routes file.
Also, I was using "GET" in my ajax call in my JavaScript ... I changed to POST and now it's working =)
Really seems like routing trouble. Do you have appropriate row for /tickets/extended_info path in your routes.rb? If so, can you post it here?
I suppose something like this
get "/ticket/extended_info", :to => "tickets_controller#extended_info"
in routes.rb and your action on controller should be just
def extended_info
puts params[:id].inspect
end