Ajax response in erb from ruby method defined in controller - ruby-on-rails

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.

Related

Can an axios request be used to get a zip file from a Rails endpoint?

I'm trying to make a request to a Rails controller method that responds with a zipped file. How to I make the frontend Axios request?
Controller method:
include ActionController::Streaming
include Zipline
def index
respond_to do |format|
format.zip do
zipline([[#project.attached.url, "#{#project_name.parameterize}.pdf"]], "documents.zip")
end
end
end
What I would do if I were using a view:
= link_to "Download projects", company_projects_path(#company, format: :zip)
What would the equivalent axios request look like? This does not work:
const handleClick = () => {
axios
.get(`/projects/${project.id}`, {
headers: { 'Accept': 'application/zip' }
})
.catch(e => console.log(e))
};
So I found this worked for me:
<a href={`/projects/${project.id}.zip`} download>Download all</a>
Instead of using a button with an onClick axios request that would stream a zipped file to it - which makes no sense - simply creating an anchor tag that has a link to the zip path will download it.
As max pointed out headers: { 'Accept': 'application/zip' } would be the correct format to access it, but it doesn't make sense doing this.
EDIT:
Checkout this answer. The browser will throw an error Resource interpreted as Document but transferred with MIME type application/zip.

Send data to url in ruby ​on rails

I have a problem, I want to send a json that I have to a URL and this is an action in my controller, I want to get this json in my js by means of an http get, the problem is that I do not understand very well how to do it.
All_events is a method in my helper that returns a json
The action of my controller with the data I want to send
def events_calendar
render json: {events: all_events}
end
In my routes.rb:
resources :tools do
collection do
get 'events_calendar' => 'tools#events_calendar'
end
end
My js:
$http({
method: 'GET',
url: "/admin/tools/events_calendar"
}).then(function (response) {
console.log(response);
}, function (response) {
});
When I execute this, this is the result:
Any suggestions on how to solve this error?
You need an AJAX call:
$.getJSON('/admin/tools/events_calendar', function(response) {
console.log(response)
});
Please, check the Working with JavaScript in Rails guide.

Rails - update flash using an ajax post action

I have an action that calls a javascript file which contains an ajax method like this one:
$.ajax({
type: 'POST',
url: "<%= some_action(model) %>",
dataType: 'json',
data: { 'something': true },
success: function(received_data) {
// Do something with received_data
$('#notice').html("<%= escape_javascript(render 'layouts/flash_messages', flash: flash).html_safe %>");
}
});
The "some_action" tries to put some info into flash[:success], and I want to get it in the success function so that I can pass it to the render.
I have already tried the flash.now[:sucess], but nothing. It seems that it is only possible to do this if I write in the flash hash from the action that calls this javascript file - but I don't want this since "some_action" will generate dynamic content.
Is that something possible to to?
Thanks for the help!
you can send js request instead of json request .
and then in your "some_action.js.haml" file you can write
$('#notice').html("<%= escape_javascript(render 'layouts/flash_messages', flash: flash).html_safe %>");
what's happening here is that your javascript file is not getting refreshed hence content of html is not changing .

How to insert into table using link tag

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

Routing in Ajax petition in Rails 2

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

Resources