0

I am trying to make a verification in ajax if an email has already been taken in laravel 5.

This is my ajax:

$.ajax({
    type: 'POST',
    url: '/EditEmail',
    data: form.serialize(),
    dataType: 'json',
    timeout: 9000,
    error:function(data) {
        //verify if the user has already been taken 
    },
    success:function(data) {
        window.location.href=window.location.href;
    }   
});

This is the code in my controller :

public function EditEmail()
{    
    if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
    {
       DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));

       return Response::json(['success' => 'request succeeded'], 200);
    }    
}

So i already make the verification in my controller and user can't introduce the same email but i want to know how can i send data from my controller to ajax so i can make the verification there too.Does anybody have a solution ?

1
  • You're already sending data back, what doesn't work? Commented Aug 1, 2015 at 21:06

1 Answer 1

1

You have two options.

First option using statusCode :

According to the Ajax documentation (http://api.jquery.com/jQuery.ajax/), you can do something like that :

statusCode: {
    200: function() {
      alert( "user found" );
    },
    404: function() {
      alert( "user not found" );
    }
 }

and returns in your controller :

// user does not exist
return Response::json(['status' => 'not_found'], 404);

//or if the user does exist
return Response::json(['status' => 'found'], 200);

Second option using simple json data :

$.ajax({
   type: 'POST',
    url: '/EditEmail',
    data: form.serialize(),
    dataType: 'json',
    timeout: 9000,
    error:function(data) {
       //something went wrong with the request 
    },
    success:function(data) {
        if(data['status'] == "found") {
             alert( "user found" );
        } else {
             alert( "user not found" );
        }
    }   
});

and in your controller :

public function EditEmail()
{    
     if(Hash::check(Input::get('ParolaActuala'),$parola) && count(User::where('email','=',$NoulEmail)->get()) == 0 )
     {
          DB::table('users')->where ('user_id',Auth::user()->user_id)->update(array('email' => Input::get('NoulEmail')));

          return Response::json(['status' => 'not_found']);
     }    

     return Response::json(['status' => 'found']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks man the solution with the statusCode works very fine for me!

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.