Web Technology - Old Questions

3.  Develop a simple Web site that takes first name, last name and address from the user and stores this information in the database. Use JavaScript to validate form data.

10 marks | Asked in 2075

//index.html

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Form Registration</title>

</head>

<body>

    <h2>Client Side Form Validation</h2>

    <form name="signupForm" onsubmit="return validateForm();" method="POST" action="./formSubmit.php">

        <div>

            <label for="f_name">Please enter your first name: </label>

            <input type="text" name="f_name" id="f_name">

        </div>

        <div>

            <label for="l_name">Please enter your last name: </label>

            <input type="text" name="l_name" id="l_name">

        </div>

        <div>

            <label for="address">Please enter your address: </label>

            <input type="text" name="address" id="address">

        </div>

        <div>

            <input type="submit" name="signup" value="Signup">

        </div>

    </form>

    <script>

        function validateForm() {

            if (document.signupForm.f_name.value == "") {

                alert("Please provide your first name!");

                document.signupForm.f_name.focus();

                return false;

            }

           else if (document.signupForm.l_name.value == "") {

                alert("Please provide your last name!");

                document.signupForm.l_name.focus();

                return false;

            }

            else if (document.signupForm.address.value == "") {

                alert("Please provide your address!");

                document.signupForm.address.focus();

                return false;

            }

            return true;

        }

    </script>

</body>

</html>


//formSubmit.php

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "webtech";

$tablename = "users";

if($_SERVER["REQUEST_METHOD"] == "POST"){

$f_name = $_POST['f_name'];

$l_name = $_POST['l_name'];

        $address = $_POST['address'];


//connect to database

$conn = mysqli_connect($servername, $username, $password) or die(mysql_error()); //Connect to server

mysqli_select_db($conn, $dbname) or die("Cannot connect to database"); //Connect to database


        // Insert the values into database

mysqli_query($conn, "INSERT INTO ".$tablename."(f_name,L_name,  address) VALUES ('$f_name', '$l_name', '$address')"); 

Print '<script>alert("Congrats! Your Submission is Successfully Registered!");</script>'; 

?>