使用JavaScript Fetch API时输出PHP表单验证错误消息 [英] Output PHP Form Validation Error Messages When Using JavaScript Fetch API

查看:176
本文介绍了使用JavaScript Fetch API时输出PHP表单验证错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个表单的页面,其中每个表单都是在后端使用PHP处理的,该后端将数据发送到MySQL数据库,但在前端,它使用Java脚本的fetchAPI来防止在表单的一个实例完成并将数据发送到数据库时刷新页面。

我有一些正在进行的PHP服务器端验证,这些验证仍然适用于不将数据发送到数据库,尽管在提交时,完成的表单实例确实会从页面中消失(由于下面显示的Java脚本),但如果验证失败,则在刷新时重新出现。

下面的主代码示例包括通常输出错误消息的代码块:

<?php 
    // echo form validation error messages
    if(isset($error)) {
        foreach($error as $msg) {
            echo "<p>** {$msg}</p>";
        }
    }
?>
在输出这些错误消息方面,是否仍然可以使用此PHP代码(目前无法工作),或者我现在将javascript fetchAPI与PHP结合使用,除了安全地防止表单未能通过验证的PHP验证之外,我还需要用JavaScript编写验证以在前端输出错误吗?应该注意的是,页面上有多个表单实例,它们是通过While循环输出的,每个实例都与特定的POST相关。

<?php
if(isset($_POST['upload-submit'])) {
    // note $imageTitle is a variable given to the title of a post submitted via an HTML form

    if(!preg_match('/^[a-zA-Z0-9s]+$/', $imageTitle)) {
        $error[] = "Post Title can be letters and numbers only";
    }

    if(empty(trim($imageTitle))){
        $error[] = "Image Title cannot be blank";
    }

    // if no errors process submission
    if (!isset($error)) {

        try {

        // PDO prepared statements that update the database
    
        } catch (PDOException $e) {
            echo "There is an error: " . $e->getMessage();
        }

    }
}
?>

这里还有在页面上工作的javascript fetchAPI代码。

var forms = document.querySelectorAll('.image-upload-details-form'),

forms.forEach(item => {
    
        item.querySelectorAll('[type="submit"], button').forEach(button => {
            button.addEventListener("click", e => item._button = button); //store this button in the form element
        })

        item.addEventListener("submit", function(evt, btn) {

            evt.preventDefault();

            const formData = new FormData(this);
            if (this._button) //submitted by a button?
            {
            formData.set(this._button.name, this._button.value);
        }

        fetch("upload-details.php", {
            method: 'post',
            body: formData
        }).then(function(response){
            return response.text();
        }).then(function(text){
            console.log(text);
        }).catch(function (error){
            console.error(error);
        })

        // removes form when submitted
        item.remove();

    })

})

非常感谢您的帮助/建议。

推荐答案

您需要一次性回显所有错误,否则只会得到第一个回音...;

<?php 
        // echo form validation error messages
        $echo = [];
        if(isset($error)) {
            foreach($error as $msg) {
                $echo[] = "<p>** {$msg}</p>";
            }
        echo implode(PHP_EOL, $echo);
        }
    ?>

和您的其他区块:

<?php
if(isset($_POST['upload-submit'])) {
    // note $imageTitle is a variable given to the title of a post submitted via an HTML form

    if(!preg_match('/^[a-zA-Z0-9s]+$/', $imageTitle)) {
        $error[] = "Post Title can be letters and numbers only";
    }

    if(empty(trim($imageTitle))){
        $error[] = "Image Title cannot be blank";
    }

    // if no errors process submission
    if (!isset($error)) {

        try {
        $success = false;
        // PDO prepared statements that update the database => success = true ?
        echo $success;
        } catch (PDOException $e) {
            echo "There is an error: " . $e->getMessage();
        }

    }
    echo $errors; // form 'user' errors
}
?>

或类似的smthg

这篇关于使用JavaScript Fetch API时输出PHP表单验证错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