Pass variable from JavaScript to Ruby session - javascript

I have a simple input text field:
<input type="text" id="master_password" size="20" placeholder="Master Password" />
<a class="btn btn-default" id="master_submit" href="#">Submit</a>
And some javascript listening:
$(document).ready(function() {
$('#master_submit').click(function() {
alert("sometext");
});
});
The alert works, obviously. I want to store the text field (#master_password) in session[:master_pass] as I will be using it to decrypt many passwords stored in the database. I'm pretty sure I have to use some AJAX, but not familiar with it at all. What code would I replace the alert with in the js file (or view, or controller, of course) to store the data as a Ruby variable?

Assuming you're using Rails, you could use javascript to make an AJAX request to the Rails app, and then in Rails, you could set the session value.
In Javascript (jQuery):
var data = "password=" + encodeURIComponent($('#master_password').val());
$.ajax({
url: '/my_controller/action',
data: data,
type: 'post'
})
.done(function(response) {
// Do something with the response
})
.fail(function(error) {
// Do something with the error
});
And in Rails, setup a controller with the appropriate route, and in the action:
class MyController < ApplicationController
...
def action # << name whatever you like
session[:password] = params[:password]
end
...
end

Related

Laravel : How to pass variable from View (javascript) to Controller? [duplicate]

This question already has an answer here:
How to send a variable from JS to my Laravel Controller
(1 answer)
Closed 2 years ago.
I'm extremely new to Laravel (level -0). Our backend guy used it for a web app that we are developing. So after googling i finally figured out how to pass variables from Controller to View. Now i need to pass from View to Controller. I saw that there are some question regarding this but the way its been asked/answered i really dont understand. So what i have now is
Controller :
public function index()
{
$title = "Congratulations";
$messageOne = "You've learned something new!";
$messageTwo = "Remember all the tips!";
return view('pages.index',compact('title','messageOne'));
}
View (where i want the string to be displayed) :
<div>
{{$title}}
<br>
{{$messageOne}}
</div>
These messages (messageOne, and others) will change depending on button click which is controlled via js. I was thinking in the js function i could have a variable set like :
$('thebutton').click(function(){
var buttonclicked = "learning";
})
then send that variable to Controller then in Controller (im not sure how to code it but..) check what the string of buttonclicked variable is and depending on the string return to View the message string. From searches i have to also tweak the Route (which im not sure about as well)?
is that flow possible? otherwise, advice on how i can do this will be appreciated.
UPDATE
the suggested link to another question in the comment helped which answers the question. also, all the answers helped in some way so im not sure which to choose. Do i have to choose only 1?
One way you can send it using the $.ajax() or the other way you can send it using query parameters like so:
<a href={{ route('route-name', ['param 1' => 'Param 1 Value', ......]) }}Click me!</a>
Then in your route define your route as following.
Route::get('/url/{param1}/{param2}/.....', 'ControllerName#MethodName')->name('route-name');
Then go to your controller and define your function like so:
use Illuminate\Http\Request;
public function functionName(Request $request){
// Get your variables from $request
$param1 = $request->param1;
$param2 = $request->param2;
}
In JS you should use ajax for passing data from view to controller for example
$('thebutton').click(function(){
var buttonclicked = "learning";
//her xyz your url
$.get( "xyz", { value: buttonclicked } )
.done(function( data ) {
//write your code after success
});
});
then in controller get the value from ajax request
public function test(Request $request){
dd($request->value);
}
View to Controller. You can post data via ajax call.
or Submit the form data to controller form post method
<form method="post" action="/controller" />
<input type="text" value="100" id="txt" name="txt" />
<button type="submit"/>
</form>
Once submit data 100 go to controller. By this way we can pass data to controller.
JS to Controller Pass data
var pincode = $('#pincode').val();
$.ajax({
type:'POST',
url:"{{ route('post_data') }}",
data:{"_token": "{{ csrf_token() }}","postal":pincode},
success:function(data){
//Success code
}
});
Controller code like below
public function post_data(Request $request)
{
$postal_code = addslashes($request->all()['postal']);
}
Hope it helps

How to make a "condition if" in php when the <span> is changed? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
View
<input type="text" id="textToDisplay" />
<br />
<input type="button" value="Add message" onClick="showMessage()" />
<br />
<span id="messageSpan"><span>
JS
function showMessage() {
var message = jQuery("#textToDisplay").val();
jQuery("#messageSpan").text(message);
}
By the way, i'm using laravel. Basically, what I want to do is, if user input 22 then it will shows success message. All these do it in php without changing/adding in js. jsfiddle example
Basically my idea is like this,
<?php
if(<span id="messageSpan"><span> == 22)
success
else
<span id="messageSpan"><span>
?>
You cannot do this like the way to describe it above. You either have to do in using only javascript / jquery or you use both languages (php and javascript) and
sent an ajax request to your server do something there and return some data to your client (javascript) and show that in your view.
I added some comments so that the process is better to understand, if you have any questions just ask.
I would do this using ajax so you are going to use javascript and php which should be better for you right now.
So this is your html markup:
<input type="text" id="textToDisplay" />
<br />
<input type="button" value="Add message" onClick="showMessage()" />
<br />
<span id="messageSpan"><span>
And now you are going to sent the input value using ajax to your controller, like this:
$(document).ready(function(){
// on each key up we are going to sent the value later you should probably change this and sent the value after you click on a button
$('#sentMessage').keyup(function(){
// this holds the current value of the input field
var inputValue = $(this).val();
// you are going to sent the input data to this route '/showMessage'
// you are going to use the post method
$.ajax({
type: "POST",
url: '/showMessage',
data: {
inputValue: inputValue
},
// if you post is successful then do following ....
success: function(data) {
// here we are just going to show the message inside you span, the returned data comes from your controller
$("#messageSpan").text(data.inputValue);
},
// if there was an error do following ....
error: function(data) {
// if there was an error you could just show a message with some error message
$("#messageSpan").text('ERROR!');
}
});
});
});
In your Laravel Controller class you need have have a function like this:
public function showMessage(Request $request)
{
// $inputValue contains the inputValue data from your ajax call
$inputValue = $request->inputValue;
// You could / should also do some validation here later on ...
// Thus you should probably save the data, I do not know what excatly you are going to do with it later ...
// now we are sending back the data
return response()->json($inputValue);
});
What you also have to do it to create a proper route so that your ajax request finds it.
So in your routes.php you need to createa a route like this:
Route::get('/showMessage', ['as' => 'showMessage', 'uses' => 'YourController#showMessage']);

