How to Submit Form Without Page Refresh using Ajax, jQuery

This tutorial will teach you about creating form that will submit information without refreshing the form page. The jQuery post() and get() methods are used for HTTP POST or GET request from the server. Instead, an notification message will display on successful submission.

HTML and jQuery Code

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">

            function submitdata()
            {
                var name = $('#name_of_user').val();
                var age = $('#age_of_user').val();
                var course = $('#course_of_user').val();
                
                $.ajax({
                    type: 'post',
                    url: 'insertdata.php',
                    data: {
                        user_name: name,
                        user_age: age,
                        user_course: course
                    },
                    success: function (response) {
                        $('#success__para').html("You data will be saved");
                    }
                });

                return false;
            }

        </script>

    </head>
    <body>

        <form method="POST" onsubmit="return submitdata();">
            <input type="text" name="username" id="name_of_user">
            <input type="text" name="userage" id="age_of_user">
            <input type="text" name="usercourse" id="course_of_user">
            <input type="submit" name="submit_form" value="Submit">
        </form>
        <p id="success_para" ></p>
    </body>
</html>

PHP Code (insertdata.php)

<?php
    define('DB_SERVER', "localhost");
    define('DB_USER', "root");
    define('DB_PASS', "");
    define('DB_DATABASE', "whatsappdwld_db");
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

    if (isset($_POST['user_name'])) {
        $name = $_POST['user_name'];
        $age = $_POST['user_age'];
        $course = $_POST['user_course'];
        $insertdata = " INSERT INTO user_info (name,age,course) VALUES( '".$name."','".$age."','".$course."' ) ";
        mysqli_query($con, $insertdata);
    }
?>

Leave a Reply

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