使用Pjax提交表单时未定义索引

PHP Undefined index when submitting form with Pjax

本文关键字:未定义 索引 表单 Pjax 提交 使用      更新时间:2023-09-26

我一直在试验Pjax,到目前为止我很喜欢它。它工作得很好,但我遇到了一个问题。当提交一个表单(post)与pjax,一切工作,但我得到一个"PHP通知:未定义的索引:名称"在错误日志。

下面是我提交表单的代码:

$(document).on('submit', 'form[data-pjax]', function(event) {
    event.preventDefault();
    $.pjax.submit(event, '#containercontainer');
    return false;
});

我已经得到了所有必需的.js文件包括,但这里不是为了简单。

这是我的表单的删节版本:

<form data-pjax method="POST" action="add-process.php" id="addform">
    <div class="row">
        <div class="col-sm-5">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" id="name" placeholder="Name" name="name" autocomplete="off" autofocus>
            </div>
        </div>
        ...
    </div>
    <button id="submit_btn" type="submit" class="btn btn-success btn-block" style="font-weight:bold;">ADD</button>
</form>

在add-process.php文件中,我得到$name = $_POST['name']的变量;但是错误日志显示这些行没有定义索引。

更新:

我修改了我的PHP代码,包括推荐的isset(),如下所示:
// GET INFO FROM FORM
if(isset($_POST['userID'])) {
    $userID = $_POST['userID'];
}
if(isset($_POST['reason'])) {
    $reason = $_POST['reason'];
}
if(isset($_POST['otherreason'])) {
    $otherreason = $_POST['otherreason'];
}
if($reason == 3) {
    $reason = $otherreason;
}
if(!is_numeric($userID)) {
    echo 'User ID not numeric!';
    exit();
}

修复了一些事情,但我仍然在日志中得到错误:

PHP Notice:  Undefined variable: reason
PHP Notice:  Undefined variable: userID
再次感谢您的帮助!

你得到

PHP Notice:  Undefined variable: reason
PHP Notice:  Undefined variable: userID

因为你的isset($_POST['userID']) AND isset($_POST['reason'])返回false,因为它们不存在。这就是变量未定义的原因。您可以添加"默认"值。

您可以跟踪表单发送到服务器端的内容。试试这个:

print_r($_POST);

print_r($_REQUEST);

about form:检查输入的名称。输入名称'userID'和'reason'存在吗?

任何时候在条件中设置变量时,最好先初始化它们:

$reason = null;
$userID = false;
/* .... your current code starts here   */

PHP抛出通知以帮助您避免由输入引起的错误(即稍后引用userrid等)。首先初始化它们可以清楚地表明您实际上使用的是您想要的名称。