0

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>
Rajesh
  • 195
  • 1
  • 1
  • 15

3 Answers3

0

To implement an AJAX request, you need to call a function when the 'submit' button is pressed, and use an XMLHTTPRequest object.

With this, you open a connection to the server, by calling its open function, and passing the request type ("POST" in your case), the requested URL, and whether it should be asynchronous or not. Details on constructing one of these objects can be found here.

Instead of the PHP code calling the header() function to redirect you to success.html if the coupon matches, echo a value that indicates success, and check for it in your object's onreadystatechange() function.

If your value matches in the JavaScript function, toggle the visibility of a HTML element to signify success, or display an alert - also, remove the target from the form that you have created, as it will submit and redirect you.

Community
  • 1
  • 1
cstr_
  • 98
  • 6
0

Your logic is flawed. The query already specifies if entered coupon code matches with coupon code from database: where couponCode='$coupon' so,

if(mysqli_num_rows($results_coupon)>0) { header ("Location: success.html"); 

will suffice. If you choose to, use jQuery, like this:

var couponVal = $('input[name=coupon]').val(); // get textfield value
$.post(checkValidity.php, {coupon: couponVal }, 
function(data, status) {
if(status == success) {
  if(parseInt(data) > 0) {
    // code here if coupon code match
  }
}
});

In checkValidity.php, write your logic to check match in database. Instead of header, use echo mysqli_num_rows($results_coupon)

See here for syntax.

0

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; }   
  }
?>
Shahzad
  • 2,443
  • 6
  • 21
  • 31
  • Hi, i tried your code but not working. In the php code, i hope it should be if(isset($_POST['sub'])) instead of if(isset($_POST['coupon'])) if i am not wrong. But after changing that also it isn't working – Rajesh Sep 24 '16 at 06:31
  • @Rajesh, debug the code. uncomment `console.log(result);` from my updated answer and also `echo $_POST['coupon'];` in codeValidate.php and share what error you get. – Shahzad Sep 24 '16 at 07:35
  • i am putting ajax and html form also in codeValidate.php. is that fine? – Rajesh Sep 24 '16 at 08:07
  • @Rajesh, Try my updated answer. And if you getting any error in console write down here. – Shahzad Sep 24 '16 at 08:19
  • Hi, I executed your updated code. when i enter something and submit nothing happens but url changes. When I entered test and subitted URL changes as http://localhost/ajaxform/ajax.html?coupon=test&sub=Submit, when i submitted the blank field url changes to http://localhost/ajaxform/ajax.html?coupon=&sub=Submit and when i entered correct coupon code url changes to http://localhost/ajaxform/ajax.html?coupon=D100&sub=Submit – Rajesh Sep 24 '16 at 09:37
  • Thanks a ton. it works. Can I set the error message 'Failed to validate the coupon' in setCustomValidity inside the form instead of showing as a pop up i.e., – Rajesh Sep 24 '16 at 11:24