Я разрабатываю уникальный плагин корзины для WordPress. У меня странная ошибка Undefined index
только в Safari. Я не понимаю, почему это только на сафари, но нормально работает в других браузерах.
Пожалуйста, посмотрите это видео, там я подробно объяснил.
Видео
https://youtu.be/j7wxcUYw-hU
Перейти непосредственно к точке выдачи
https://youtu.be/j7wxcUYw-hU?t=165
Ошибка
[08-May-2020 07:01:38 UTC] PHP Notice: Undefined index: c_name in /Users/usrename/Sites/wpdev/wp-content/plugins/plugin-name/public/plugin-name-cart-add-process-ajax.php on line 91
[08-May-2020 07:01:38 UTC] PHP Notice: Undefined index: c_email in /Users/usrename/Sites/wpdev/wp-content/plugins/plugin-name/public/plugin-name-cart-add-process-ajax.php on line 91
[08-May-2020 07:01:38 UTC] PHP Notice: Undefined index: c_qty in /Users/usrename/Sites/wpdev/wp-content/plugins/plugin-name/public/plugin-name-cart-add-process-ajax.php on line 91
Код в строке 91
// setup customers
$customers = gs_validate_customers_on_add($_POST[ 'c_name' ], $_POST[ 'c_email' ], $_POST[ 'c_qty' ], $_POST[ 'qty' ]);
Функция gs_validate_customers_on_add
объединяет все эти три поля в один ассоциативный массив после проверки входных данных. как показано ниже
[
[0] => [
'name' => 'John Doe',
'email' => 'johndoe@email.com',
'qty' => 2
],
...
]
AJAX
$(function () {
let response_alert = $('#response');
response_alert.hide();
$('form.addtocartform').on('submit', function (e) {
e.preventDefault();
let formData = $(this).serialize();
let names = [];
let emails = [];
$('input[name="name"]').each(function () {
names.push(this.value);
});
$('input[name="email"]').each(function () {
emails.push(this.value);
});
console.log(names);
$.ajax({
method: 'POST',
dataType: 'json',
url: ajax_vars.ajax_url,
data: formData + "&action=gs_add_to_cart&nonce=" + ajax_vars.nonce,
beforeSend: function () {
console.log(this.data);
console.log('Sending...');
},
success: function (response) {
if (response.success === true) {
console.log(response);
let message = response.data.message;
let gifts = response.data.gifts;
let next_gift = response.data.next_gift;
// display next gift item
if (response.data.hasOwnProperty('next_gift')) {
response_alert.fadeIn().prepend(alerts('info', next_gift));
}
// display gift items
if (response.data.hasOwnProperty('gifts')) {
response_alert.fadeIn().prepend(alerts('gift', gifts));
}
// display success message
response_alert.fadeIn().prepend(alerts('success', message));
// $('#product_option').val(null);
$('#qty').val(1);
$('#product_option, .customer-name, .customer-email').val(null);
}
if (response.success === false) {
response_alert.fadeIn().prepend(alerts('error', response.data));
}
gs_alert_stats();
},
error: function (response) {
let error_message = (response.data === undefined) ? 'Something went wrong!' : response.data;
response_alert.fadeIn().prepend(alerts('error', error_message));
gs_alert_stats();
},
complete: function () {
}
});
return false;
});
// control dynamically created error with JS - close/hide
function gs_alert_stats() {
let gs_alert = $('.gs-message');
$('.gs-close').on('click', function () {
alerts('Clicked');
$(this).parent(gs_alert).fadeOut();
});
}
});
Функция обратного вызова
function gs_add_p_to_cart_ajax()
{
// Check if user is logged in
if ( ! is_user_logged_in()) {
// throw error if user is not logged in
wp_send_json_error(__('Please login to order', 'group-shop'));
// we use this manually as want to print error
wp_die();
}
// check and validate nonce
if ( ! check_ajax_referer('gs_nonce', 'nonce', FALSE)) {
// throw error if validation fails
wp_send_json_error(__('Do not be nasty with validation', 'group-shop'));
// we use this manually as want to print error
wp_die();
}
// prepare for data validation
$group_id = absint($_POST[ 'group_id' ]);
$product = absint($_POST[ 'product' ]);
$qty = absint($_POST[ 'qty' ]);
$customers = NULL;
$product_option = NULL;
if ( ! gs_group_is_active($group_id)) {
// throw error if group is closed
wp_send_json_error(__('Last purchase date is crossed', 'group-shop'));
}
// check group id
if ( ! $group_id) {
// throw error if validation fails
wp_send_json_error(__('Group is not defined', 'group-shop'));
}
// check product id
if ( ! $product) {
// throw error if validation fails
wp_send_json_error(__('Product is not defined', 'group-shop'));
}
// setup customers
$customers = gs_validate_customers_on_add($_POST[ 'c_name' ], $_POST[ 'c_email' ], $_POST[ 'c_qty' ], $_POST[ 'qty' ]);
// check option value
if (isset($_POST[ 'product_option' ]) && $_POST[ 'product_option' ] === '') {
// throw error if validation fails
wp_send_json_error(__('Please select option', 'group-shop'));
} else {
$product_option = (isset($_POST[ 'product_option' ])) ? absint($_POST[ 'product_option' ]) : NULL;
}
if ($qty <= 0) {
// throw error if validation fails
wp_send_json_error(__('At lest one quantity is required', 'group-shop'));
}
// insert record
$cart = new Group_Shop_Cart();
$cart_id = $cart->add_p_to_cart($group_id, $product, $qty, $customers, $product_option);
// if record inserted
if ($cart_id) {
$disc = new Group_Shop_Discount();
$disc->set_gift_response_data($group_id, get_current_user_id(), 'Product is added to cart');
$data = [
'message' => __('Product is added to cart', 'group-shop'),
'gift' => $disc->get_gift_data($group_id, get_current_user_id()),
];
// show success message once record inserted
wp_send_json_success($disc->gift_response_data);
} else {
// throw error if fails to insert record
wp_send_json_error(__('Something went wrong', 'group-shop'));
}
// stop further execution once all process done
wp_die();
}
// hook the function
add_action('wp_ajax_gs_add_to_cart', 'gs_add_p_to_cart_ajax');
add_action('wp_ajax_nopriv_gs_add_to_cart', 'gs_add_p_to_cart_ajax');
Заголовок
Summary
URL: http://wpdev.org/wp-admin/admin-ajax.php
Status: 500 Internal Server Error
Source: Network
Address: 127.0.0.1:80
Initiator:
jquery.js:4:26433
Request
POST /wp-admin/admin-ajax.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Host: wpdev.org
Origin: http://wpdev.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15
Connection: keep-alive
Referer: http://wpdev.org/products/pizza/?group_id=298
Content-Length: 86
Cookie: wordpress_8ce0964f9d22....45p5
X-Requested-With: XMLHttpRequest
Response
HTTP/1.1 500 Internal Server Error
Access-Control-Allow-Origin: http://wpdev.org
Content-Type: text/html; charset=UTF-8
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Referrer-Policy: strict-origin-when-cross-origin
Cache-Control: no-cache, must-revalidate, max-age=0
Date: Fri, 08 May 2020 09:18:49 GMT
Access-Control-Allow-Credentials: true
Content-Length: 178
Connection: close
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Powered-By: PHP/7.4.2
Server: Apache/2.4.41 (Unix) PHP/7.4.2
X-Robots-Tag: noindex
Request Data
MIME Type: application/x-www-form-urlencoded; charset=UTF-8
action: gs_add_to_cart
nonce: 6d13df5fc3
group_id: 298
product: 297
qty: 1
product_option: 1
Глядя на Запросить данные в заголовке ответа, я обнаружил, что c_name
, c_email
и c_qty
отсутствуют. Я не понимаю, почему он не отправляется, поскольку он находится в той же форме.