简体   繁体   English

AngularJS验证

[英]Angularjs validate

I want validate my form using ajax , but the errors are not showing properly. 我想使用ajax验证表单,但错误未正确显示。 Here is my code: 这是我的代码:

Html HTML

<body ng-app="app" ng-controller="dkController">
<form ng-submit="dk()">
<label>Username</label>
<input type="text" name="username" ng-model="formdata.user">
{{errorName}}
<label>Password</label>
<input type="text" name="password" ng-model="formdata.pass">
<label>Email</label>
<input type="text" name="email" ng-model="formdata.email">
<button type="submit" >Submit</button>
{{message}}

</form>
</body>

Js JS

function dkController($http,$scope){
                $scope.formdata={};
                $scope.dk = function(){
                    $http({
                        method:"POST",
                        url:"dk.php",
                        data:$.param($scope.formdata)
                    })
                    .then(function(response){
                        $scope.errorName = response.data.errors.username;
                    })

and PHP 和PHP

$conn= new mysqli('localhost','root','','dangky');
$username   = isset($_POST['username']) ? trim($_POST['username']) : '';
$sql="SELECT *FROM dangky where username='$username'";
$result= mysqli_query($conn,$sql);

$errors=array();
$data=array();
if(empty($username))
$errors['username']='user name is required';

if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
    if ($row['username'] == $username){
        $errors['check'] = 'Tên đăng nhập đã tồn tại';
}
}
if(!empty($errors)){
    $data['success']=false;
    $data['errors']=$errors;
}
echo json_encode($data);

Error username is showing but errors check not showing . 显示错误的用户名,但未显示错误检查。

This is the php output 这是PHP的输出

{"success":false,"errors":{"username":"user name is required"}} . 

The problem is youu passed $scope.formdata which contains 问题是您通过了$ scope.formdata,其中包含

{ user : 'someone', pass: 'abc123!', email: 'me@medotcom' }

Your PHP script is looking for post data { username: 'someone' } 您的PHP脚本正在查找发布数据{ username: 'someone' }

So rename your ng-model to ng-model="formdata.username" or change your PHP to find $_POST['user'] . 因此,将您的ng-model重命名为ng-model="formdata.username"或更改您的PHP以找到$_POST['user'] Your choice but they must match. 您的选择,但它们必须匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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