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.
Related
<%= form_for(#mymodel, remote: true, html: { id: 'match_form' }) do |f| %>
<!-- I need to check if #mymodel.match_id matches the value generated by a controller function -->
<%= f.submit 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
<%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
<% end%>
<script type='text/javascript'>
$(function() {
$(document).on("click", "#match_submit", function(event){
$.ajax('my_controller_method', {
type: 'GET',
dataType: 'script',
data: {
mid: $("#").val(), // how do I pass #mymodel.match_id here?
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
</script>
I have a form as shown above.
How do I pass #mymodel.match_id in the ajax call above?
In my controller function, I would like to check if passed match_id is a certain value; if not, I would like to display a modal with an error message and just an Ok button. How can I achieve this?
< > a) Should I return the correct value from controller function and check the same in my javascript code above and show a javascript alert?
< > < > i) If yes, then how can I return a number from a controller function to my JavaScript invoking function?
or
< > b) would I be able to render a bootstrap modal with an Ok button in my controller itself?
UPDATE 1:
I tried this to pass match_id and id from mymodel to the ajax call but it did not work:
$(document).on("click", "#match_submit", function(event){
alert ("match id changed!");
alert($("#match_form").data('id'));
alert($("#match_form").data('match_id'));
$.ajax('cpl_evaluate_match_id', {
type: 'GET',
dataType: 'script',
data: {
debit_id: $("#match_form").data('id'),
match_id: $("#match_form").data('match_id')
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
The alerts to print id and match_id print undefined in the alert messages.
UPDATE 2:
I tried this to return a number from my controller function but this doesn't seem to work either:
def evaluate_match_id
puts params[:debit_id]
puts params[:match_id]
return 1
end
the puts above turn up blank
$(document).on("click", "#match_submit", function(event){
alert ("match id changed!");
alert($("#match_form").data('id'));
alert($("#match_form").data('match_id'));
$.ajax('cpl_evaluate_match_id', {
type: 'GET',
dataType: 'script',
data: {
debit_id: $("#match_form").data('id'),
match_id: $("#match_form").data('match_id')
},
success: function(result){
if(result){ // yes or no? 1 or 0, it's the return coming from your controller
alert('true');
alert(result);
}
else{
alert('error');
alert(result);
}
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
The value of result in the success: block in the JavaScript code above comes up as undefined (my controller function blindly returns the number 1 which I was expecting to be the value of result here). So the if(result) condition fails and the else block gets called instead.
You can use the attr to get the value element in jquery. something like this
$('#match_form').attr('id')
some ideas coming from PHP, no exp from ruby-on-rails.
can you pass the #mymodel.match_id in an 'attribute' of your html?
<form data-match_id='#mymodel.match_id'...
or
<form custom_name='#mymodel.match_id' ...
or similar. then, you can use that on ajax to to call the form's data
via Jquery:
$("#match_form").data('match_id')
or
$("#match_form").attr('custom_name')
on your second question, you should have a success function on your ajax, that will return the contents recieved from your controller.
$.ajax({url: "my_controller_method",
data: {
mid: $("#match_form").data('match_id'),
}
success: function(result){
if(result) // yes or no? 1 or 0, it's the return coming from your controller
alert('true');
else
alert('error');
}});
from your controller, you should display the return value instead of just return. (like when you accessed your controller, it will be a white screen with just the return value like 1 or 0)
Lastly, yes you can, or better if you can create a predefined messages for modal ready on your view, and just invoke which message will show on modal.
UPDATE 1:
to properly get the desired attribute on the form, first you need to get the form element properly, on either adding ID or any other method.
<form id="match_form" data-match_id="your_value_here">
from here, you can get the data attribrute 'match_id' using this jquery syntax
var match_id = $("#match_form").data('match_id');
console.log(match_id);
you can try this code on your browser's console (F12 on modern browsers Chrome/Firefox), and it should output your_value_here
on Update 2, you might need to output it, try displaying the number '1' on your controller, then try the ajax, the result will be the number '1'.
hope this answers your question.
I'm new to rails so I don't know if that is the best practice. I'm trying to send user input from index view to the index action using ajax then update the view with user input. I'm not trying to save this input in the database.
The #url always return nil.
NOTE: I try to create a custom action with no luck because it requires a template.
Thanks in advance :)
The index action
def index
#url = params[:option]
end
The index view
<input type="text" id="exampleFormControlInput1">
<p id="resp-result"><%= #url %></p>
<script type="text/javascript">
$(".button").click(function(event){
var userinput = document.getElementById("form").value;
console.log(userinput);
event.preventDefault();
$.ajax({
url:"/responses/",
type: "POST",
data: {option: userinput},
dataType: "text",
success:function(result){
alert("success" + result);
},
error:function(result){
alert("error" + result);
}
});
});
</script>
Yuna you will need to output response in json. lets assume that your ajax script can send data to ruby on rails backend properly.
Try this
at ajax
not this
url:"/responses/",
but
url:"/responses.json",
you can then get result as per
alert("success" + result.myurl);
you can myurl as part of the json response
Finally try this
def index
respond_to do |format|
##url = params[:option]
#url='nancy more url'
format.json do
render json: {myurl: #url}.to_json
end
end
end
I basically want to click a button and then submit a form when the user clicks another button. The form gets submitted but the button doesn't get clicked.
Method in the controller (put):
def set_everything
user.update_column(:everything_set, true)
end
And then I have a form:
<%= form_tag("http://someotherwebsite.com/post_method", method: :post, id:"form")%>
<%= some_field %>
<button type="button" id="form-button">Done</button>
<% end %>
And then on the same view I also have another link_to:
<%= link_to set_everything_path, method: :put, id:"set-everything-button", style:"display:none" %>
My Jquery code:
$(document).ready(function(){
$('#form-button').click(function(){
$('#set-everything-button').trigger('click');
setTimeout(function(){ $('form').submit();}, 2000);
});
});
Now I have also tried using a button_to instead of link_to but it still doesn't get clicked and when I try it manually it works just fine.
Put the target url in a data attribute on the button:
<button type="button" id="form-button" data-trigger-url="<%= set_everything_path %>">Done</button>
Send the PUT request directly in your click handler:
$(document).ready(function(){
$('#form-button').click(function(event){
event.preventDefault();
var form = $(this).closest('form');
var url = $(this).data('trigger-url');
$.ajax({
url: url,
method: 'PUT',
dataType: 'html',
success: function(){
form.submit()
}
})
});
});
Don't forget to send back 200 (OK) response from the controller action so that the javascript runs the success handler (and thus submits the form):
def set_everything
user.update_columns(everything_set: true)
head :ok, content_type: "text/html"
end
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);
}
})
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";
})