简体   繁体   中英

I am not able to get response in angular js $http.post

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);
?>

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") {
         ...
    }
}

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");
                  }
              });
       }
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM