skip to Main Content

I’m trying to send a form to php for validation before inserting data into mySQL. I’m trying to use AJAX to do it. I am unable to get through the validation process when sending a <select> <option>. If I remove the validation for the <select <option> the form processes as expected. When sending via AJAX I get the following response in console:

Response in console

When I process the form by just sending it without AJAX, the validation works fine. Below is my code:

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Validate SelectWith Ajax</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form id="frm" action="process.php" method="post" novalidate>
            <label for="yourOptions">Your Options</label>
            <select id="yourOptions" name="yourOptions" required>
                <option value="" hidden selected>Select One</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
                <option value="4">Option 4</option>
                <option value="5">Option 5</option>
            </select>
            <input type="submit" value="Submit" name="Submit">
            <?php echo "hello"; ?>
        </form>
        <script
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous">
        </script>
        <script src="ajax.js"></script>
    </body>
</html>

PHP

<?php

$errors = array();
$data = array();

if($_SERVER["REQUEST_METHOD"] === "POST") {

    if($_POST["yourOptions"] == "") {
        $errors["yourOptions"] = "Please Select One";
    }

    if(!empty($errors)) {
        $data["success"] = false;
        $data["errors"] = $errors;

    } else {
        $data["success"] = true;
        $data["message"] = "Success!";

    }
    echo json_encode($data);
}
?>

jquery AJAX

alert("loaded");
$(document).ready(function() {

    $("#frm").submit(function(event) {
        alert("sub");
        event.preventDefault();

        console.log(typeof document.getElementById("yourOptions"));

        $(".form-group").removeClass("is-invalid");
        $(".text-muted").remove();

        var formData = {
            "yourOptions"       : $("input[name=yourOptions]").val()
        };

        $.ajax({
            type        : "POST",
            url         : "process.php",
            data        : formData,
            dataType    : "json",
            encode      : true
        })

        .done(function(data) {

            console.log(data);

            if(!data.success) {

                if(data.errors.yourOptions) {
                    $("#yourOptions").addClass("is-invalid");
                    $("#frm").append("<span class='text-muted'>" + data.errors.yourOptions + "</span>");
                }

            } else {
                $("form").append("<span class='alert alert-success'>" + data.message + "</span>");
            }
        })
        .fail(function(data) {
            alert("failed");
            console.log;
        });
    });
});

The data-type is object, but then again, so were the other fields. How do I get php to process the selected option?

2

Answers


  1. Replace

    $("input[name=yourOptions]").val()

    with

    $( "#yourOptions" ).val()
    
    Login or Signup to reply.
  2. Serialize ajax will post all data you want

    $(document).ready(function(){
        $('#frm').submit(function(event){
        event.preventDefault();
        var formValues = $(this).serialize();
            $.ajax({
            url:"process.php",
            method:"POST",
            data:formValues,
            dataType:"JSON",
                success:function(data){
                    if(data === 'ok'){
                        $('#result').html(data);
                    } else {
                        $('#result').html(data);
                        $('#frm')[0].reset();
                    }
                }
            });
        });
    });
    

    How you show result :

    <div id="result"></div>
    

    See this question for detailed explanition and more : Jquery ajax setTimeout after form succes not redirecting?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search