dosi8657
dosi8657
2016-09-24 05:38

通过Ajax进行表单验证

  • php
  • html
  • mysql
  • ajax

I am making a form in which I am adding a text box which cross checks the discount coupon code on the server and validate. The coupon code is stored on the MySQL database. The coupon code is D100 which is stored on the database. If it is correct, , then it goes to success.html otherwise it displays an error. Currently it happens by refreshing the page. Hence the typed values on the other fields become blank. I want to do it without refreshing the page so that the values typed on the other fields remain intact. I know that it can be done through AJAX. Could you please help me to fix it.

Name of the database is 'test' and the table is 'cc' and it has two columns via., 'sno' and 'couponCode'

Here is my sample code.

//dbconfig.php
<?php
$db_hostname = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'test';

$dbc = mysqli_connect ($db_hostname,$db_username, $db_password,$db_name);

if (mysqli_connect_errno()) {
echo "Could not establish database connection!";
exit();
}
?>


//index.php
<html>

    <?php

    require("dbconfig.php");
    $wrongcc=""; 

    //getting value from the form text field and cross check with the value on the database
    if(isset($_POST['sub'])) {
        $cc=$_POST['coupon'];
        if(!empty($cc)) {
            $coupon=$_POST["coupon"];
            $checkcoupon = "select couponCode from cc where couponCode='$coupon'"; 
            $results_coupon = mysqli_query($dbc,$checkcoupon);

            if(mysqli_num_rows($results_coupon)>0) {
                while($row = mysqli_fetch_array($results_coupon)){  
                    $ccode=$row['couponCode'];
                }
                if($coupon==$ccode){
                    header ("Location: success.html");                          
                }    
            } 
            else {      
                $wrongcc = "Wrong coupon code entered.";
                echo $wrongcc;      
            }   
        }
    }

    ?>

    <html>
    <form action="index.php" method="post">
        <input name="coupon" type="text" size="50" maxlength="13" oninvalid="if (this.value!=''){this.setCustomValidity('<?php echo $wrongcc;?>')}"  oninput="setCustomValidity('')" />
        <input type="submit" name="sub">
    </form>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐

换一换