How to pass a JavaScript var into a Rails Controller

I'm looking to pass a JavaScript variable into a Rails Controller. The interesting part is that the variable is generated inside Canman, and I cannot use it (yet) outside of it.
This is probably just JavaScript and not necessarily related with Canman. But I'm just not sure what it is happening here.
The approach I'm following (but completely open if there is a better way) is to populate a hidden field with jQuery, just to access the data via params from the controller.
If possible (and if this is a good practice) I will like to avoid the form, and just call some JavaScript on click and then pass that variable to the controller.
View
= form_for #post do |form|
= form.hidden_field :base64
= form.submit
JavaScript
$('form').submit(function(event){
Caman('#canvas', img, function() {
var imageBase64 = this.toBase64();
alert(imageBase64); // works fine
$('#post_base64').val(imageBase64);
});
alert(imageBase64); // nothing
});
PostsController
def update
#post = Post.find(params[:id])
raise '¯\_(ツ)_/¯'
...
end
post_params
=> {"base64"=>""}
Also, I read that an option could be to make an AJAX request. However, I'm not sure how to proceed with that, yet.
At some point, I tried with a text_area instead of a hidden_field. The text_area got populated with the right data. However, params never got the data. If I got back via the browser button, the data was in the text_area, and clicking on submit one more time, populates the params as expected.
Thanks in advance!
Short answer: Ajax.
The goal was to send the value of a variable (a base64 image) to my rails controller, and once there, keep going just with Ruby.
At the end, I created a simple Ajax function to send data from my client (Image from browser) to my server (Rails Controller) via params
save_canvas.js
$(document).on('click', '.save_canvas', function() {
event.preventDefault()
var base64Data = canvas.toDataURL('png')
$.ajax({
type: "POST",
url: "http://localhost:3000/pictures/",
data: { image: base64Data },
success: function(post){ console.log('success') },
error: function(post){ console.log(this) }
})
})
pictures_controller.rb
def create
#picture = Picture.new(image: params[:image])
#picture.save
redirect_to #picture
end
I got support to achieve this here

How to pass an argument from javascript to a Servlet through JSP

I'd like to do something like that
function(){
<% ExampleClass sample = new ExampleClass(); %>
var ID = 4;
var something = <%= sample.getSomethingById(ID) %>
}
How can I pass this ID to the jsp expression?
Thanks for any suggestion, and sorry id the question is not so well formulated.
you can also use more advanced methods and tools, like Ajax and JQuery:
function submitToJsp(){
$.ajax({
type: 'POST',
url: 'mypage.jsp',
data: {
id: '123',
comment:$('#comment').val()
},
beforeSend:function(){
// this is where we append usually a loading image
},
success:function(data){
// successful request; do something with the data
$('#output').html(data);
},
error:function(){
// failed request; give feedback to user
}
});
}
In short, by calling the function submitToJsp(); we send an asynchronous (ajax) request to the mypage.jsp jsp with 2 parameters.
use hidden variable and then put the id into that variable.You can not pass using the code above.
<input type="hidden" name="test" value="your id" />
Then you can access like request parameter.
Your javascript code is not executed until after the JSP page has been rendered. So any java variables you want to access in your script needs to be pre-rendered as a javscript variable. After the page has been rendered, you can't execute java code in your javascript. You can't "share" variables between java code and javascript like that. Your example is probably simplified, but in this case, you could just do
var something = <%= sample.getSomethingById(4) %>
You should use hidden field :-
<input type="hidden" name="hdtest" id="idtest" value="<%=sample.getSomethingById(ID) %>" />
Now inside javascript try to access the value.
Try this code in java script :
var something = document.getElementById('idtest').value;
Hope it will help you.

update table cell

this is my html form:
<form name="input" action="html_form_action.asp" method="get">
<input type="checkbox" id="mycheckbox">Don't show me again<br>
<input type="submit" id="Submit">
</form>
I have a table, is called: "mytable". this table contains: name(string), box(boolean).
I tried to do the next thing:
when the user checked the box of don't show me again, I want to update the box of the table (assuming the row with id=6).
p.s. the box of the table inits to False.
so I have to do something like:
$("#submit").click(function() {
if($("#mycheckbox").is(':checked')) {
//here I have to update the table in the database
}
});
how can I do that?
I found examples with php but I don't want to do it with php.
UPDATE:
based on your answers, I want to do it with Ruby-on-rails.
I found this:
update_sql = "update mytable set box = TRUE where id = 6"
affected_rows = Job.connection.update(update_sql)
any help appreciated!
You need to create a controller that accepts the ajax request but first update the js to this one.
# js
$("#submit").click(function() {
$.ajax({
url: '/my_tables/' + <id of resource to update>,
type: 'PUT',
data: { my_table: { box: $("#mycheckbox").is(':checked') } }
});
});
create a controller called MyTablesController
# my_tables_controller.rb
class MyTablesController < ActionController::Base
def update
#my_table = MyTable.find params[:id]
#my_table.update_attributes params[:my_table]
# do something else here like a redirect ...
end
end
that's the gist of it. If you can't make it work, you may need to start with more basic tutorials. Good luck!
$("#submit").click(function() {
if($("#mycheckbox").is(':checked')) {
$.ajax({
url: 'post.php',
cache: false,
success: function() {
alert("done");
}
});
}
});
You can use $.ajax to update your table in database. Just create post.php file and set up a query in there which updates table.
Also, PHP uses mysqli to connect to database in latest versions. mysql_ functions are deprecated.
Unfortunately, you need some sort of server script like php to communicate with mySQL :(
Query mySQL natively from JQuery without the need for PHP etc
You can use any language you like on the server (even JavaScript), but you need server side code to process the HTTP request (which you can make from JavaScript using XMLHttpRequest) and interact with the database.
(Note: "any language you like" is limited by what is installed or what you can install on your server (or a server you move to).)

Categories