Calling a js.erb file with ajax in ruby on rails - javascript

I have the following jQuery function that I'm trying to use with rails to create an alert on a page.
$("#buttonID").click(function() {
foo = $("#otherID").val();
$.ajax({
submitVar: foo //no idea what to do here
type: 'GET',
url: 'controller/action_js',
dataType: 'script'
});
});
in my controller
def action_js
#item = Item.find(:name => foo)
respond_to do |format|
format.js
end
end
action_js.js.erb:
alert(#item);
I'm trying to make it so that when I click the button with id = 'buttonID', an alert appears showing the item in the database whose name equals the value of the field with id = 'otherID'. I have no idea how to use js.erb properly with ajax or how to pass a variable to my js.erb file. Clicking the button currently does nothing.

You can use
jQuery.getScript() method to run it. See details, http://api.jquery.com/jQuery.getScript/
or
$.ajax({
...,
dataType: "script",
..
})
Both these above methods will fetch a script and then execute it.

Related

Issue passing parameter to Rails controller using AJAX

I'm wanting to send a post request from my JavaScript code to my show action in Ruby on Rails which contains data that I want to store in an instance variable so I can save it on a form in my view and upload it to my server.
As you can see below, the parameter 'base64' is showing up in my rails logs, but when I try to call #base64 in my view, after grabbing the value in the controller, it's nil.
Any advice is appreciated, thanks!
View
var full_base64 = "data:image/jpeg;base64," + base64;
$.ajax({
data: 'base64=' + full_base64,
type: 'POST',
url: "/videos/show/<%=#video.id%>"
});
Controller
def show
#video = Video.find(params[:id])
if params[:base64].present?
#base64 = params[:base64]
end
end
Routes
post 'videos/show/:id', to: 'videos#show'
Rails server log:
Started POST "/videos/show/1" for 127.0.0.1 at 2020-01-22 12:59:40 -0600
Processing by VideosController#show as */*
Parameters: {"base64"=>"data:image/jpeg;base64,iV...
...
, "id"=>"1"}
Console
>>
#base64
=> nil
>>
If I understand correctly you are trying to pass AJAX to the show action in your controller. This is a very GENERALIZED answer as you have failed to include any of your HTML code and it looks like you don't have a button to fire the AJAX. But I'll try to point you in the right direction. You need to do something along the general lines of:
var full_base64 = "data:image/jpeg;base64," + base64;
$.ajax({
data: 'base64=' + full_base64,
type: 'POST',
url: "/videos/my_ajax_upload"
});
That will send your AJAX call to a controller method I've called my_ajax_upload but you can call it whatever you like. In your controller you would need something like:
def my_ajax_upload
#video.update(base_64: params[:base64])
respond_to do |format|
format.js {render :action => "base_64_response" }
end
end
This responds to the initial AJAX call by saving the param you sent to the DB and replying by calling a file called base_64_response.js.erb which might look something like:
$('#pic_upload').html('<%= escape_javascript(render :partial => 'base_64_response') %>');
Which will render the HTML file called base_64_response.html.erb which needs to contain the html code you want to appear in the page that called it.
<div id="pic_upload">
<%= #base64 =>
</div>
The cycle is load page -> do something to trigger AJAX call to controller method -> process AJAX call with controller method -> render JS file -> JS file replaces div in page with new html
You probably need to read up more on how AJAX works in Rails. This RailsCast might help http://railscasts.com/episodes/136-jquery-ajax-revised?view=asciicast
Just FYI - I have also noticed strange things in Rails if you do not explicitly define the content type. In your posted example you are not stating the contentType and it could be parsing nil for that reason. When posting base 64 data you can specify the content type as:
$.ajax({
data: 'base64=' + full_base64,
type: 'POST',
contentType: 'application/octet-stream'
url: "/videos/show/<%=#video.id%>"
});
and it may change what the controller parses for the body.
How to post an image in base64 encoding via .ajax?
Just use string instead of symbol for hash key
if params["base64"].present?
#base64 = params["base64"]
end

Reading variable value from Rails controller in view for Rails

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.

Use Ajax or jQuery to Make Table Element in Rails App Load Separate From Page

I have a page with a list of user sites and on it I am making an API call to check the status of something for each site. The problem is that it makes the page take forever to load, so I would like the page to load and then that table element to update after it's done checking using AJAX or jQuery. I'm not great with AJAX or jQuery though and all the Rails/Ajax tutorials I've been reading seem to deal more with forms and data stored within the database. Here's my table element:
Part of My View
<td>
<% if HTTParty.get(site.domain + 'api')["status"] == "ok" %>
OK
<% else %>
Error
<% end %>
</td>
The Controller Action Loading View
def sites_page
#sites = Site.where(user_id: current_user.id)
render 'sites_page'
end
How can I make this load separately as mentioned above? I know I don't have any attempted code yet, but I really don't know where to start.
Thanks for your help.
Just attach AJAX call to the td on window load, it will be evaluated later after page is rendered. AJAX call can be something like this:
$(window).load(function() {
var target = $(".td-that-will-be-evauated-later")
url = target.data("url")
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(result){
target.html(result.body)
},
error: function(xhr, status, error) {
$(target).html("error");
}
})
})
Url should point to the controller action that will fetch information for particular user, for example:
class UsersController < ActionController::Base
def fetch_info
#user = User.find(params[:id])
#response = #user.fetch_info
render json: {success: true, body: response.body}
end
end

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