【问题标题】:back-end error_msg is not giving a alert..!后端 error_msg 没有发出警报..!
【发布时间】:2016-03-15 19:17:04
【问题描述】:

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

这里是 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
}
?>

这里是 .php 文件,以便清楚了解我在做什么..!!

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

这里是主文件 .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();
            }
        });
    });

}); 

这里是对应的 .html 文件

<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>

【问题讨论】:

    标签: javascript php jquery html database


    【解决方案1】:

    来自cmets:

    所以只有在显示注册成功后!我想提交表单并将其重定向到login.html

    解决方案非常简单,涉及在.ajax() 中添加async 参数并将其设置为false。将async 设置为false 意味着您正在调用的语句必须完成,然后才能调用函数中的下一条语句。如果您设置async: true,则该语句将开始执行,并且无论异步语句是否已完成,都将调用下一条语句。

    你的 jQuery 应该是这样的:

    $(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);
                }
            });
        });
    }); 
    

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

    已编辑:

    首先确保&lt;!DOCTYPE html&gt;在你的页面顶部,它代表html5并且html5支持required属性。

    现在开始您的前端验证。 HTML5 表单验证过程仅限于通过提交按钮提交表单的情况。 Form submission algorithm 明确表示通过submit() 方法提交表单时不执行验证。显然,这个想法是,如果您通过 JavaScript 提交表单,则应该进行验证。

    但是,您可以使用checkValidity() 方法,针对 HTML5 属性定义的约束请求(静态)表单验证。

    为简单起见,我删除了您的条款和条件复选框和 Google ReCaptcha。您可以稍后将它们合并到您的代码中。

    这是你的 HTML 代码 sn-p:

    <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>
    

    你的 jQuery 会是这样的:

    $(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);
                    }
                });
            }
    
        });
    
    }); 
    

    【讨论】:

    • 脱帽先生...!!超级简单的代码..以及对它的超级解释...!!!真的很棒..!!
    • 先生..!!有人怀疑它限制了前端验证..!!为什么会这样先生..!?
    • @krishna 你到底在哪里进行前端验证
    • @krishna 抱歉耽搁了。请清楚地解释你的问题。你遇到了什么错误?什么不工作?除了这条线&lt;/div&gt;ass="checkbox i-checks"&gt;&lt;label&gt; &lt;input type="checkbox"&gt;&lt;i&gt;&lt;/i&gt; Agre,我看不到任何奇怪的问题。你确定这是正确的吗?
    • @krishna 我已经更新了我的答案。请参阅我回答的已编辑部分。
    【解决方案2】:

    您的表单提交在 ajax 操作之前执行操作,因此它会重新加载页面并使用表单提交而不是提交按钮单击

    //execute's the function on click
        $("#register").on('submit',function(e){
           e.preventDefault(); // prevent page from reloading 
    

    确定步骤以确保在您尝试使用 ajax 时一切正常

    1st : 使用表单提交并使用e.preventDefault(); 防止页面重新加载

    //execute's the function on click
        $("#register").on('submit',function(e){
           e.preventDefault(); // prevent page from reloading
           alert('Form submited'); 
       });
    

    如果弹出警报和表单没有重新加载页面,那么下一步使用 ajax

      //execute's the function on click
        $("#register").on('submit',function(e){
           e.preventDefault(); // prevent page from reloading
           $.ajax({
              url: "register.php",
              type: "POST",
              dataType: "JSON",
              data: {success : 'success'},
              success : function(data){
                  alert(data);
              }
           });
       });
    

    在 php 中 (register.php)

    <?php 
       echo $_POST['success'];
    ?>
    

    这段代码应该用“成功”警告框来提醒。如果这一步很好,那么现在你的 ajax 和 php 文件已成功连接,然后传递变量并做其他事情

    【讨论】:

    • 先生..$("#register").on('submit',function(e){ e.preventDefault(); 或 $("#submit").on('submit' ,function(e){ e.preventDefault();
    • @krishna $("#register").on('submit', .. 好的这段代码可以防止页面加载.. 你应该得到一个警报
    • 先生...现在正在显示错误,但是当我在警报框上单击“确定”时,它会自动在
      tag
      中执行操作
    • @krishna 请在进行下一步之前检查每个步骤..首先检查您的 ajax 和 php 连接并确保它们已经连接..并且表单不会重新加载页面然后编写您的 php数据库代码
    • @krishna 更新答案请查看步骤并确保一切顺利
    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2012-08-28
    • 2015-04-29
    相关资源
    最近更新 更多