简体   繁体   中英

Pass variable from JavaScript to Ruby session

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM