【问题标题】:how to display form errors under input field with php and javascript如何使用 php 和 javascript 在输入字段下显示表单错误
【发布时间】:2020-08-30 17:17:40
【问题描述】:

我有一个表格。我想提交表单而不重新加载页面。所以我使用 ajax 将数据发送到 PHP,然后使用 PHP 验证输入,将错误存储在一个数组中。如何将错误数组返回到 javascript 并在输入字段中显示错误。

有什么建议吗?

<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)
        }
    });
})

【问题讨论】:

    标签: javascript php


    【解决方案1】:

    首先更改php文件的这一部分

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

    有了这个

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

    这 (json_encode(...)) 将 php 变量转换为 json 编码的字符串。 现在您将在客户端取回字符串作为结果(responsetext)。

    在客户端,您可以使用 JSON.parse(result); 将字符串转换为 JSON 对象; 并将错误返回一个字符串(js 字符串)。

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-12
      • 2017-10-11
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      相关资源
      最近更新 更多