Reputation: 953
I have built simple payment system. A part from system is autorize user to create advertisement, but before it can happen user has to fill in text field simple confirmation code. Code is from SMS.
I added AJAX blur so when focus is lost application would check if confirmation code is valid.
So far I have like this:
In SMS controller:
@token = ('0'..'9').to_a.shuffle.first(5).join
@payment.token_salt = BCrypt::Engine.generate_salt
@payment.token_hash = BCrypt::Engine.hash_secret(@token, @payment.token_salt)
I am not saving token as plain text, I am saving just salt and hash as security precaution. It works great.
In Advertisement controller:
def checktoken
@payment = Payment.where('identifier = ?', params[:identifier])
if @payment.present?
if @payment.token_hash == BCrypt::Engine.hash_secret(params[:token], @payment.token_salt)
render :nothing => true, :status => 200
else
render :nothing => true, :status => 409
end
else
render :nothing => true, :status => 409
end
return
end
This method would find required advertisement by identifier
and then check if given token hash is the same as in database. So I need 2 values to get to work this code. params[:token]
and params [:identifier]
I managed to send first one:
In form:
<% text_field(:identifier,:value=> @advertisement.identifier, :'data-validate' => '/advertisements/checktoken') %>
<%= text_field(:token,:placeholder=> "Kods *" ,:'data-validate' => '/advertisements/checktoken') %>
In routes.rb
collection do
get 'checktoken'
end
My script:
$(document).ready(function(){
$('[data-validate]').blur(function() {
$this = $(this);
$.get($this.data('validate'), {
token: $this.val()
}).success(function() {
$this.removeClass('field_with_errors');
}).error(function() {
$this.addClass('field_with_errors');
});
});
});
Question is how to pass @advertisement.identifier variable value in the same maner as I am doing with token ?
I googled for this, but there wasn't valid examples just how to do with single value.
Any help would be great. Thanks
Upvotes: 0
Views: 37
Reputation: 1671
You could set id
attribute on those fields and you can use it later as selector.
In your view:
<%= text_field(
:identifier,
:value => @advertisement.identifier,
:'data-validate' => '/advertisements/checktoken',
:id => 'identifier_field'
) %>
<%= text_field(
:token,
:placeholder => "Kods *",
:'data-validate' => '/advertisements/checktoken'
:id => 'token_field'
) %>
In your javascript code:
$(document).ready(function(){
$('[data-validate]').blur(function() {
$this = $(this);
$.get($this.data('validate'), {
token: $('#token_field').val(),
identifier: $('#identifier_field').val()
}).success(function() {
$this.removeClass('field_with_errors');
}).error(function() {
$this.addClass('field_with_errors');
});
});
});
Upvotes: 1