Pavan
Pavan

Reputation: 33542

Can't get the duplication check working with ajax in rails

I'm trying to call a method with ajax which checks for duplicate email. Below is my code

#users_controller.rb
def check_email
  email = User.find_by(email: params[:email]) #record exists

  if email
    #return true
    render :json => { status: "true" }
  else
    return false
  end
end

#view code

<input type="email" name="email" id="s_email"  placeholder="Email"/>
<span id="duplicate_email"></span>

#jquery
$('#s_email').on('change keyup paste', function() {

  var email = $('#s_email').val();
  $.ajax({
    url: '/users/check_email',
    data: {"email": email},
    type: 'GET',
    dataType: 'json',

    success: function(status){
      if (status == 'true') {
        $('#duplicate_email').text("Email Already Exists! Try Different Email");
      }
    }
  });
});

#server log
Started GET "/users/check_email?email=pavan%40xyz.in" for 127.0.0.1 at 2016-11-28 11:45:02 +0530
Processing by UsersController#check_email as JSON
  Parameters: {"email"=>"[email protected]"}
Redirected to http://localhost:3000/
Filter chain halted as :login_check rendered or redirected
Completed 302 Found in 0ms

Problem: Though the record exists, the error never shows up.

What I'm doing wrong?

Upvotes: 0

Views: 67

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

The problem is in the error Filter chain halted as :login_check rendered or redirected looks like an authentication error. Also staus == 'true' should be staus.status == 'true' according to your action code.

Upvotes: 1

Related Questions