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.
Related
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.
I posted question recentry as same
how to use local or instance variable inruby codein coffeescript in haml templ
Getting helpful comment, I'm trying to pass param to controller in ajax but it always returns error callback I can't not find the reason.
Here is my code.
.html.haml
:coffee
$('input#field').change ->
$.ajax
url: '/posts/gaga'
type: "GET"
dataType: "json"
data: { code: $('input#field').val() }
error: (jqXHR, textStatus, errorThrown) ->
alert "error"
success: (data, textStatus, jqXHR) ->
alert "success"
routes.rb
get 'posts/gaga'
posts_controller.rb
def gaga
#model = Model.new
render nothing: true
end
Does anyone know what's wrong my code?
Thanks in advance.
I think your route is incorrect. It should be formatted like this at least:
get "posts/gaga", to: "posts#gaga"
However this might be more what you want if you already have a resources :posts in your routes.rb:
resource :posts do
collection do
get :gaga
end
end
Because then you can avoid repeating get "posts/..." if you plan on adding more custom actions.
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 .
I have on Java web app and another Rails web app.
I need to create a jquery ajax request from java to Rails app.
How to do this.
I tried with this in jquery
$.ajax({
type: "POST",
url:"someurl",
cache:false,
success: function(data) {
//alert here
}
How to give some response to this ajax request from rails?
Is the above code correct ?
In Rails,
def index
#var1 = "myname"
respond_to do |format|
format.js{}
end
end
In index.js.erb,
alert(#var1);
In the console ,
Rendered index.js.erb (0.2ms) Completed 200 OK in 26ms (Views: 6.2ms |
ActiveRecord: 0.1ms)
Normally you can do it in jquery post.
For example:-
$.post( yourURL, {data:data}, function(response){});
yourURL will be the url which should be a valid url to any of the controller method in rails app checked by rake routes.
Then you can create the action in the controller. Suppose you are posting to the 'your_method' of index controller.
action should respond as js .
for example:-
in index controller define
def your_method
#your code here
respond_to do |format|
format.js{}
end
end
Make one js.erb file of the action. After posting to the method from ajax correctly, it will provide some response. Capture it in your response value in jquery post. and make required changes.
Hope this will help you.
Issue was, Ajax does not work on cross domain.
Java is hosted in one domain and Rails in another domain... that was the issue in my case.
I handle Ajax in java side itself now. Works fine.
I think maybe you should add datatype option to your JQuery ajax.
And It's depends on what is the your rails response
dataType: 'script', dataType: 'json' or dataType: 'text' ...
Suppose for example your model name is Post and you are calling the post method in rails it will be something like that.
$('#Button').on('change', function(event) {
var selected_resource_id = $(this).val();
$.ajax({
type: 'POST',
url: "<%= post_path %>",
data: { id: selected_resource_id },
success: function (data) {
alert("Ajax success");
}
});
});
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