后端error_msg没有提供警报。 [英] back-end error_msg is not giving a alert..!

查看:174
本文介绍了后端error_msg没有提供警报。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery来执行一个.php文件,但是我的主要问题是,当后端发生错误时,我使用了一个警报来显示error_msg ..但是我故意提交一个错误...它只是移动到页面指定的行动...没有错误警报强行起来... plz帮助我出来这。!!原谅我,如果我错了



这里注意 DB_Function.php

 <?php 
class DB_Functions {
私人$ db;

//数据库连接的构造函数
函数__construct(){
try {
$ hostname =localhost;
$ dbname =miisky;
$ dbuser =root;
$ dbpass =;
$ this-> db = new PDO(mysql:host = $ hostname; dbname = $ dbname,$ dbuser,$ dbpass);

catch(PDOException $ e)
{
die('数据库需求错误:'。$ e-> getMessage());


$ b $ **
*存储新用户
*返回用户的详细信息
* /
public函数storeUser($ fname,$ lname,$ email,$ password,$ mobile){
try {
$ hash = md5($ password);
$ sql =INSERT INTO users(fname,lname,email,password,mobile,created_at)VALUES('$ fname','$ lname','$ email','$ hash','$ mobile' ,NOW());
$ dbh = $ this-> db-> prepare($ sql);
$ b $ if($ dbh-> execute()){
//获取用户详细信息
$ sql =SELECT * FROM users WHERE email ='$ email'LIMIT 1 ;
$ dbh = $ this-> db-> prepare($ sql);
$ result = $ dbh-> execute();
$ rows = $ dbh-> fetch();
$ n = count($ rows);
if($ n){
return $ rows;


$ b catch(Exception $ e){
die('Error access database:'。$ e-> getMessage());
}
返回false;

$ b $ *来检查用户是否已经注册
* /
public function isUserExisted($ email){
try {
$ sql =选择电子邮件从用户WHERE电子邮件='$电子邮件'限制1;
$ dbh = $ this-> db-> prepare($ sql);
$ result = $ dbh-> execute();
if($ dbh-> fetch()){
return true;
} else {
return false;

} catch(Exception $ e){
die('Error access database:'。$ e-> getMessage());

$ b $ *来检查用户
是否存在手机号码* /
public function isMobileNumberExisted($ mobile){
try {
$ sql =选择手机用户WHERE mobile ='$ mobile'LIMIT 1;
$ dbh = $ this-> db-> prepare($ sql);
$ result = $ dbh-> execute();
if($ dbh-> fetch()){
return true;
} else {
return false;

} catch(Exception $ e){
die('Error access database:'。$ e-> getMessage());
}
}
//DB_Functions.php正在建设中
//需要添加更多功能
}
?>

这里是通过 .php 文件清楚了解正在做什么。 。!

 <?php 
require_once'DB_Functions.php';
$ db = new DB_Functions();

// json响应数组
$ response = array(error=> false);
if(!empty($ _ POST ['fname'])&&!empty($ _ POST ['lname'])&&!empty($ _ POST ['email'])&& amp ;!empty($ _ POST ['password'])&&!empty($ _ POST ['mobile'])){
//接收后参数
$ fname = trim($ _ POST [ 'FNAME']);
$ lname = trim($ _ POST ['lname']);
$ email = trim($ _ POST ['email']);
$ password = $ _POST ['password'];
$ mobile = trim($ _ POST ['mobile']);

//验证您的电子邮件地址
if(filter_var($ email,FILTER_VALIDATE_EMAIL)){
//验证您的密码
if(strlen($ password)> ; 6){
//验证您的手机
if(strlen($ mobile)== 12){
//检查有效的电子邮件地址
if($ db-> ; isUserExisted($ email)){
//用户已经存在
$ response [error] = true;
$ response [error_msg] =用户已经存在。 $电子邮件;
echo json_encode($ response);
} else {
if($ db-> isMobileNumberExisted($ mobile)){
//用户已经存在
$ response [error] = true;
$ response [error_msg] =用户已经存在。 $移动;
echo json_encode($ response);
} else {

//创建一个新用户
$ user = $ db-> storeUser($ fname,$ lname,$ email,$ password,$ mobile) ;
if($ user){
//用户存储成功
$ response [error] = false;
$ response [uid] = $ user [id];
$ response [user] [fname] = $ user [fname];
$ response [user] [lname] = $ user [lname];
$ response [user] [email] = $ user [email];
$ response [user] [created_at] = $ user [created_at];
$ response [user] [updated_at] = $ user [updated_at];
echo json_encode($ response);
} else {
//用户未能存储
$ response [error] = true;
$ response [error_msg] =注册时发生未知错误!;
echo json_encode($ response);
}
}
}
} else {
$ response [error] = true;
$ response [error_msg] =手机号码无效!;
echo json_encode($ response);
}

} else {
// 6个字符的分钟
$ response [error] = true;
$ response [error_msg] =密码必须至少包含6个字符!;
echo json_encode($ response);
}

} else {
//无效电子邮件地址
$ response [error] = true;
$ response [error_msg] =无效的电子邮件地址;
echo json_encode($ response);
}
} else {
$ response [error] = true;
$ response [error_msg] =请填写所有必需的参数!;
echo json_encode($ response);
}
?>

在这里输入主文件 .js

  $(document).ready(function(){

//执行单击
$( #submit)。click(function(e){

/ * jquery调用所请求的url
并解析json * /
$ .ajax({
url:register.php,
type:POST,
data:{
fname:$(#fname)。val(),$ b $ val(),
email:$(#email)。val(),
password:$(#password)。val() ,
mobile:$(#mobile)。val()
},
dataType:JSON,
/ *给出警告框
显示结果* /
success:function(json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
} else {
alert(Registeration successful!,json.user.email);
}
},
错误:函数(jqXHR,textStatus,errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});

});

然后在这里输入相应的 .html 文件

 < form method =POSTname =registerid =registerclass =mtrole =formaction =login html的> 

< div class =form-group>
< input type =textname =fnameid =fnameclass =form-controlplaceholder =First Namerequired =>
< / div>
< div class =form-group>
< input type =textname =lnameid =lnameclass =form-controlplaceholder =Last Namerequired =>
< / div>
< div class =form-group>
< input type =emailname =emailid =emailclass =form-controlplaceholder =Emailrequired =>
< / div>
< div class =form-group>
< input type =passwordname =passwordid =passwordclass =form-controlplaceholder =Passwordrequired =>
< / div>
< div class =form-group>
< input type =mobilename =mobileid =mobileclass =form-controlplaceholder =Mobile Norequired =>
< / div>
< div class =form-groupid =recaptcha_widget>
< div class =required>
< div class =g-recaptchadata-sitekey =6Lc4vP4SAAAAABjh8AG>< / div>
<! - 结束缩略图 - >
< / div>
<?php include(js / captcha.php);?>
< / div>
< div class =form-group>

< / div> ass =checkbox i-checks>< label> < input type =checkbox>< i>< / i> Agre
< button type =submitname =submitid =submitclass =btn btn-primary block full-width m-b> Register< / button>

< p class =text-muted text-center>< small>已有帐户?< / small>< / p>
< a class =btn btn-sm btn-white btn-blockhref =login.html>登入< / a>
<

/表格>


解决方案

来自评论:


因此,只有在显示注册成功后!我才会提交表单并将其重定向到 login.html

好的解决方案非常简单,包括将 async 参数添加到 false .ajax()中。将 async 设置为 false 意味着您调用的语句必须先完成才能调用函数中的下一个语句。如果设置了 async:true ,那么该语句将开始执行,并且将调用下一个语句,而不管async语句是否已完成。

$ b $

你的jQuery应该是这样的:
//执行单击
$(#submit)的函数。click(function(e){

/ * jquery调用请求的url
并在json * /
$ .ajax({
url:register.php,
type:POST,
data:{
fname:$(#fname).val(),
lname:$(#lname).val(),
email:$(#email).val(),
password:$(#password)。val(),
mobile:$(#mobile)。val()
},
async:false,
dataType:JSON,
/ *发出警报框
以显示结果* /
success:function(json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
} else {
alert(Registeration successful!,json.user.email);
('#register')。submit();
}
},
错误:函数(jqXHR,textStatus,errorThrown){
alert(errorThrown);
}
});
});
});

所以表单只会在注册成功时才会提交,否则不会。



已编辑: 首先请确保<!DOCTYPE html> 在页面顶部,代表html5,html5支持 required 属性。



现在谈谈您的前端验证事宜。 HTML5表单验证过程仅限于通过提交按钮提交表单的情况。 表单提交算法明确表示不执行验证当通过 submit()方法提交表单时。显然,这个想法是,如果你通过JavaScript提交表单,你应该进行验证。然而,你可以请求(静态)表单验证对照定义的约束通过HTML5属性,使用 checkValidity()方法。

为简单起见,我删除了条款和条件复选框和Google ReCaptcha。您可以在代码中加入这些代码。



所以这里是您的 HTML 代码片段:

 < form method =POSTname =registerid =registerclass =mtrole =formaction =login.html> 

< div class =form-group>
< input type =textname =fnameid =fnameclass =form-controlplaceholder =First Namerequired />
< / div>
< div class =form-group>
< input type =textname =lnameid =lnameclass =form-controlplaceholder =Last Namerequired />
< / div>
< div class =form-group>
< input type =emailname =emailid =emailclass =form-controlplaceholder =Emailrequired />
< / div>
< div class =form-group>
< input type =passwordname =passwordid =passwordclass =form-controlplaceholder =Passwordrequired />
< / div>
< div class =form-group>
< input type =mobilename =mobileid =mobileclass =form-controlplaceholder =Mobile Norequired />
< / div>

<! - 您的复选框在此处 - >
<! - 您的Google ReCaptcha - >

< input type =submitname =submitid =submitclass =btn btn-primary block full-width m-bvalue =Register/>

< / form>

< p class =text-muted text-center>< small>已有帐户?< / small>< / p>
< a class =btn btn-sm btn-white btn-blockhref =login.html>登入< / a>

您的 jQuery 会如下所示:

  $(document).ready(function(){

//执行单击
$( #submit)。click(function(e){

var status = $('form')[0] .checkValidity();
if(status){
/ * jquery调用所请求的url
并解析json * /
$ .ajax中的数据({
url:register.php,
type:POST ,
data:{
fname:$(#fname)。val(),
lname:$(#lname)。val(),
email :$(#email)。val(),
password:$(#password)。val(),
mobile:$(#mobile)。val()
$,b $ b async:false,
dataType:JSON,
/ *发出警报框
来显示结果* /
成功:函数(json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
} else {
alert(Registeration successful!,json.user.email);
$('#register')。submit();
}
},
错误:函数(jqXHR,textStatus,errorThrown){
alert(errorThrown);
}
});
}

});

});


I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong

here gose the DB_Function.php

<?php
class DB_Functions {
    private $db;

    // constructor for database connection
    function __construct() {
        try {
            $hostname = "localhost";
            $dbname = "miisky";
            $dbuser = "root";
            $dbpass = "";
            $this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
        }
        catch(PDOException $e)
        {
            die('Error in database requirments:'    . $e->getMessage());
        }
    }

    /**
      * Storing new user
      * returns user details of user
      */
  public function storeUser($fname, $lname, $email, $password, $mobile) {  
    try {
        $hash = md5($password);
        $sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
        $dbh = $this->db->prepare($sql);

        if($dbh->execute()){
            // get user details
            $sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
            $dbh = $this->db->prepare($sql);
            $result = $dbh->execute();
            $rows = $dbh->fetch();
            $n = count($rows);
            if($n){
                return $rows;
            }
        }
    }
    catch (Exception $e) {
        die('Error accessing database: ' . $e->getMessage());
    }
    return false;
}

/*to check if user is
 already registered*/
  public function isUserExisted($email) {
    try{
        $sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
        $dbh = $this->db->prepare($sql);
        $result = $dbh->execute();
        if($dbh->fetch()){
            return true;
        }else{
            return false;
        }
    }catch (Exception $e) {
        die('Error accessing database: ' . $e->getMessage());
    }
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
    $sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
    $dbh = $this->db->prepare($sql);
    $result = $dbh->execute();
    if($dbh->fetch()){
    return true;
    }else{
    return false;
    }
}catch(Exception $e){
    die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction 
//more functions to be added
}
?>

here gose the .php file to be clear on what am doing..!!

<?php
    require_once 'DB_Functions.php';
    $db = new DB_Functions();

    // json response array
    $response = array("error" => false);
    if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
        // receiving the post params
        $fname = trim($_POST['fname']);
        $lname = trim($_POST['lname']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $mobile = trim($_POST['mobile']);

        // validate your email address
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
            //validate your password
            if(strlen($password) > 6){
            //validate your mobile
            if(strlen($mobile) == 12){
            //Check for valid email address
            if ($db->isUserExisted($email)) {
                // user already existed
                $response["error"] = true;
                $response["error_msg"] = "User already existed with " . $email;
                echo json_encode($response);
            } else {
                if($db->isMobileNumberExisted($mobile)) {
                    //user already existed
                    $response["error"] = true;
                    $response["error_msg"] = "user already existed with" . $mobile;
                    echo json_encode($response);
            } else {

                // create a new user
                $user = $db->storeUser($fname, $lname, $email, $password, $mobile);
                if ($user) {
                    // user stored successfully
                    $response["error"] = false;
                    $response["uid"] = $user["id"];
                    $response["user"]["fname"] = $user["fname"];
                    $response["user"]["lname"] = $user["lname"];
                    $response["user"]["email"] = $user["email"];
                    $response["user"]["created_at"] = $user["created_at"];
                    $response["user"]["updated_at"] = $user["updated_at"];
                    echo json_encode($response);
                } else {
                    // user failed to store
                    $response["error"] = true;
                    $response["error_msg"] = "Unknown error occurred in registration!";
                    echo json_encode($response);
                }
            }
         }
        } else {
            $response["error"] = true;
            $response["error_msg"] = "Mobile number is invalid!";
            echo json_encode($response);
        }

        } else {
            //min of 6-charecters
            $response["error"] = true;
            $response["error_msg"] = "password must be of atleast 6-characters!";
            echo json_encode($response);
        }

       } else {
            // invalid email address
            $response["error"] = true;
            $response["error_msg"] = "invalid email address";
            echo json_encode($response);
        }
    } else {
        $response["error"] = true;
        $response["error_msg"] = "Please fill all the required parameters!";
        echo json_encode($response);
    }
?>

and here gose the main file .js

$(document).ready(function(){

    //execute's the function on click
    $("#submit").click(function(e){

        /*jquery to call the url requested 
        and parse the data in json*/
        $.ajax({
            url: "register.php",
            type: "POST",
            data: {
                fname: $("#fname").val(),
                lname: $("#lname").val(),
                email: $("#email").val(),
                password: $("#password").val(),
                mobile: $("#mobile").val()
            },
            dataType: "JSON",
            /*Give out the alert box
            to display the results*/ 
            success: function (json){
                if(json.error){
                    alert(json.error_msg);
                    e.preventDefault();
                }else{
                    alert("Registeration successful!",json.user.email);
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert(errorThrown);
                e.preventDefault();
            }
        });
    });

}); 

and here gose the corresponding .html file

<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">

                    <div class="form-group">
                        <input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
                    </div>
                    <div class="form-group">
                        <input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
                    </div>
                    <div class="form-group">
                        <input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
                    </div>
                    <div class="form-group">
                        <input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
                    </div>
                    <div class="form-group">
                        <input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
                    </div>
                    <div  class="form-group" id="recaptcha_widget">
                                                        <div class="required">
                                                          <div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
                                                       <!-- End Thumbnail-->
                                                      </div>
                                                      <?php include("js/captcha.php");?>
                    </div>
                    <div class="form-group">
                            <div cle the terms and policy </label></div>
                    </div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
                    <button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>

                    <p class="text-muted text-center"><small>Already have an account?</small></p>
                    <a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
                <

/form>

解决方案

From the comments:

So only after displaying Registeration successful! I want to submit the form and redirect it to login.html

Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

Your jQuery should be like this:

$(document).ready(function(){
    //execute's the function on click
    $("#submit").click(function(e){

        /*jquery to call the url requested 
        and parse the data in json*/
        $.ajax({
            url: "register.php",
            type: "POST",
            data: {
                fname: $("#fname").val(),
                lname: $("#lname").val(),
                email: $("#email").val(),
                password: $("#password").val(),
                mobile: $("#mobile").val()
            },
            async: false,
            dataType: "JSON",
            /*Give out the alert box
            to display the results*/ 
            success: function (json){
                if(json.error){
                    alert(json.error_msg);
                    e.preventDefault();
                }else{
                    alert("Registeration successful!",json.user.email);
                    ('#register').submit();
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert(errorThrown);
            }
        });
    });
}); 

So the form will only get submitted if the registration is successful, otherwise not.

Edited:

First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.

Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.

For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.

So here's your HTML code snippet:

<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">

    <div class="form-group">
        <input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
    </div>
    <div class="form-group">
        <input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
    </div>
    <div class="form-group">
        <input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
    </div>
    <div class="form-group">
        <input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
    </div>
    <div class="form-group">
        <input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
    </div>

    <!--Your checkbox goes here-->
    <!--Your Google ReCaptcha-->

    <input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />

</form>

<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>

And your jQuery would be like this:

$(document).ready(function(){

    //execute's the function on click
    $("#submit").click(function(e){

        var status = $('form')[0].checkValidity();
        if(status){
            /*jquery to call the url requested 
            and parse the data in json*/
            $.ajax({
                url: "register.php",
                type: "POST",
                data: {
                    fname: $("#fname").val(),
                    lname: $("#lname").val(),
                    email: $("#email").val(),
                    password: $("#password").val(),
                    mobile: $("#mobile").val()
                },
                async: false,
                dataType: "JSON",
                /*Give out the alert box
                to display the results*/ 
                success: function (json){
                    if(json.error){
                        alert(json.error_msg);
                        e.preventDefault();
                    }else{
                        alert("Registeration successful!",json.user.email);
                        $('#register').submit();
                    }
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        }

    });

}); 

这篇关于后端error_msg没有提供警报。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