简体   繁体   English

我的 PHP 代码和 Jquery 有问题

[英]Having Problem with my PHP Code and Jquery

I need some help Whenever I input all the information and wanted to click submit, it always alert me "You already submit before" but it was the first time i entered the information.我需要一些帮助每当我输入所有信息并想单击提交时,它总是提醒我“您之前已经提交过”,但这是我第一次输入信息。 So there shouldn't be any duplicate values.所以不应该有任何重复的值。 And the data itself also didn't post into my phpmyadmin database.而且数据本身也没有发布到我的 phpmyadmin 数据库中。

Secondly, i added the addclass("error") and removeclass ('error') in the javascript.其次,我在 javascript 中添加了 addclass("error") 和 removeclass ('error')。 However only those selection questions will show the red error border line while text input questions didn't show the error border line even though it is wrong但是,只有那些选择问题会显示红色错误边界线,而文本输入问题即使错误也不会显示错误边界线

I have spent days to investigate it but still couldn't solve it.我花了几天时间调查它,但仍然无法解决它。

My index.php file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Refund Request Form</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link rel="stylesheet" href="css/style.css" >
<!--    <script src="form.js"></script>-->

</head>

<body>



<div class="container">
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <div class="form-container">
        <span style="text-align: center;padding-bottom: 0px;"><br>
            <center>
                <h1>
                    Refund Request Form
                </h1>
            </center>

        </span>
        <form method="post" id="form" name="form">

            <label for="school_num">School Number: <span class="required">*</span></label>
            <input id="school_num" type="text" placeholder="Enter your School Number" name="school_num"  maxlength="50">

            <label for="name">Full Name: <span class="required">*</span></label>
            <input id="name" type="text" placeholder="Enter your Name in Capital as per IC" name="name"  maxlength="50">

            <label for="email">Email Address: <span class="required">*</span></label>
            <input id="email" type="text" placeholder="Enter your Email Address" name="email"  maxlength="50">

            <label for="ic_num">IC Number: <span class="required">*</span></label>
            <input id="ic_num" type="number" placeholder="Enter your IC Number (without dash)" name="ic_num" data-parsley-length="[12,12]"  maxlength="12">


            <label for="nts">Event1 Refund Amount: <span class="required">*</span></label>
            <select id="nts" placeholder="-" name="nts" onchange="sum()"  >
                <option value = "-" selected>-</option>
                <option value = "0" >0</option>
                <option value = "80">80</option>
                <option value = "100">100</option>
                <option value = "110">110</option>
                <option value = "110">120</option>
            </select>

            <label for="pesta">Event2  Refund Amount: <span class="required">*</span></label>
            <select id="pesta" placeholder="" name="pesta" onchange="sum()"  >
                <option value = "-" selected>-</option>
                <option value = "0" >0</option>
                <option value = "100">100</option>
                <option value = "360">360</option>
                <option value = "450">450</option>
                <option value = "460">460</option>
                <option value = "535">535</option>
                <option value = "540">540</option>
            </select>

            <label for="remarks">Remarks:</label>
            <textarea id="remarks" name="remarks" placeholder="Type your remarks here" rows="5" maxlength="6000"></textarea>

            <label style="border-bottom:1px dotted grey; padding-top: 30px;" colspan="2"></label>

            <label for="refund" class="refund" style="color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500; font-size: 150%;width: 30%">Refund Total: </label>
             <input id="refund"  class="refund1" value="0" readonly style="border:none;color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500;font-size: 150%;width: 20%">
            <!-- <input type="hidden" id="refund" name="refund" class="refund1" value="0" > -->

            <input class="button-primary"  name="submit" id="submit" role="button" type="button" onClick="validateForm()" value="Submit">
<!--            <input type="button" class="button-primary"  type="submit" name="submit" id="submit" role="button"  value="Submit">-->

        </form>

        <div id="success_message" style="display:none">
            <h3>Submitted the form successfully!</h3>
            <p> We will get back to you soon. </p>
        </div>
        <div id="error_message" style="width:100%; height:100%; display:none; "> <h3>Error</h3> Sorry there was an error sending your form.</div>
    </div>
</div>
</body>

<script>

    $(document).ready(function() {
        //this calculates values automatically
        sum();
        $("#nts, #pesta").on("keydown keyup", function() {
            sum();
        });
    });

    function sum() {
        var nts = document.getElementById('nts').value;
        var pesta = document.getElementById('pesta').value;
        var refundTotal = parseInt(nts) + parseInt(pesta);
        if (!isNaN(refundTotal)) {
            document.getElementById('refund').value ="RM " + refundTotal;
        }
    }

    function validateEmail($email) {
        var re = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
        if ($email == '' || !re.test($email))
        {
            return false;
        }
    }

    function validateAlphabet($account_name){
        var letters = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
        if($account_name.value.match(letters))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    // function validateNumber (){
    //
    // }


    function validateForm() {
        $('#submit').disable=true;
        var valid = true;
        var error_msg="";

        //school number
        if($('#school_num').val()=='' && $.trim($('#school_num').val()).length<=0 ){
            error_msg+=("Please insert your school number\n");
            $('#school_num').addClass("error");
            valid=false;
        }else{
            $('#school_num').removeClass("error");  
        }

        //name
        if($('#name').val()==''){
            error_msg+=("Please insert your name\n");
            $('#name').addClass("error");
            valid=false;
        }else{
            $('#name').removeClass("error");
        }

        //email
        if($('#email').val()==''){
            error_msg+=("Please insert your email address\n");
            $('#email').addClass("error");
            valid=false;

        }else{
            if(validateEmail(document.getElementById('email').value)==false){
                //console.log(document.getElementById('email').value);
                error_msg+=("Invalid email address, Please fill in the correct email\n");
                $('#email').addClass("error");
                valid=false;

            }else{
                $('#email').removeClass("error");
            }
        }

        //ic number
        if($('#ic_num').val()==''){
            error_msg+=("Please insert your IC Number (without dash)\n");
            $('#ic_num').addClass("error");
            valid=false;
        }else{
            if(!$.isNumeric($("#ic_num").val())){
                //console.log(document.getElementById('email').value);
                error_msg+=("Invalid IC Number - should be numbers only (no dash)\n");
                $('#ic_number').addClass("error");
                valid=false;

            }else{
                $('#ic_number').removeClass("error");
            }
        }

        //school
        if($('#school').val()=='-'){
            error_msg+=("Please select your school\n");
            $('#school').addClass("error");
            valid=false;
        }else{
            $('#school').removeClass("error");
        }

        //nts
        if($('#nts').val()=='-'){
            error_msg+=("Please select your NTS refund amount\n");
            $('#nts').addClass("error");
            valid=false;
        }else{
            $('#nts').removeClass("error");
        }

        //pesta
        if($('#pesta').val()=='-'){
            error_msg+=("Please select your PESTA refund amount\n");
            $('#pesta').addClass("error");
            valid=false;
        }else{
            $('#pesta').removeClass("error");
        }

        if(error_msg!=""){
            alert(error_msg);
        }
        if(valid){
            $.ajax({
                url: 'form_ajax.php',
                type: 'POST',
                data: {
                    'action':'check_duplicate',
                    'school_num':$('#school_num').val(),
                    'name':$('#name').val(),
                    'email':$('#email').val(),
                    'school':$('#school').val(),
                    'nts':$('#nts').val(),
                    'pesta':$('#pesta').val(),
                    'refund':$('#refund').val(),
                },
                error: function() {
                },
                before:function(){

                },
                dataType: 'json',
                success: function(data) {
                    if(data.is_duplicated==0){
                        $.ajax({
                            url: 'form_ajax.php',
                            type: 'POST',
                            data: {
                                'action':'submit_form',
                                'school_num':$('#school_num').val(),
                            },

                            before:function(){

                            },
                            dataType: 'json',
                            success: function(data) {
                                $('#submit').disable=false;

                                if(data.status==1){
                                    alert(data.message);
                                    $('#success_message').show()
                                    //TOOD: Clear all input
                                    $('#school_num').val(''),
                                    $('#name').val(''),
                                    $('#email').val(''),
                                    $('#school').val(''),
                                    $('#nts').val(''),
                                    $('#pesta').val(''),
                                    $('#refund').val('')
                                }else{
                                    alert(data.message);
                                    $('#error_message').show()
                                }
                            },
                            error: function() {
                            },
                        });
                        //TOOD: Clear all input
                    $('#school_num').val(''),
                    $('#name').val(''),
                    $('#email').val(''),
                    $('#school').val(''),
                    $('#nts').val(''),
                    $('#pesta').val(''),
                    $('#refund').val('')
                    }
                    else{
                        alert('You already submit before');
                    }
                },
            });

        }else{
            $('#submit').disable=false;
        }

    }



</script>
</html>

My form_ajax.php file
<?php

//if(isset($_POST['submit'])){
if($_POST['action']=='submit_form'){
    require "config.php";
    require "common.php";
    $statement=false;
    $new_student = array(
        "school_num"     => $_POST['school_num'],
        "name"           => $_POST['name'],
        "email"          => $_POST['email'],
        "ic_num"         => $_POST['ic_num'],
        "school"         => $_POST['school'],
        "nts"            => $_POST['nts'],
        "pesta"          => $_POST['pesta'],
        "remarks"        => $_POST['remarks'],
        "refund"         => $_POST['refund']
    );

    try{
        //#1 Open Connection
        $connection = new PDO ($dsn,$username,$password,$options);
        //#2 Prepare Sql QUERY
        $statement = $connection->prepare("INSERT INTO details (school_num,name, email, ic_num,school,nts,pesta,remarks,refund,date) values (?,?,?,?,?,?,?,?,?,NOW())");
        $statement ->bindParam(1,$_POST['school_num'],PDO::PARAM_STR);
        $statement ->bindParam(2,$_POST['name'],PDO::PARAM_STR);
        $statement ->bindParam(3,$_POST['email'],PDO::PARAM_STR);
        $statement ->bindParam(4,str_replace($_POST['ic_num'], '-', ''),PDO::PARAM_INT);
        $statement ->bindParam(5,$_POST['school'],PDO::PARAM_STR);;
        $statement ->bindParam(6,$_POST['nts'],PDO::PARAM_INT);
        $statement ->bindParam(7,$_POST['pesta'],PDO::PARAM_INT);
        $statement ->bindParam(8,$_POST['remarks'],PDO::PARAM_STR);
        $statement ->bindParam(9,$_POST['refund'],PDO::PARAM_INT);


        //$statement = $connection->prepare($sql);
        $statement->execute();
        $return_message=array('status'=>1,'message'=>'Your information has been saved');
        echo json_encode($return_message);

    }   catch (PDOException $error){
        $return_message=array('status'=>0,'message'=>'Sorry we cannot save your information');
        echo json_encode($return_message);
    }
}

if( $_POST['action']=='check_duplicate'){
    require "config.php";
    require "common.php";
    $statement=false;


    try{
        //#1 Open Connection
        $connection = new PDO ($dsn,$username,$password,$options);
        //#2 Prepare Sql QUERY
        $statement = $connection->prepare("SELECT details.school_num FROM details");
        $statement->bindParam(':school_num', $_POST ['school_num'], PDO::PARAM_STR);


        //$statement = $connection->prepare($sql);
        $statement->execute();
        $statement->fetchAll();

        $return_message=array('status'=>1,'message'=>'there is duplicate');
        echo json_encode($return_message);

    }catch (PDOException $error){
        $return_message=array('status'=>0,'message'=>'no duplicate');
        echo json_encode($return_message);
    }

}

In your code php does not return the is_duplicated variable.在您的代码中 php 不返回is_duplicated变量。 Therefore, data.is_duplicated is always undefined in javascript.因此, data.is_duplicated在 javascript 中始终未定义 That's why result of if check if(data.is_duplicated==0) will always false, because undefined not equal to 0 .这就是为什么 if 检查if(data.is_duplicated==0)的结果总是假的,因为undefined不等于0

try to replace this code尝试替换此代码

$return_message=array('status'=>1,'message'=>'there is duplicate');

to this对此

$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' => 1);

and here和这里

$return_message=array('status'=>0,'message'=>'no duplicate');

to this对此

$return_message=array('status'=>0,'message'=>'no duplicate', 'is_duplicated' => 0);

PS By the way, why you don't check what statement has? PS顺便问一下,为什么你不检查什么语句? I guess is not correct.我猜是不正确的。

//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();

$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);

should be应该

//$statement = $connection->prepare($sql);
$statement->execute();
$results = $statement->fetchAll();
if (empty($results)) {
    $duplicate = 0;
} else {
    $duplicate = 1;
}

$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' = $duplicate);
echo json_encode($return_message);

PPS To check if there is data in the database is better to use count() and limit=1 PPS要检查数据库中是否有数据,最好使用 count() 和 limit=1

GOOD LUCK祝你好运

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

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