How to check user email uniqueness and pass result to jQuery?

I have this problem : I'm checking user email in controller and sending json successfull response if it is already taken and add css styling of input, also I need to prevent submit and add some message.

Here is my checkemail action ( used this article - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery ):

def checkemail
  if !User.where('email = ?', params[:email]).empty?
    format.jsonr do
      render :json => { 
        :status => :ok, 
        :message => "Success!",
      }.to_json
    end
  end
end

and in my routes:

         checkemail GET    /checkemail(.:format)

          match "/checkemail", to: 'edit_user#checkemail'

and my jQuery:

   $('#user_email').focusout(function() {
    $.getJSON('/checkemail', { email: $('#user_email').val() }, function(data) {
        $('#user_email').addClass("error");
      });
   });

my HTML input code:

     <input id="user_email" name="user[email]" size="30" type="email" value="">

from mime_type initializers file:

    Mime::Type.register_alias "application/json", :jsonr, %w( text/x-json )

From Fiddler:

  Request : GET /checkemail?user@mail.com HTTP/2.0

  Response(RAW tab) : 
  Missing template edit_user/checkemail

  JSON tab is empty

QUESTIONS: How to inspect is json request sent ? How can I prevent submission form and add some message ?

Answers


I would do it like this:

$('#element').focusout(function() {
  $.getJSON('PATH_TO_EMAIL_CHECK_ACTION', { email: $('#element').val() }, function(data) {
    // The data should tell you if its unique or not, you do something
    // here depending on response 
  });
});

And in the controller, check if the email is taken. If its not, send back render json with status OK and message success. You can check if the status is success in your callback where the comment is above.

jquery focusout - http://api.jquery.com/focusout/

jquery getJSON - http://api.jquery.com/jQuery.getJSON/

About json responses in controller - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.