javascript – Alert works with conditions but redirects to the other page when pressed “OK” and doesn't allow user to change input-ThrowExceptions

Exception or error:

I’m trying to create a master card check website where the credit card number, exp date, and CVV will be checked (using JavaScript). If the details are correct, the user will be redirected to another page and the credit card details will be stored in an MYSQL database (using PHP).

I have managed to create the two webpages and the javaScript function is working fine, but the problem is that when a user inputs any incorrect details an alert dialogue will show telling the user to enter the correct (card number, date, ….) WHICH IS WHAT I WANT, but when I click OK it automatically redirects me to the other page and store the details inside the database.

I would like your help in solving this problem so that when a user clicks OK it doesn’t redirect to the other webpage, and allows the user to correct the details.

I tried putting onsubmit = “return false” inside the , which worked and allowed the user to re-edit the details, but when it redirects the user to another webpage the PHP/MySQL says “UNDEFINED INDEX” for the fields. I tried removing onsubmit = “return false” and the “UNDEFINED INDEX” error disappeared but the alert dialogue problem reappeared.

Please help with regards to the problem mentioned above.

I tried adding return false after each alert and alert box problem was solved, but the “Undefined Index” mysql error showed for the second page.

HTML CODE FOR FIRST WEBPAGE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Payment Page</title>
<link rel="stylesheet" href='form-style.css' type='text/css' />
</head>
<body>
<div class="mail">
<h2 style="margin-left:0px;">Payment Options</h2>
<hr>
<div id="CardImage/Text">
    <br>
    <img src="mastercard.png" alt="MasterCard" width="100px" height="50px" align="right">
    <h3 style="margin-left:90px;"> Debit / Credit Card</h3>
    <br>
</div>  
<form name="form1" action="secondpage.php" method="post" onsubmit="return false;" >
<div id= "payment" style="margin-left:50px; background: #F0F0F0;">
    <div id= "cardNumber">
      <label for="cardno">Card Number</label>
      <input type="text" name="creditCard" id="creditCard" style="width:300px;">
    </div>
    <br> 
    <div id="date">
        <label for="Expiration">Expiration Date</label>
        <select id= "month" name="month">
            <option selected value="month">Month</option>
            <option value="January">January</option>
            <option value="February">February</option>
            <option value="March">March</option>
            <option value="April">April</option>
            <option value="May">May</option>
            <option value="June">June</option>
            <option value="July">July</option>
            <option value="August">August</option>
            <option value="september">September</option>
            <option value="october">October</option>
            <option value="november">November</option>
            <option value="december">December</option>
        </select>

        <select id= "year" name="year">
            <option selected value="year">Year</option>
            <option value="2020">2020</option>
            <option value="2021">2021</option>
            <option value="2022">2022</option>
            <option value="2023">2023</option>
            <option value="2024">2024</option>
            <option value="2025">2025</option>
            <option value="2026">2026</option>
        </select>

    </div>
    <br>
    <div id= "securityCode">
      <label for="cvv">Security Code</label>
      <input type="text" name="cvv" id="cvv" style="width:100px;">
      <p>(3-4 digit code normally on the back of your card)</p>
    </div>
    <br>    
    <button type="submit" id="submit-button" onclick="cardCheck(document.form1.payment)">Continue</button>
</form>  
</div> 
<script src="credit-card-master-validation.js"></script>
</body>
</html>

HTML/PHP CODE FOR SECOND WEBPAGE

<?php
$servername = "localhost";
$database = "creditCard";
$username = "root";
$password = "";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection

if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

$sql = "INSERT INTO card (ccnum, expmonth, expyear, seccode)
VALUES ('$_POST[creditCard]','$_POST[month]','$_POST[year]','$_POST[cvv]')";
if (mysqli_query($conn, $sql)) {
      echo "New record created successfully";
} else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Payment Successful</title>
<link rel="stylesheet" href='form-style.css' type='text/css' />
</head>
<body>
<div class="mail">
<h2 style="margin-left:0px;">You have successfully entered your credit card details</h2>
<hr>
<div id="CardImage/Text">
    <br>
    <img src="mastercard.png" alt="MasterCard" width="100px" height="50px" align="right">
    <h3 style="margin-left:90px;"> Debit / Credit Card</h3>
    <br>
</div>  
<div id= "successPaymentConsole" style="margin-left:50px; padding-bottom:200px"> 
</div> 
<script src="credit-card-master-validation.js"></script>
</body>
</html>

JavaScript Code

function cardCheck()
{
    var enteredCardNo = document.getElementById("creditCard").value;

    var cardNo = /^(?:5[1-5][0-9]{14})$/;

    var mon = document.getElementById("month");
    var monthSelectedValue = mon.options[mon.selectedIndex].value;
    var year = document.getElementById("year");
    var yearSelectedValue = year.options[year.selectedIndex].value;
    var enteredCVV = document.getElementById("cvv").value;

    if(enteredCardNo.match(cardNo)) {
        if(monthSelectedValue != "month") { 
            if(yearSelectedValue !="year") {
                if(enteredCVV.length > 2 && enteredCVV.length < 5) {                    
                    window.location.href = "secondpage.php";
                } else {
                    alert("Please input a correct CVV");
                }
            } else {
                alert("Please select a year");
            }
        } else {
            alert("Please select a month");
        }
    } else {
        alert("Not a valid Mastercard number!");
    }
}

How to solve:

When you use return false then you switch off the default submit behavior. Then you do a simple redirection by changing href – so the form does not pass the data to the second page (all the $_POST data is empty) – that’s why you have the error. So – what you can do:

Add id param to the form, eg:

<form id="creditCardForm" name="form1" action="secondpage.php" method="post" >

and then use preventDefault in your cardCheck function. It will prevent the form submission so you have to submit the form manually if the data is fine:

function cardCheck()
{
event.preventDefault(); //here you prevent it from being submitted every time

var enteredCardNo = document.getElementById("creditCard").value;

var cardNo = /^(?:5[1-5][0-9]{14})$/;

var mon = document.getElementById("month");
var monthSelectedValue = mon.options[mon.selectedIndex].value;
var year = document.getElementById("year");
var yearSelectedValue = year.options[year.selectedIndex].value;
var enteredCVV = document.getElementById("cvv").value;

if(enteredCardNo.match(cardNo)) {
    if(monthSelectedValue != "month") { 
        if(yearSelectedValue !="year") {
            if(enteredCVV.length > 2 && enteredCVV.length < 5) {                    
                document.getElementById("creditCardForm").submit();  //here's the form submittion
            } else {
                alert("Please input a correct CVV");
            }
        } else {
            alert("Please select a year");
        }
    } else {
        alert("Please select a month");
    }
} else {
    alert("Not a valid Mastercard number!");
}
}

Didn’t try it, but hopefully it will help you to solve the problem.

Answer:

Remove the onsubmit attribute from your <form> element in the HTML. Try to use addEventListener in JavaScript to listen for events.

If we use the cardCheck function as the callback to the submit event, we can control inside the function what will happen with the event. Using event.preventDefault will prevent the form from submitting. When you use event.preventDefault in, for example a click event, it will prevent the default click behavior. So now the form won’t submit and you can give it the behavior you want.

I’ve modified your nested if statements to a structure which does not require nesting. In my opinion, this is much more readable. The return keyword is essential in this. Whenever an if statement is true, the function will stop. Only if all the if statements result in false, (which means all input is correct) the user will be routed to the next page.

var form = document.querySelector('form[name="form1"]');
form.addEventListener('submit', cardCheck);

function cardCheck(event)
{

    // Don't execute the default submit behavior.
    event.preventDefault();

    var enteredCardNo = document.getElementById("creditCard").value;

    var cardNo = /^(?:5[1-5][0-9]{14})$/;

    var mon = document.getElementById("month");
    var monthSelectedValue = mon.options[mon.selectedIndex].value;
    var year = document.getElementById("year");
    var yearSelectedValue = year.options[year.selectedIndex].value;
    var enteredCVV = document.getElementById("cvv").value;

    if (!enteredCardNo.match(cardNo)) {
      alert("Not a valid Mastercard number!");
      return;
    }

    if (monthSelectedValue === "month") {
      alert("Please select a month");
      return;
    }

    if (yearSelectedValue === "year") {
      alert("Please select a year");
      return;
    }

    if (!(enteredCVV.length > 2 && enteredCVV.length < 5)) {
      alert("Please input a correct CVV");
      return;
    }

    window.location.href = "secondpage.php";

}

Answer:

One way to resolve this problem is by using only onsubmit.

Remove onclick from the Continue(submit) button

<button type="submit" id="submit-button">Continue</button>

Change the form element so that it calls cardCheck on submit like below

<form name="form1" action="secondpage.php" method="post" onsubmit="return cardCheck(document.form1.payment)">

Inside you cardCheck if everything is alright return true else return false. Also remove the submit() call. Here is the updated code

function cardCheck()
{
event.preventDefault(); //here you prevent it from being submitted every time

var enteredCardNo = document.getElementById("creditCard").value;

var cardNo = /^(?:5[1-5][0-9]{14})$/;

var mon = document.getElementById("month");
var monthSelectedValue = mon.options[mon.selectedIndex].value;
var year = document.getElementById("year");
var yearSelectedValue = year.options[year.selectedIndex].value;
var enteredCVV = document.getElementById("cvv").value;

if(enteredCardNo.match(cardNo)) {
    if(monthSelectedValue != "month") { 
        if(yearSelectedValue !="year") {
            if(enteredCVV.length > 2 && enteredCVV.length < 5) {                    
                return true;
            } else {
                alert("Please input a correct CVV");
                return false;
            }
        } else {
            alert("Please select a year");
            return false;
        }
    } else {
        alert("Please select a month");
        return false;
    }
} else {
    alert("Not a valid Mastercard number!");
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *