Question:
How to validate bootstrap with php AJAX?

Problem:

I'd like to serialize my form so that it can be sent to a php file via Ajax. I'm using Bootstrap to validate the form beforehand. Unfortunately, the php code returns an empty array. Bizarrely the debugger seems to show that postData contains the right strings:


"a_location=abc&a_headline=def"


(function ($) {

    "use strict";


    function process_new_post(postData) {

        $.ajax({

            url:"createpost.php",

            method:"POST",

            data:  postData ,

            contentType: false,

            processData: false,

            cache: false,

            success:function(response)

            {

                alert(response);

            },

            error:function(jqXHR, textStatus, errorThrown){

                console.error("AJAX Request Error:", textStatus, errorThrown);

            }

        });

    }


    $(document).ready(function () {

        var forms = document.querySelectorAll('.needs-validation');

        Array.prototype.slice.call(forms)

            .forEach(function (form) {

                form.addEventListener('submit', function (event) {

                    Array.from(form.elements).forEach((input) => {

                       if ( (input.value.trim()==='') && (input.type!=='button') && (input.type!=='submit') ) {

                         input.value = '';

                       }

                    });


                    if ( !form.checkValidity() ) {

                      event.preventDefault();

                      event.stopPropagation();

                    }

                    else {

                        event.preventDefault();

                        process_new_post( $("#formcreatenewpost").serialize() );

                    }

                    form.classList.add('was-validated')

              }, false);

        });

    });

})(jQuery);



<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="needs-validation" id="formcreatenewpost" method="post" enctype="multipart/form-data" novalidate>

    <div class="row g-3">

        <div class="col-md-6">

            <div class="form-floating">

                <input type="text" class="form-control" name="a_location" id="a_location" placeholder="Town(s)" required>

                <label for="a_location">Town(s)</label>

            </div>

        </div>

        <div class="col-12">

            <div class="form-floating">

                <input type="text" class="form-control" name="a_headline" id="a_headline" placeholder="Headline" required>

                <label for="a_headline">Headline</label>

            </div>

        </div>

        <div class="col-4 gy-5">                                    

            <button class="btn btn-primary w-100 py-3" type="submit" id="postcreatenewpost">Post</button>

        </div>

    </div>

</form>



Solution:

Don't set contentType and processData as false. Let Ajax handle it by itself. Then you will see the values being read on your controller file.

The else block in the submit event handler is being called. Logging the postData in the script was returning all the values too as you said yourself. The problem is with how you're sending the data.


Suggested blogs:

>5 easy ways to repair the .NET Framework on Windows

>Integrate SASS into the build and consume a UI toolkit

>8 Steps to use Redux Persist in React Native

>How to build an Electron application from scratch

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers