首页 > 解决方案 > PHP - AJAX - 字段组数组 POST 值总是显示未定义的索引

问题描述

平台:WordPress

我有一组两个可克隆字段 nameemail. 因此,当用户克隆时,他们将拥有一组nameemail字段。

注意:这些字段是新添加到我的代码中的,并且 AJAX 可以在没有两个新添加字段的旧代码中正常工作。

ajax 代码总是给我一个未定义的索引name错误。在debug.log文件中查看下面打印的确切错误

PHP 注意:未定义的索引:第 89 行.../cart-add-process-ajax.php 中的名称

第 89 行代码

下面的代码检查两个字段是否具有相同数量的数组项。所以稍后我可以将它们组合成一个关联数组。

此外,这些字段是选项,因此如果空 AJAx 仍应处理。

if (count($_POST[ 'name' ]) != count($_POST[ 'email' ])) {

    // throw customers error
    wp_send_json_error(__('Customer details are incorrect', 'online-shop'));
} 

阿贾克斯

$('form.addtocartform').on('submit', function (e) {
    e.preventDefault();

    let names = [];
    let emails = [];

    $('input[name="name"]').each(function () {
        names.push(this.value);
    });

    $('input[name="email"]').each(function () {
        emails.push(this.value);
    });

    $.ajax({

        method: 'POST',
        dataType: 'json',
        url: ajax_vars.ajax_url,
        data: {
            action: 'gs_add_to_cart',
            nonce: ajax_vars.nonce,
            group_id: $('#group_id').val(),
            product: $('#product').val(),
            qty: $('#qty').val(),
            name: names,
            email: emails,
            product_option: $('#product_option').val(),
        },
        ...
    }
}

HTML

<form method="POST" id="gsAddToCart" class="addtocartform" action="">
    <label for="product_option" class="gs-label">Options</label><select name="product_option" id="product_option" class="gs-select-box"><option value="">Select option</option><option value="0">Salty</option><option value="1">Sweet</option><option value="2">Bitter</option></select>
    <label for="qty" class="gs-label">Qty.</label>
    <input type="number" name="qty" id="qty" class="gs-number" min="1" step="1" value="1">

    <!-- these fields in the div are clonable and here I have a problem -->
    <div id="entry1" class="clonedInput gs-customer-fields">
        <input class="gs-field" type="text" name="name[]" placeholder="Name">
        <input class="gs-field" type="email" name="email[]" placeholder="Email">
    </div>
    <span class="gs-customer-delete" id="btnDel" disabled="disabled">delete</span>
    <span class="gs-customer-add" id="btnAdd">add</span>

    <input type="hidden" id="product" name="product" value="168">
    <input type="hidden" id="group_id" name="group_id" value="298">
    <input type="hidden" id="_gs_nonce" name="_gs_nonce" value="3676c059a6"><input type="hidden" name="_wp_http_referer" value="/products/id-adipisci-dolores-dicta/?group_id=298">
</form>

问题

如何使用可克隆的表单字段处理 ajax,以便我可以在 PHP 中作为数组获取?

标签: phpjqueryajax

解决方案


推荐阅读