Open In App

How to submit a form or a part of a form without a page refresh using jQuery?

Last Updated : 24 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

How to prevent an HTML form to submit?

When submitting a form, clicking the submit button usually navigates to a new route as specified in the form's action attribute. However, this can be done in the background using event.preventDefault(), which blocks the default event behavior.

By attaching an onsubmit event listener to the form, we can prevent the default event and stop the page from navigating. After calling event.preventDefault(), we can retrieve the form values and make a POST request to the desired route.

Prerequisites:

Approach

The HTML page includes a form with "Name" and "Job" fields and a submit button, styled for centering. On form submission, jQuery's event.preventDefault() prevents the default page refresh. The form data is serialized into an object and sent via an AJAX POST request to "https://reqres.in/api/users". If the request succeeds, a message with the new user ID is displayed in the span; if it fails, the error status is shown. This approach allows form submission without navigating to a new page, providing a smoother user experience.

Example: In this example, we have taken a fake post request where we need to post some information and the server will return the id as an object.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
    .container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    h1 {
        color: green;
    }
    
    h3 {
        text-align: center;
    }
    
    input,
    span {
        margin-top: 20px;
    }
    </style>
</head>

<body>
    <div>
        <h1 class="container">
            GeeksforGeeks
        </h1>
        <h3>Submitting the form without page refresh</h3>
    </div>
    <form>
        <div class="container">
            <input placeholder="Name" type="text" name="Name" />
            <input placeholder="Job" type="text" name="job" />
            <input type="submit" /> 
        </div> 
        <span class="container"></span> 
    </form>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">
    </script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('form').on('submit', function(event) {
            event.preventDefault();
            
            // It returns a array of object 
            let userinfo = $(this).serializeArray();
            let user = {};
            userinfo.forEach((value) => {
                
                // Dynamically create an object
                user[value.name] = value.value;
            });
            let url = "https://reqres.in/api/users";
            $.ajax({
                method: "POST",
                url: url,
                data: user
            }).done(function(msg) {
                
                // When the request is successful
                $('span').text('user is successfully created with Id ' + msg.id);
            }).fail(function(err, textstatus, error) {
                $('span').text(textstatus);
            });
        });
    });
    </script>
</body>

</html>

Output:


Next Article

Similar Reads