Platform: WordPress
I have a group of two clonable fields name
and email
. So when user clones, they will have a set of name
and email
fields.
Note: These fields are newly added to my code and AJAX was working fine with the older code without two newly added fields.
The ajax code is always giving me an undefined index name
error. See exact error below print in the debug.log file
PHP Notice: Undefined index: name in .../cart-add-process-ajax.php on line 89
Line 89 code
The below code to check if both fields have the same number of array items. So later I can combine them to an associative array.
Additionally, these fields are options so if empty AJAx should still process.
if (count($_POST[ 'name' ]) != count($_POST[ 'email' ])) {
// throw customers error
wp_send_json_error(__('Customer details are incorrect', 'online-shop'));
}
AJAX
$('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>
Question:
How to process ajax with clonable form fields so that I can get as an array in PHP?