dosi8657 2016-09-24 05:38
浏览 67
已采纳

通过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条回答 默认 最新

  • dqysi86208 2016-09-24 06:11
    关注

    Update Answer - 2: ( just put both files in same folder )

    Step - 1: Html page with ajax code - Ajax.html

      <html>
        <form id="form_submit">
          <input id="coupon" name="coupon" type="text" size="50" maxlength="13" />
          <input id="btn_submit" type="button" value="Submit">
        </form>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript">
          $("form_submit").submit(function(e){ e.preventDefault(); return false;});
          $("#btn_submit").click(function(e) { e.preventDefault();
            var coupon = $("#coupon").val();  
            // validate for emptiness
            if(coupon.length < 1 ){ alert("enter coupon value"); }
            else{ 
              $.ajax({
                url: './codeValidate.php',
                type: 'POST',
                data: {coupon: coupon},
                success: function(result){
                  console.log(result);
                  if(result){ window.location.href="success.html"; }
                  else{ alert("Error: Failed to validate the coupon"); }
                }
              });     
            }
          });
        </script>
      </html>
    

    Step - 2: Coupon validation php file - codeValidate.php

    <?php 
      require("dbconfig.php");
    
      if(isset($_POST['coupon']) && !empty($_POST['coupon']) ){
        $coupon = trim($_POST['coupon']);        
        $checkcoupon = "SELECT couponCode FROM cc WHERE couponCode='".$coupon."'"; 
        $results_coupon = mysqli_query($dbc,$checkcoupon);    
        if(mysqli_num_rows($results_coupon)) {   echo true; } 
        else { echo false; }   
      }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog