Adding javascript values into Ruby Hash [duplicate] - javascript

This question already has an answer here:
Accessing Javascript variable from ruby
(1 answer)
Closed 5 years ago.
Passing data from Ruby to Javascript is easy, for example:
<script type="text/javascript">
function change_value(val){
alert ("<%= #alert %>")
}
}
</script>
This will sent an alert with the data stored at the alert variable in the controller.
But I don't know how it works in the opposite direction, for example, if I need to store an element id into a controllers variable:
<script type="text/javascript">
function change_value(element){
<% #element_id = *** element.id *** %>
alert ("<%= #element_id %>")
}
}
</script>
The real deal is up next, the code surrended by *** are supposed to be the needed javascript values (#billeable_qts is a Hash):
<script type="text/javascript">
function change_value(product){
<% #billeable_qts[****product.id****] = ***document.getElementById('product.id').value**** %>
<% #billeable_qts.each do |key, value| %>
<% alert = "Key = " + key + ", value: " + value.to_s%>
alert ("product: <%= alert %>")
<% end %>
}
</script>

As everyone has suggested, you can't do it the way you're wanting.
A simple workaround would be to create a method (or use one that's already in your controller), and then do an ajax call to the method.
For example, do an ajax call to the update method of the first product, and pass in the variables you want to update in the params:
var value = document.getElementById('product.id').value
var id = 1
$.ajax({
url: '/products/' + id,
type: 'POST',
data: {
product: {
value: value,
}
},
success: function(result) {
location.reload();
},
error: function(err) {
console.log(err);
}
})

Related

Rails + JS + Ajax request

Hi I'm making simple clone of game where is Waldo (Wally) with Rails + JS + Ajax. The idea is: player becomes 3 images and has to check where 3 characters (Waldo,Wilma,Wizard) are. After 3. image shows up field to submit name and after submit show high score list.
So far, i have code the mechanism for time (JS variable with setInterval), points (JS + AJAX + rails controller) but i can't code the action for submit name, points and time to model.
My view file:
<%= form_tag('/check/highscore', method: :post, format: :js, remote: true ) do %>
<%= text_field_tag 'name', 'enter your name' %>
<%= submit_tag 'submit' %>
<% end %>
<script type="text/javascript">
$.ajax({
url: "<%= highscore_check_index_path %>",
type: "POST",
format: "js",
dataType: "script",
data: { username: $(this).username, score: guessd, time: time },
success: function(data) {
$('send_highscore').append('data.username')
window.waldo.HS()
},
});
};
my controller file:
def highscore
#username = params[:name]
respond_to do |format|
format.js { render :layout => false }
format.html
end
end
def highscore2
record = Highscore.new
record.username = params[:username]
record.score = params[:score]
record.time = params[:time]
record.save
end
my highscore.js.erb
console.log("<%=j #username %>");
window.waldo.HS = function(username) {
$.ajax({
url: "<%= highscore2_check_index_path %>",
type: "POST",
format: "js",
data: { username: name, score: guessd, time: time },
success: function(data) {
console.log(data);
$('send_highscore').append('data.username')
}
});
});
I know, my oode is very bad quality, but i try to learn it now. Problem is that the highscore.js.erb is not executed although i see it in firebug rendered as a js script file.
The idea of highscore.js.erb is to mix ruby and js variables and together sent do highscore2 action in check controller and save to db.
js.erb is a bad way to learn.
Ruby on Rails can be used as a kind of poor mans Single Page Architecture by using remote: true and returning JS.erb responses. But all it really does it gives you enough rope to hang yourself.
Its a really bad way to learn ajax as it leads to poor code organisation and a very non RESTful application as it leads to a focus on procedures instead of resources.
I instead encourage you to try to learn ajax without mixing ERB and JS. Mixing server side and client side logic just makes everything much more complicated as you have to keep track of what is happening where.
Instead you might want to focus on setting up reusable javascript functions in app/assets/javascripts and fetching JSON data instead of javascript procedures.
This will teach you not only to do ajax in Rails but also how to do it with external API's and teach you valuable lessons about how to structure and organise code.
So lets start looking at how to refactor:
Highscores should be a resource.
Lets start by setting up the routes:
resources :highscores, only: [:create, :index, :show]
And the controller:
class HighscoresController < ApplicationController
respond_to :json, :html
def create
#highscore = Highscore.create(highscore_params)
respond_with #highscore
end
def index
#highscores = Highscore.order(score: :desc).all
respond_with #highscores
end
def show
#highscore = Highscore.find(params[:id])
respond_with #highscore
end
private
def highscore_params
params.require(:highscore).permit(:username, :time, :score)
end
end
Responders is a pretty awesome tool that makes it so that we don't have to do a bunch of boilerplate code when it comes to returning responses. Our create method will return 200 OK if it was successful and 422 BAD ENTITY or some other "bad" response code if it failed.
Some javascript scaffolding
Lets set up a little bit of scaffolding so that we can hook our javascript up to a specific controller and action without using inline script tags.
Open up layouts/application.html.erb and replace the <body> tag:
<%= content_tag :body, data: { action: action_name, controller: controller_name } do %>
<%= yield %>
<% end %>
Then add this little piece to applicaiton.js:
// Triggers events based on the current controller and action.
// Example:
// given the controller UsersController and the action index
// users:loaded
// users.index:loaded
$(document).on('page:change', function(){
var data = $('body').data();
$(this).trigger(data.controller + ":loaded")
.trigger(data.controller + "." + data.action + ":loaded");
});
Where is that ajax y'all was talkin' bout?
Lets say we have a list of highscores that we want to update either at regular intervals (polling) or when the user submits a highscore.
// app/assets/javascripts/highscores.js
function getHighscores(){
var $self = $('.highscores-list');
return $.getJSON('/highscores').done(function(highscores){
var elements = $.map(highscores, function(h){
return $('<li>').text([h.username, h.score].join(', '));
});
$self.empty().append(elements);
});
};
$(document).on('games:loaded highscores:loaded', function(){
// refresh highscores every 5 seconds
(function refresh(){
getHighscores().done(function(){
window.setTimeout(refresh, 5000);
});
}());
});
That last part is a bit hairy - its a recursive function that sets a new timer when the ajax call has completed. The reason we use this and not setInterval is that setInterval does not care if the previous call was completed or not.
Creating Highscores.
First lets russle up a form:
<%# app/views/highscores/_form.html.erb %>
<%= form_for(local_assigns[:highscore] || Highscore.new), class: 'highscore-form' do |f| %>
<div class="field">
<%= f.label :username %>
<%= f.text_field :username %>
</div>
<%= f.hidden_field :score %>
<%= f.hidden_field :time %>
<%= f.submit %>
<% end %>
And then lets spiff it up with some ajax goodness:
$(document).on('games:loaded highscores:loaded', function(){
$('#new_highscore').submit(function(e){
$.ajax(this.action, {
data: {
highscore: {
username: this.elements["highscore[username]"].value,
time: this.elements["highscore[time]"].value,
score: this.elements["highscore[score]"].value
}
},
method: 'POST',
dataType: 'JSON'
}).done(function(data, status, jqXHR){
getHighscores();
// todo notify user
});
return false; // prevent form from being submitted normally
});
});

