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 ?
I would do it like this:
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