Reputation: 75
I want to check whether the email id already exists in the db. If the email id exists, it should return false, else true. I'm not able to get the response. I've attached the controller code and the php code. [the variable validUser is undefined]
Controller.js
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
});
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
}
}
});
checkUser.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "user_details");
//$data = json_decode(file_get_contents("php://input"));
//$email = mysql_real_escape_string($data->email);
$email = $_POST['email'];
$result = $conn->query("SELECT count(*) as count from user where email='$email'");
$outp = "";
$rs = $result->fetch_array(MYSQLI_ASSOC)
if ($rs['count']==0)
{
$outp ="true";
}
else
{
$outp ="false";
}
$conn->close();
echo($outp);
?>
Upvotes: 0
Views: 94
Reputation: 1431
You're if
statement needs to be inside the .then callback, otherwise you'll end up checking it before youre ajax request gets responded to
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
});
}
}
});
Upvotes: 0
Reputation: 39023
You're not checking the response in the correct place, or rather - at the correct time.
$http.post
returns immediately. Your .then
callback is called when the response is returned from the server. The code after the call to post
(your if
statements) is executed right after $http.post
returns, and before the response is received from the server.
You should place your validation code inside your callback:
$http.post(...).then(function(response) {
validUser = response;
if(validUser==="true") {
...
} else if (validUser==="false") {
...
}
}
Upvotes: 1