Rendering an object passed through Pusher in Rails

I am trying to implement a realtime chat application.
I'm using pusher to notify server about the button click, and then pass the message object as message to a subscriber. What I need to do is, render that message in other user's chat screen(show.html.erb) dynamically. Here is my cycle:
// MessagesController.rb
def create
conversation = Conversation.find(params[:conversation_id])
message = Message.create(content: params[:content], user_id: params[:user_id])
conversation.messages << message
Pusher['test_channel'].trigger('my_event', {
message: message
})
end
And my subscriber is
// show.html.erb
// some html code
<ul class="chats">
<%= render #messages %>
</ul>
// some html code
<script>
// some js code
var channel = pusher.subscribe('some_channel');
channel.bind('some_event', function(data) {
// What to do here?
});
</script>
This assumes you are using jquery. It's also untested so may have a few bugs/syntax errors.
Ajax method:
JS
channel.bind('some_event', function(data) {
$.ajax({
url:'/messages/'+data.message.id,
success:function(html){ $('.chats').append(html)}
});
});
routes:
match '/messages/:id' => "messages#show_no_layout"
controller:
def show_no_layout
#message = Message.find(params[:id])
render "show", layout: false
end
view(show.html.erb):
<%= *whatever you want in here* %>
ICH(read more) method:
This will of course require adding an extra js file which is why its not my first suggestion.
Template:
<script id = "messageTemplate" type = "text/html">
{{ message.content }}
// plus whatever else you want.
</script>
channel.bind('some_event', function(data) {
messageHtml = ich.messageTemplate(data.message);
$('.chats').append(messageHtml);
});
If you are using JQuery,
channel.bind('some_event', function(data) {
$('.message').text(data.message);
});
See this tutorial.

Rails returning GET response as HTML, not redirecting

