Combine validation with save

I’m a newbie on JavaScript and have a problem:

I have a form works with bootstrap 5. I use the validation script. This works good when I “Post” the form with submit en opens save.php.
But I want to save the form without refresh. So I have a script that works when the Save button is clicked.

How can I combine these scripts so when I click on submit, first the form is validated and when that is ok the save action is done on the server but there is no refresh.

This is my code:

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">   

        <!--CSS-->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link rel='stylesheet' id='fonts-titillium-css'  href='https://fonts.googleapis.com/css?family=Titillium+Web:400,400i,600,700&#038;display=swap' type='text/css' media='all' />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.6.0/font/bootstrap-icons.css">
        <!--JS-->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://kit.fontawesome.com/db9293d16d.js" crossorigin="anonymous"></script>       

        <title>START</title>
    </head>
    <body>

        <form id="user_form" method="post" action="save.php" class="row g-3 needs-validation" novalidate>
            <div class="col-md-3">
                <label for="validationCustom01" class="form-label">First name</label>
                <input type="text" class="form-control" id="validationCustom01" name="fname"value="" required>
                <div class="valid-feedback">
                    Looks good!
                </div>
            </div>
            <div class="col-md-3">
                <label for="validationCustom02" class="form-label">Last name</label>
                <input type="text" class="form-control" id="validationCustom02" name="lname" value="" required>
                <div class="valid-feedback">
                    Looks good!
                </div>
            </div>

            <div class="col-md-6">
                <button class="btn btn-primary" type="submit">Submit form</button> 
                <button type="button" class="btn btn-primary" id="btn-add">Save changes</button>
            </div>
        </form>

        <script>
            // Example starter JavaScript for disabling form submissions if there are invalid fields
            (function () {
                'use strict'

                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.querySelectorAll('.needs-validation')

                // Loop over them and prevent submission
                Array.prototype.slice.call(forms)
                        .forEach(function (form) {
                            form.addEventListener('submit', function (event) {
                                if (!form.checkValidity()) {
                                    event.preventDefault()
                                    event.stopPropagation()
                                }

                                form.classList.add('was-validated')
                            }, false)
                        })
            })()
        </script> 

        <script>
            $(document).on('click', '#btn-add', function (e) {

                var data = $("#user_form").serialize();
                $.ajax({
                    data: data,
                    type: "post",
                    url: "save.php",
                    success: function (dataResult) {
                        var dataResult = JSON.parse(dataResult);
                        if (dataResult.statusCode == 200) {
                            alert('Data added successfully !');
                            location.reload();
                        } else if (dataResult.statusCode == 201) {
                            alert(dataResult);
                        }
                    }
                });
            });
        </script>
    </body>
</html>

Well you appear to have all the pieces. In your event handler for on click of #btn-add , get a reference to the form and run the checkValidity on it. Just like you do in the submit addEventListener. If it passes, then you call the $.ajax() call there.

Something similar to this… (this is just to show you the thought)

$(document).on('click', '#btn-add', function (e) {
    e.preventDefault();

    // Grab the form
    let user_form = $("#user_form");
    let data = user_form.serialize();

    // Check if it is valid
    if (user_form.checkValidity()) {
        // If so, call the ajax
        $.ajax({
            data: data,
            type: "post",
            url: "save.php",
            success: function (dataResult) {
                var dataResult = JSON.parse(dataResult);
                if (dataResult.statusCode == 200) {
                    alert('Data added successfully !');
                    location.reload();
                } else if (dataResult.statusCode == 201) {
                    alert(dataResult);
                }
            }
        });
    } else {
        // Not valid so do whatever you want here for that case.
    }
});

Now of course I didn’t go through the whole process of testing this, but I just wanted to show you how with the one event you can grab the form, check validity and if valid THEN call your ajax.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.