Reputation: 59
I'm working on sms-validation function onto Sinatra site. And I got this code:
post '/coop/sendcode' do
@code = Random.rand(1000..9999).to_s
phone = params[:phone].to_s
HTTParty.get('http://sms.ru/sms/send?api_id=' + api_id + '&to=' + phone + '&text=' + @code)
end
And this view:
%form
%div.form-group
%label Phone
%input#phone.form-control{:name => "phone", :placeholder => "7 950 123 45 67"}
%button#sendsms.btn.btn-default{"data-toggle" => "modal", "data-target" => "#myModal"} Send
And this JS:
$(document).ready(function(){
$("#sendsms").click(function(){
var phone = $("#phone").val();
$.ajax({
url: "/coop/sendcode",
data: {"phone": phone},
type: "post"
});
});
$("#checkcode").click(function(){
var serversCode = @code
var usersCode = $("#code").val();
if (serversCode == usersCode) {
console.log("good: srv - " + serversCode + ", usr - " + usersCode);
} else {
console.log("bad: srv - " + serversCode + ", usr - " + usersCode);
}
});
});
After user types phone number, he press on Send button, which opens modal window (with button#checkcode) where he can type a validation code from sms. But this code doesn't work, and main question is how to pass @code variable from Ruby to JS?
Thank you in advance.
Upvotes: 0
Views: 499
Reputation: 485
Try using this gem: https://github.com/gazay/gon-sinatra
It will allow you to set the code in the controller like this:
gon.code = @code
and access it in the javascript in a similar way:
var serversCode = gon.code
Upvotes: 1