Running the following code shows that the Controller and the View are receiving and parsing the JSON appropriately, and returning HTML. (This can be seen through the alert in the call back function.)
However, what I want is for the browser to be redirected to /json_test/main, not to just receive the HTML in response.
Controller:
class JsonTestController < ApplicationController
def main
#postData = params[:scores]
end
def test
end
end
main.html.erb:
<h1>JsonTest#main</h1>
<p>Find me in app/views/json_test/main.html.erb</p>
<% #postData.each do |key, value| %>
<p><%= key %> : <%= value %></p>
<% end %>
test.html.erb:
<script type="text/javascript">
var postUrl = "<%= json_test_main_path %>";
var postJson = JSON.parse('{ "scores" : { "player1": 5, "player2": 6 } }');
$.get(postUrl, postJson, function(data, status, xhr) {
alert("Data: " + data + "\nStatus: " + status);
}, "html");
</script>
Any help would be appreciated.
What's the point of doing an AJAX request if your goal is to redirect the user unto another page?
There is no point.
Nonetheless, you can add a success callback in your $.get which redirects the browser.
.done(function() {
window.location.href = "http://stackoverflow.com";
})

rails 4.0.1 can't show ruby code in view via javascript ajax

I'm trying to update vote count via ajax once user has voted. My code works fine except for something which should be pretty basic, which is showing the new total number of votes.
My javascript has the following code:
var voteCount = "<%= #trip.total_up_votes %>";
...
$.ajax({
...
success: function() {
console.log("SAVED TO VOTES TABLE SUCCESSFULLY");
$('#voting_up').html(voteCount);
},
...
});
Once the vote link has been clicked, everything gets added to the table fine except it shows the new vote count as <%= #trip.total_up_votes %> i.e. as a string. The total_up_votes method simply counts the number of up votes from the votes table. This works fine when the page is first loaded or when it's refreshed.
I've tried escape_javascript and many other suggestions after trawling through the internet but I'm still stuck. Could someone help please?
EDIT:
As requested, my votes_controller does this:
def cast_vote()
#vote = Vote.where("user_id = ? AND trip_id = ?", current_user, params[:id]).first || Vote.new(:user_id => current_user)
#vote.vote_type = params[:vote_type]
#vote.user_id = params[:user_id]
#vote.trip_id = params[:id]
respond_to do |format|
#vote.save
format.html {redirect_to :back}
format.js
end
end
Have you tried dropping the quotes?
var voteCount = <%= #trip.total_up_votes %>;
...
$.ajax({
...
success: function() {
console.log("SAVED TO VOTES TABLE SUCCESSFULLY");
$('#voting_up').html(voteCount);
},
...
});
This is all overkill. You should use the ruby ajax helper "remote". use this:
<%= link_to "Vote up", vote_up_path, remote: true %>
The remote: true above will tell the browser to handle the link via ajax, so the page will not get reloaded. vote_up_path is just an example. Lets say vote_up_path takes you to the controller action votes#upvote, then in your votes views folder you should have a file called upvote.js.erb. In that file, have the following code:
var voteCount = <%= #trip.total_up_votes %>;
console.log("SAVED TO VOTES TABLE SUCCESSFULLY");
$('#voting_up').html(voteCount);

how to get a variable in the link_to path

I am trying to use a variable in the following link_to call:
<%= link_to '<button type = "button">Players</button>'
.html_safe, live_players_path(:Team => #tmf) %>
but every time i click this it no longer has the value of the variable which was set here:
<select id = "FilterTm">
<option>Select a Team...</option>
<% Abbrv.order("Team").each do |abbrv| %>
<option><%= abbrv.Team %></option>
<% end %>
</select>
using an ajax call:
$(document).ready(function(){
$('#FilterTm').change(function(){
Tm = $('#FilterTm').val();
SelectTm = true;
$.ajax (
{
url: "http://localhost:3000/live_players.json' +
'?TmFilter="+Tm+"&Selected="+SelectTm,
type: "get",
dataType: "json",
cache: true,
success: function(data) {
alert("Loading Players....");
},
error: function(error)
{
alert("Failed " + console.log(error) + " " + error);
}
});
});
});
So in summary, I select a Team from the select dropdown, which triggers the ajax, which set the #tmf variable in the controller, but when clicking the link_to, the variable (#tmf) is nil. How can i get the variable to stay so it can be used later?
This gets rendered on the server & sent to the client during the first request from the user:
<%= link_to '<button type = "button">Players</button>'
.html_safe, live_players_path(:Team => #tmf) %>
The ajax request is a separate request. Changing #tmf on the server during the ajax request only changes #tmf on the server. It has to be sent to the client. You will have to make the server side of the ajax request send the new #tmf value to the client, then write custom javascript to set the value of the href. Something like this:
No need to use rails here...
<a id="playerBtn"><button type="button">Players</button></a>
THe javascript pseudocode:
var playerBtn = $("#playerBtn");
...
success: function(data) {
alert("Loading Players....");
playerBtn.href= "url/?Team=" + data.tmf;
},
Btw for others that see this post I really just used:
$('selector').attr('href', 'url');
selector being the element, and the url being the requested information.

Categories

Resources