I have a method to translate different strings in Product class from English language to another. It has two variables: string and language. And for the first one I expect to get current value of the text area. Here how it looks like in JS:
var primary_value = document.getElementById('primary_body_html_value').getElementsByClassName('note-editable')[0].innerText;
And then I want to use this method inside JS function:
var translated_string = "<%= GoogleTranslator.translate(primary_value, 'de') %>"
The main question is how can use this 'primary_value' inside 'translated_string'? As I know - I can use Ajax but I am a bit new to this and I don't understand how to write correctly a method for Ajax and for Product controller. In case if you need a controller code:
class ProductsController < AuthenticatedController
before_action :set_product, only: %i[show edit update]
def index
if params.include?('id')
redirect_to edit_product_path(params[:id]) and return
end
end
def edit
redirect_to products_path, error: 'product not found' unless #product
render :edit_polaris
end
def update
if #product.update(product_params)
render json: {
status: :ok,
notice: 'Saved successfully!'
}, status: 200
else
render json: {
status: :error,
error: 'Something Went Wrong'
}, status: 400
end
end
private
def product_params
params.permit(
:id,
primary_locale: {},
locales: {}
)
end
def set_product
#product = Product.find(product_params[:id])
end
end
This is just a sketch but hopefully can help you out.
It can be inside one of your existing controller methods, for the sake of the example lets say you added a route (and controller method) called translated_string to ProductsController.
#ProductsController
def translated_string
primary_value = params[:primary_value]
#translated_string = GoogleTranslator.translate(primary_value, 'de')
render json: {translated_string: #translated_string}
end
Now when something happens on your DOM page where primary_value is set, you send primary_value via ajax to translated_string and you get the json response with the translated string back - u can do whatever you want with it. This is just an example, there are a million ways to go about it, hope this gives you a direction.
Related
I work on a task manager app, and I want to create html div 'cards' (with title, duration etc...), with all the datas I got on a database in rails.
I guess that I have to use javascript functions, but I can't get a way to do it.
I saw a lot of things on google, but I can't find exactly javascript calls from a rails controller (because I only catch all datas in the controller).
Here is my controller :
def new
# Retrieve all tasks in the project
#taskModel = Task.new()
#projectTasks = #taskModel.getProjectTasks()
# Add tasks on html
(0..#projectTasks.length).each do |i|
respond_to do |format|
format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
end
end
end
and my js file :
window.createTask = (title, content, duration) ->
card = document.createElement('div');
document.getElementsByClassName('content')[0].appendChild(card);
With my code, I get this error : ActionController::UnknownFormat
ActionController::UnknownFormat indicated that your ajax request is interpreted as a request with the wrong format. To answer this part better you'd have to post the javascript with the ajax call.
Secondly, you have to rethink the render in this block
(0..#projectTasks.length).each do |i|
respond_to do |format|
format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
end
end
You are calling respond_to multiple times which is just wrong. Put this loop into a new.js.erb view.
What is the current best solution to fix the problem that rails respond_with returns an empty body with status 200 on successful PUT requests, but Ember (JQuery) expects a valid JSON response, therefore javascript warnings are shown?
I could of course replace respond_with in the rails code with if/render/then/render/end, however that loses the brevity and I would prefer not to do that. I have been checking and in some places I read that this should already be fixed in JQuery, but with the below versions I still get the same problem.
Ember : 1.5.1
Ember Data : 1.0.0-beta.8.2a68c63a
Handlebars : 1.3.0
jQuery : 1.11.0
Ah yes, Rails PUT requests. Best I came up with was to fill in the response myself, like so:
def update
book = Book.find(params[:id])
updated_book = BookUpdater.new(book, user: current_user).update(permitted_params)
respond_with do |format|
if updated_book.errors.present?
format.json { render json: { errors: updated_book.errors }, status: 422 }
else
format.json { render json: updated_book, status: :ok }
end
end
end
Gotta keeps the Embers happy.
This question already has answers here:
How to pass Ruby variables to a JavaScript function in a Rails view?
(6 answers)
Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file
(2 answers)
Closed 8 years ago.
i'm new in Rails and in a controller i have:
class PagesController < ApplicationController
def home
#temp = "Hello"
end
end
I have read that i must put the javascript code in application.js (tell me if true) and i have:
window.onload=function(){alert("<%= j #temp %>")}
Obviously that alert print the string "<%= j #temp %>"
How can i pass the variable #temp to the javascript so that the alert can print Hello?
Thanks
I wrote an article on how to pass Ruby objects to the client. Ryan Bates also has an excellent RailsCast on passing data to JS.
Add a div to your view that corresponds to your the PagesControlle#home action that will not be visible when you load the page but will contain the data stored in the Ruby objects:
# views/pages_controllers/home.html.erb
<%= content_tag :div, class: "temp_information", data: {temp: #temp} do %>
<% end %>
Load the page with this div included and view the page source. You can see your Ruby objects stored in the .temp_information div. Open up the JavaScript console to access the Ruby objects as JavaScript objects:
$('.temp_information').data('temp')
You do not need to add your JS to a JS partial, you can also use the asset pipeline.
I do something similar to, but simpler than gon. I have the following in my ApplicationController.
def javascript_variables(variables)
#javascript_variables ||= {}
#javascript_variables.merge!(variables)
end
Within a controller action I can then do something like
def some_action
javascript_variables(user: current_user)
end
In my ApplicationHelper I have something like this
def javascript_variables(variables = nil)
#javascript_variables ||= {}
#javascript_variables.merge!(variables) and return if !variables.nil?
output = ''
padding = #javascript_variables.keys.group_by(&:size).max.first
#javascript_variables.each do |variable, value|
output << "#{variable.to_s.ljust(padding)} = #{value.to_json},\n "
end
raw "var " + output.strip.html_safe.gsub(/\,\Z/m, ';')
end
and finally in my layout's <head> I have
<script>
<%= javascript_variables %>
</script>
This gives me something like this (from a real example in my application)
<script>
var pageModule = "site/index",
isCustomer = false,
utype = "normal",
isAnonymous = true,
keyboardShortcuts = false,
pubnub = null,
requestToken = "3zj974w074ftria3j";
</script>
Take a look at this.
http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs
One of the easiest ways is to use js.erb file, where you can do ruby tags to access variables that you defined in the controller action.
You need to use a respond_to block in the controller action, specifying the action to be able to respond to javascript.
items_controller.rb
class ItemsController < ApplicationController
def action
respond_to do |format|
format.js
#format.html {} # These are for allowing other types of formats to be responded to.
#format.json {} # But they are not necessary for using this js.erb way of doing things.
end
end
end
/views/items/action.js.erb
$(div).html('The cat has erased your page');
I am currently trying to use AJAX in my application via jRails. I am trying to return a JSON object from my controller, and then parse it in my Javascript. I am using json2.js to do the parsing.
Here is the code I currently have:
function getSomething()
{
$.ajax({
type: "GET",
url: "map/testjson",
success: function(data) {
var myData = JSON.parse(data[0]);
window.alert(myData.login);
}
});
}
and in the controller:
class Map::MapController < ApplicationController
def index
end
def testjson
#message = User.find(:all)
ActiveRecord::Base.include_root_in_json = false
respond_to do |w|
w.json { render :json => #message.to_json }
end
end
end
The window.alert simply says 'undefined' (without tics).
However, if I change the javascript to window.alert(data) (the raw object returned by the controller) I get:
[{"salt":"aSalt","name":"",
"created_at":"2010-03-15T02:34:25Z","remember_token_expires_at":
null,"crypted_password":"aPassword",
"updated_at":"2010-03-15T02:34:25Z","id":1,"remember_token":null,
"login":"zgwrig2","email":"zach#zach.com"}]
This looks like an array of size 1, if I'm looking at it correctly, but I have tried just about every combination of JSON.parse on the data object that I can think of, and nothing seems to work.
Any ideas on what I'm doing wrong here?
EDIT
This seems to work fine if there is more than one row in the Users table.
When there are more than one row, what you are deal is a String of your object in json format, not your json object representation.
Really sorry for me english, i want explaind better ...
And if #message is a null object, because there isnt any messange, the render to json dont make anything, and when you are in your JS, you will have a problem because you dont have any response which worker. You must check your #message object. Maybe you can do that:
w.json {render :json => (#message.nil?) ? 0 : #checkpoint }
then, in your callback function you must check if your data response is "0" (like string) or one object.
I can see what you have 2 problems in your code.
It is better if you use $.getJSON to do a JSON request.
jQuery is yet a parser of JSON... then in your callback function you only must do:
$(data).each(function(i, user){
// what you like do with a user
});
In your rails response there a error, is not a w.json { render :json => #message.to_json }, is only w.json { render :json => #message }. Whiout ".to_json".
Hope that helps.
I have this to calling the choose_category:
{ :action => :choose_category, :id => category } do %>
And I have this method to calling the choose_category.js.rjs:
def choose_category
begin
category = Category.find(params[:id])
rescue
ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
# flash[:notice] = "Invalid product"
redirect_to :action => :index
else
respond_to { |format| format.js }
# redirect_to_index
end
end
I want to call back the category name, how can I do that? I try this, but it return nothing for me.
page.alert(#category.name)
Your problem is that #category isn't defined in your RJS template.
RJS files are essentially views that generate Javascript. Like views, they have access to instance variables set in the controller, but not local variables.
Putting this in the begin section of your action should solve your problem.
#category = Category.find(params[:id])
I'm not sure of this since I'm not very familiar with js and rjs, but I would add to your rjs something like this:
category_name = <%= #category.name %>;
and then
page.alert(category_name)
or just:
page.alert(<%= #category.name %>)
If you can write your own JavaScript why not use the Ruby's to_json() method to output your object in JSON to an embedded constant on your page and then write some JavaScript to access this variable and manipulate as needed?