Skip to content
Advertisement

how to display form errors under input field with php and javascript

I have a form. I want to submit the form without reloading the page. so I am using ajax to send data to PHP and then validating the inputs with PHP storing the errors in an array. How can I return error array to javascript and show errors in input fields.

Any Suggestions?

<form action="" method="post" id="order-form">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" name="name" placeholder="Your Name" id="name" class="form-control">
                <small></small>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <input type="text" name="email" placeholder="Email Address" id="email" class="form-control">
                <small></small>
            </div>
        </div>
    </div>
    <!-- some more inputs -->
    <?= csrf_token_tag(); ?>
    <button type="submit">Subscribe</button>
</form>

PHP

<?php

$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$csrf_token = $_POST['csrf_token'] ?? '';

$errors = [];

if (!csrf_token_is_valid($csrf_token) && !csrf_token_is_recent($csrf_token)) {
    $errors['form'] = 'The security token is missing from your request';
}

if (is_blank($name) || has_length_less_than($name, 3)) {
    $errors['name'] = 'Name must be at least 3 chars long.';
}

if (is_blank($email) || !has_valid_email_format($email)) {
    $errors['email'] = 'Looks like this email is incomplete.';
}

if (empty($errors)) {
    // do something
} else {
    return $errors;
}

Javascript

const form = $('#order-form')
form.on('submit', e => {
    e.preventDefault()

    $.ajax({
        type: 'post',
        url: '<?= SITE_URL . '/private/shared/order-form-process'; ?>',
        data: form.serialize(),
        success: (result) => {
            console.log(result)
        }
    });
})

Advertisement

Answer

At first change this portion of the php file

if (empty($errors)) {
    // do something
} else {
    return $errors;
}

with this

if (empty($errors)) {
    // do something
    //don't return any other text before
    echo "{}";
} else {
    echo json_encode($errors);
}
exit();

This (json_encode(…)) will convert the php variable to a json encoded string. Now you will get back the string as result (responsetext) on client side.

At client side you can convert the string to a JSON object using JSON.parse(result); and get the errors back to a string (js string).

const form = $('#order-form');
form.on('submit', e => {
    e.preventDefault()
    $.ajax({
        type: 'post',
        url: '<?= SITE_URL . '/private/shared/order-form-process'; ?>',
        data: form.serialize(),
        success: (result) => {
            processResult(result)
        }
    });
});

function processResult(result){
    let jsonResult={};
    let haveError=false;
    try{
        jsonResult=JSON.parse(result);
    }catch(err){
        //JSON string cannot be converted to json object
        console.log("Error in returned json string");
        return;
    }
    if(jsonResult.form){
        // jsonResult.form is the $errors["form"] on php
        // show Token error to user
        console.log("Token Error");
        console.log(jsonResult.form);
        haveError=true;
    }
    if(jsonResult.name){
        // jsonResult.name is the $errors["name"] on php
        // show Name error to user
        console.log("Name Error");
        console.log(jsonResult.name);
        haveError=true;
    }
    if(jsonResult.email){
        // jsonResult.email is the $errors["email"] on php
        // show Email error to user
        console.log("Email Error");
        console.log(jsonResult.email);
        haveError=true;
    }
    if(!haveError){
        //When there is no error
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement