skip to Main Content

i am using Localhost using xamp, i have created html,css3 form and also create a php script file but when i click on form submit button the data is send to database but the form current page is redirect to connect.php and also the message "New record is inserted successfully" displayed on redirected page.

While i want to display the "New record is inserted successfully" message on same page and also do not want the redirection.

my html code

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <title>Form site</title>
</head>
<body>
    <form method="post" action="connect.php">
        <!-- Existing fields -->
        Cnic: <input type="number" name="cnic_number"><br><br>
        Name: <input type="text" name="name"><br><br>
        FIR No: <input type="text" name="fir_no"><br><br>
        FIR Date: <input type="date" name="fir_date"><br><br>
        Section: <input type="text" name="section"><br><br>
        Police Station: <input type="text" name="police_station"><br><br>
        Address: <textarea name="address"></textarea><br><br>

        <input type="submit" value="Submit">
    </form>
    <!-- Placeholder for success message -->
    <div id="message"></div>
</body>
</html>
 

PHP Code

<?php
$name = filter_input(INPUT_POST, 'name');
$cnic_number = filter_input(INPUT_POST, 'cnic_number');
$fir_no = filter_input(INPUT_POST, 'fir_no');
$fir_date = filter_input(INPUT_POST, 'fir_date');
$section = filter_input(INPUT_POST, 'section');
$police_station = filter_input(INPUT_POST, 'police_station');
$address = filter_input(INPUT_POST, 'address');

if (!empty($name) && !empty($cnic_number)) {
    $host = "localhost";
    $dbusername = "root";
    $dbpassword = "";
    $dbname = "mysite2";

    // Create connection
    $conn = new mysqli($host, $dbusername, $dbpassword, $dbname);

    if (mysqli_connect_error()) {
        die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
    } else {
        // Prepare and execute the SQL query to insert data
        $sql = "INSERT INTO mysite2table (name, cnic_number, fir_no, fir_date, section, police_station, address)
                VALUES ('$name', '$cnic_number', '$fir_no', '$fir_date', '$section', '$police_station', '$address')";

        if ($conn->query($sql)) {
            echo "New record is inserted successfully";
        } else {
            echo "Error: " . $sql . " " . $conn->error;
        }
        $conn->close();
    }
} else {
    echo "cnic number and name should not be empty";
}
?>

Check the screenshot when i submit the data

when entering the data

After submitting the page is redirected to connect.php and message also displayed on redirected page

enter image description here

My PC folder screenshot

enter image description here

Note: I want to display the message "New record is inserted successfully" on same page "form.html" and also do not want the page to be redirected to connect.php

I hope someone will help me, because i am stuck here and i am giving up

2

Answers


  1. After statement, before closing your php tag, put this line

    header('Location: http://www.yourwebsite.com/');
    

    Sometime, your destination can be inside your website, in this case, use

    header('Location: ../folder/file.ext');
    

    where ../folder/file.ext is your path

    If you have many redirection to do, create a function

    function redirect($path){
    
        header('Location: ' . $path);
    }
    

    Header take a lot parameters… This is not a complete explanation.

    To display your message after redirecting, put your message in session. Don’t forget to start it.

    $_SESSION['message'] = $message; // to add your value
    

    and

    echo "Your form was submitted successfully. Specific message : " . $_SESSION['message']; // to get your value
    
    Login or Signup to reply.
  2. As the commenters suggested, you should really read up on AJAX request, to be able to effectively use them. Here’s however some basic code that should get you started.

    First off we want to keep the form from actually submitting but calling a javascript function instead:

    <form method="post" action="connect.php" onsubmit="mySubmitForm(this, 'message'); return false;">
    

    So when the user submits the form the function mySubmitForm is being called and by returning false the form will not get submitted by the browser.

    Then we need a javascript function that takes all the values from the form, submits them in an AJAX request to the URL given in the action attribute of your form and then displays the results to the user:

    async function mySubmitForm(form, result_container) {
        fetch(form.getAttribute('action'),
        {
            method: "POST",
            body: new FormData(form)
        })
        .then(response => response.text())
        .then(text => document.getElementById(result_container).innerHTML = text)
        .catch(error => console.error(error));
    }
    

    And that’s pretty much it. Your complete form.html would then look like this:

    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="styles.css">
        <title>Form site</title>
    </head>
    <body>
        <form method="post" action="connect.php" onsubmit="mySubmitForm(this, 'message'); return false;">
            <!-- Existing fields -->
            Cnic: <input type="number" name="cnic_number"><br><br>
            Name: <input type="text" name="name"><br><br>
            FIR No: <input type="text" name="fir_no"><br><br>
            FIR Date: <input type="date" name="fir_date"><br><br>
            Section: <input type="text" name="section"><br><br>
            Police Station: <input type="text" name="police_station"><br><br>
            Address: <textarea name="address"></textarea><br><br>
    
            <input type="submit" value="Submit">
        </form>
        <!-- Placeholder for success message -->
        <div id="message"></div>
        <script>
            async function mySubmitForm(form, result_container) {
                fetch(form.getAttribute('action'),
                {
                    method: "POST",
                    body: new FormData(form)
                })
                .then(response => response.text())
                .then(text => document.getElementById(result_container).innerHTML = text)
                .catch(error => console.error(error));
            }
        </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search