0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.