I am trying to validate the uniqueness of an email address in my form using ajax but I don't know how to access the JSON data using jquery.
So far when a user enters an email address (currently on keyup ) the input gets sent to the controller and JSON data gets returned with a variable {"email_exists":true} or {"email_exists":false} depending on if the email address has been previously saved to the database or not. This works correctly.
I am using jquery to validate other form functions (email validation, field presence) on form submit, and dynamically showing errors depending on the problem.
My issue is that I have no idea how to access the returned JSON data using jquery. I am also struggling to access it from with erb, <%= p params[:email_exists] %> shows nothing. I am new to JSON and any help would be appreciated, thanks.
EDIT: This is how I'm validating the email address.
new.html.erb
$("#comingsoon_email").on('change keyup paste',function(){
console.log("change?");
$.post('/checkemail?email='+$("#comingsoon_email").val(),function(data){
routes.rb
post '/checkemail', to: 'comingsoons#emailcheck'
comingsoons_controller.rb
def emailcheck
@comingsoon = Comingsoon.search(params[:email])
respond_to do |format|
format.json {render :json => {email_exists: @comingsoon.present?}}
end
end
comingsoon.rb
def self.search(email)
if email
where('email = ?',email).first
end
end
JSON returns
{"email_exists":true} or {"email_exists":false} depending on if the email address has been previously saved to the database or not.
I want to display an error message via jquery if the email address has been taken.
$.ajaxor$.postor whatever) has success and failure callbacks. In those callbacks you access the data. You might want to take a step back and set a breakpoint in the JS debugger and take a look at what the parameters to those callbacks are.