Reading variable value from Rails controller in view for Rails - javascript

I have an instance variable, #source_code in my Rails controller that I want to retrieve in my Ajax response via the success function. I am calling this Ajax function from my index.html.erb file and it renders a show.html.erb file. I want to get my text area to print out the #source_code.code value.
SourcesController.rb
def show
Rails.logger.debug("REACHED: show >>")
#source_code = Source.find_by(id: params[:id])
Rails.logger.debug("REACHED: source_code >>" + #source_code.code.to_s)
#sources = Source.all
end
index.html.erb
function updateTextArea(source_id){
console.log(source_id);
$.ajax({
type: "GET",
url: "/sources/" + source_id,
data: {source_id: source_id},
success: function (response){
alert("Ajax success")
console.log("<%= #source_code %>");
editor.session.setValue("<%= #source_code %>");
},
error: function(){
alert("Ajax error!")
}
});

Expanding on Nycen's answer, you first want your controller handle the ajax request and return a JSON response:
def show
respond_to do |format|
format.json { render json: Source.find_by(id: params[:id]) }
end
end
PS: Take care with that, it will send all of the fields of your Source record down the wire. I call slice (see ActiveRecord.slice()) on the model to limit the fields returned in the JSON.
Then your JavaSript needs to use the JSON result of that ajax call:
function updateTextArea(source_id){
console.log(source_id);
$.ajax({
type: "GET",
url: "/sources/" + source_id,
success: function (response){
alert("Ajax success")
console.log(response.code);
editor.session.setValue(response.code);
},
error: function(){
alert("Ajax error!")
}
});
It depends on how your routes are setup, but there should be no need to set the data property in the Ajax call. Your route is likely to pull it from the URL path: /sources/12345.
Note there is no show.html.erb with this setup. There is no view, your controller just returns JSON.

You're expecting your success handler to have access to #source_code just like a "show.html.erb" view would, but it doesn't work that way.
When you use ajax, the method is called from the browser; it's a piece of code you send away from your server, it can still interact with it, but it doesn't have access to the controller variables.
So, your show action needs to render something your handler can understand, for instance json. Then you'll have access to it in your success by reading your "response" variable.

Related

Passing a javascript variable (string) to the controller via ajax - 404

I am trying to pass a javascript variable from my view to my controller via ajax according to the example shown here: Passing JavaScript variable to ruby-on-rails controller
my controller "pages_controller.rb" contains the following method:
def test_page
#message= params[:id]
puts #message
end
the respective view "test_page.html.erb" contains javascript with an ajax call which is triggered by clicking a button:
<button id="submit_button">Submit Text</button>
<script>
$("#submit_button").on('click',function(event) {
var string = "helloWorld";
$.ajax({
url: "/test/test_page/?id="+string,
type: "POST",
dataType: "text",
success: function(){
alert('Saved Successfully');
},
error:function(){
alert('Error');
}
});
});
</script>
In routes.rb I have defined the following route:
post 'test/test_page/:id', to: 'pages#test_page'
However, when I press the button I get the defined error-alert and upon inspecting the browser console I see the following error:
jquery.js:11007 POST https://my-website.com/test/test_page/?id=halloWelt 404 (Not Found)
But I can see that "rake routes" shows that the following route is defined:
POST /test/test_page/:id(.:format) pages#test_page
I have tried defining another method in the controller and rerouting, however the 404 error still remains. What can I do to fix this 404 error?
If you're looking to pass the :id to that route, you can use the following url: https://my-website.com/test/test_page/halloWelt. (i.e. "/test/test_page/" + string)
I believe in your AJAX, for a POST request, if you want to pass any other data you should explicitly pass in the data like below, rather than via url parameters.
$.ajax({
url: "/test/test_page/" + string,
type: "POST",
data: { hi: 'there' },
...

Use Ajax to request for rails controller data

I was hoping someone could help me out on this one, and a possible explanation. I have a rails controller called get_songs that will get a hash of songs from the currently logged in user. That said, whenever a particular button is clicked I want to get the data from the get_songs controller at put it in javascript variable. The following is what I have so far.
playlist.js.erb
function get_songs() {
var mysongs;
$.ajax({
type : 'GET',
url : "getSongs",
dataType : 'json',
success : function(response) {
}
});
}
My controlller
class StaticPagesController < ApplicationController
respond_to :js, :json, :html
def get_songs()
if user_signed_in?
session[:user_id] = current_user.id
present_user = User.find(session[:user_id])
present_user = present_user.playlist.keys
#songs = present_user
respond_to do |format|
format.json { render :json => #songs}
end
end
My routes:
match '/getSongs', to: 'static_pages#get_songs', via: 'get'
If everything was working you would do:
success : function(response) {
mysongs = response;
}
The 'response' parameter on the success function is the result of the ajax call you are sending from your controller; the #songs json.
A simple way to debug your javascript (to check what is the value of your 'response' after the ajax request) is to right-click on your browser and click on 'inspect', then go to the 'Sources' tab, look for your javascript file and click the line where you want to add the debug point (in this case the line with 'mysongs = response', then refresh the page. It should stop running at that point and show the value of 'response'.
I think problem in session. When you send request using ajax, you don't send any cookies and session. So try this
$.ajax({
type:"GET",
beforeSend: function (request){
//your token is here
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr("content"));
},
url: "getSongs",
dataType : 'json',
success : function(response) {
console.log(response)
}
});
Also, make sure that you have <%= csrf_meta_tag %> in layouts/application.html.erb
UPD
If you are using gem 'jquery-rails'
and have //= require jquery_ujs in application.js file
Content of csrf_meta_tag automatically will be added to all your ajax requests

$.ajax request in Rails 4 app doesn't render view

I'm new to Rails and I'm trying to submit model data to a controller method, from javascxript, and render the list of results...
function submitResults() {
resultURL = "/result";
resultData = JSON.stringify(results);
$.ajax({
type: "POST",
url: resultURL,
data: { results: resultData},
contentType: "application/html",
dataType: "html"
});
The server shows the controller method is executed and the view is rendered...
Started POST "/result" for 127.0.0.1 at 2014-11-14 17:36:32 -0600
Processing by ResultsController#create as HTML
Result Load (0.7ms) SELECT "results".* FROM "results"
Rendered results/index.html.erb within layouts/application (366.0ms)
Completed 200 OK in 4722ms (Views: 408.3ms | ActiveRecord: 1.3ms)
but the browser doesn't render the view. Here's my create method that's triggered by the $.ajax call...
def create
result = Result.new(result_params)
result.save
#results = Result.all
respond_to do |format|
format.html { render :index }
end
end
Why doesn't the browser load the index view?
You ajax call is not doing anything with the response, define callback functions for it. E.g.:
$.ajax({
type: "POST",
url: resultURL,
data: { results: resultData},
contentType: "application/html",
dataType: "html"
}).done(function(response) {
//attach the response somewhere in the DOM.
});
Check the AJAX doc for all callbacks.
BTW, you usually do not want to load a whole html page through an ajax call. Seems like the page you are rendering includes everything (seems to be using the default layout). In such a case, making AJAX calls can have no benefits (and make things harder) and you might want to do the post through an html form.

Selecting data from another page in Ajax

This is my ajax handling code:
$.ajax({
url: "shirts/first?page=" + params[:page],
type: "GET"
})
How to tell Ajax to take the results from the next page in the shirts/first file?
I wrote the code as I've shown but it throws a error saying 'syntax error'! How can I solve this?
Also my .js.erb file if its of some help:
$("#container1").append("<%= escape_javascript(render 'shirts/first')%>");
If you're performing ajax pagination, you'll have to ensure you can handle the Ajax request on the controller (using respond_to), and send the correct data:
JS
#app/assets/javascripts/application.js
$("a.pages").on("click", function() {
$.ajax({
url: "shirts/first?page=" + $(this).attr("id"),
type: "GET"
});
});
You'd need to have your pagination buttons with the page's ID for this
Controller
#app/controllers/shirts_controller.rb
def first
#shirts = Shirt.where(your_query)
respond_to do |format|
format.html
format.js
end
end
View
#app/views/shirts/first.js.erb
$("#container1").append("<%= raw(escape_javascript(render 'shirts/first')) %>");
you have mixed the rails params and javascript code, in javascript
url: "shirts/first?page=" + params[:page]
has syntax error because of : charachter, and even if you remove it means you have a javascript object named params and page is a variable which refers to a key in the params object, whereas here params[:page] refers to a querystring which its key is page in the current request from the client.
So change it like:
$.ajax({
url: "shirts/first?page=<%= params[:page] %>",
type: "GET"
});
You have to be careful here, cause the code above means the current page is being loaded with the page in its querystrings like: http://example.com/homepage?page=helloworld and helloworld probably is the other page in your story.
and for your .js.erb file, in rails 3.0.8, you have to wrap every escape_javascript call with raw():
$("#container1").append("<%= raw(escape_javascript(render 'shirts/first')) %>");

How to send GET request to rails from javascript

I've been googling all day and still couldn't find any answers.So basically in my javascript function, I want to send a GET request to my rails controller and the rails controller will send back a JSON object. Any idea how do I do this? thnx
Using jQuery I would do something like this:
In the selector and event you want, for instance on clicking some element:
$(function() {
$('#foo').click( function(){
var params = '{"field1": "value1", "field2: "value2"}';
$.get('/controller/bar', params, function(data){
alert(data);
});
});
});
Then in your Rails controller:
def bar
/// hack hack hack
render :json => {"response" => "OK"}
end
The in your routes.rb:
match 'controller/bar' => 'controller#bar'
Finally, change "controller" according to your code. Firebug is your friend!
you can use jQuery ajax to make get or post request from javascript.
jQuery.ajax({
url: "url to controller method", // it should be mapped in routes.rb in rails
type: "GET",
data: {field1 :value1, field2:value2}, // if you want to send some data.
dataType: "json"
success: function(data){
// data will be the response object(json)
}
});
response from rails will something similar to the below, you can modify as per your requirement.
respond_to do |format|
format.js { render :json => #json_data }
end

Categories