Routing in Ajax petition in Rails 2 - ruby-on-rails

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

Related

Ajax response in erb from ruby method defined in controller

I have a ruby controller file with various methods defined, i want to get response of one of the method in erb i.e frontend using ajax call.
I am a beginner in ruby, so doesn't have much experience of handling requests in ruby, when i try to run the below code it gives error 404 in console stating url not found.
I have added relevant code snippets instead of entire code.
=> appcontroller.rb file
def returnimage_url
image_url = "http://dfdabfyag.jpg" //random url
{ :success => true, :img_value => image_url }.to_json
end
=> loadimage.erb file
<script>
function showImage(){
$.ajax({
url: '/returnimage_url',
method: 'GET',
dataType: "json",
success: function(response){
let image_data = JSON.parse(response);
console.log(image_data);
}
});
}
showImage();
</script>
You need to map the path /returnimage_url to your appcontroller.rb file and the specific method.
That should be done in your config/routes.rb file using something like this:
get 'returnimage_url', to: 'app#returnimage_url'
That will work if you rename your appcontroller.rb to app_controller.rb
See routing documentation for more info.
There are more issues in your code, but this should point you in the right direction and resolve the 404.

Rails 5: ajax post request not working correctly

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!!

Link_to target '_blank' combined with controller action

I have the code:
= link_to image_tag(image_info), 'web-site', :target=>'blank'
which works great to open the site in a new tab BUT -
The image is an advertisement that I am hosting and I want to also record the fact that the image was clicked and time and other details.
Is there a way to combine the link_to, target '_blank' with a call to a controller action?
You can achieve that with Javascript and to record the click time you need to define an action which will save the time and other details.
= link_to image_tag(image_info), 'web-site', class: 'save-time'
JS:
$('.save-time').on('click', function(e){
e.preventDefault();
var linkUrl = $(this).attr('href');
$.ajax({
url: '',
type: 'POST'
success: function(response){
if(response){
window.open(linkUrl, '_blank');
}
}
})
});
Hope that helps!
One non-Javascript way of going about this would be to create a controller action that:
Does whatever tracking you want to do
redirects to your external website.
Then set your link up so that it calls your controller action directly.
As a very simple example, that would benefit from a bit more sophistication:
Route
# config/routes.rb
# [...]
get 'tracking/:url_id', to: 'tracking#redirection', as: 'track_redirection'
Controller
# app/controllers/tracking_controller.rb
class TrackingController
def redirection
url = {
1 => 'google.com',
2 => 'bbc.com'
}[params[:url_id]]
TrackingClass.new(url, current_user).track
redirect_to url
end
end
View
= link_to image_tag(image_info), track_redirection_path(1), target: 'blank'
This will create an internal link to /tracking/1 which your controller will then redirect to the correct url.
You can link to the controller method path
link_to "controller/method", target: 'blank', method: :post do
image_tag image_path("whatsapp-icon.svg")
end
Routes
# config/routes.rb
resources :controller do
post "method" => "controller#method"
end

rails ajax call redirect to invalid path

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.

Error adding custom route to controller

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?

Resources