'Jquery Ajax how return Errors from PHP?

I have simple, form which works with Jquery Ajax, but I don't know how can I get my Errors from php.

My Form

<form action="customer.php" method="post" class="addForm">
    <input name="username" type="text" placeholder="username"> <br>
    <input name="name" type="text" placeholder="name"> <br>
    <button type="submit" name="btnAdd">Add New Customer</button>
</form>

My Script

<script>
    $(document).ready(function() {

        $("form.addForm").submit(function(e) {
            e.preventDefault();

            // form's url and method
            var addForm_URL = $("form.addForm").attr("action");
            var addForm_Method = $("form.addForm").attr("method");

            var username_Val = $("input[name='username']").val();
            var name_Val = $("input[name='name']").val();

            var btnAdd_Val = $("button[name='btnAdd']").val();

            $.ajax({
                url: addForm_URL,
                method: addForm_Method,

                data: {
                    username_Post: username_Val,
                    name_Post: name_Val,
                    btnAdd_Post: btnAdd_Val
                },

                success: function(data) {
                    if (data) {
                        console.log(data);
                        $("input[name='username']").val("");
                        $("input[name='name']").val("");
                    } else {
                        console.log(data); // here should be my errors
                    }

                }

            });
        });
    });
</script>

My php

if (isset($_POST['btnAdd_Post']) && empty($_POST['username_Post'])) {
//some stuff
    echo 'Error 1';
}

if (isset($_POST['btnAdd_Post']) && $_POST['name_Post'] == "my1") {
//some stuff
    echo 'Error 2';
}
if (isset($_POST['btnAdd_Post']) && !empty($_POST['name_Post'])) {
//some stuff
    echo 'Error 3';
}

As I use e.preventDefault(), I can't use any exit() or headers in my php. How can I get my echo Error 1,2,3 from php put in my Ajax and priant some stuff or redirect ?

Thanks



Solution 1:[1]

The problem is that you dont allow the post so the you cant get the $_POST info, so ether you have to let it go through with the post and catch the errors with php or log the errors with jQuery.

As far as I'm aware the you do the ajax call to prevent to reload the page and thus not accessing the PHP, but this means you'll have to catch the errors with jQuery as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tjaym