Я делаю заказную корзину. Код Ajax корректно обновляет запись. Однако я не могу обновить / обновить сумму корзины, чтобы отразить изменения, внесенные пользователем, до перезагрузки страницы.
AJAX
(function ($) {
$(function () {
let response_alert = $('#response');
response_alert.hide();
let update_button = $('.gs-update-order-btn');
let delete_button = $('.gs-delete-order-btn');
// updated process
update_button.on('click', function () {
let data_type = $(this).data('type');
let data_id = $(this).data('id');
let row_id = $(this).data('row');
let data_user = $(this).data('for');
$(this).addClass('updating');
$.ajax({
method: 'POST',
dataType: 'json',
url: ajax_vars.ajax_url,
data: {
action: 'gs_update_cart',
nonce: ajax_vars.nonce,
type: data_type,
id: data_id,
row: row_id,
qty: $('#qty-' + row_id).val(),
group_user: data_user
},
success: function (response) {
console.log(response);
let response_alert = $('#response');
if (response.success === true) {
response_alert.fadeIn().prepend(alerts('success', response.data));
}
if (response.success === false) {
response_alert.fadeIn().prepend(alerts('error', response.data));
}
gs_alert_stats();
}
,
error: function (response) {
console.log(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 () {
update_button.removeClass('updating');
}
});
gs_alert_stats();
});
// delete process
delete_button.on('click', function () {
let data_type = $(this).data('type');
let data_id = $(this).data('id');
let row_id = $(this).data('row');
// ajax code here ...
$('#data-' + data_type + '-row-' + row_id).detach();
response_alert.fadeIn().prepend(alerts('error', 'Item deleted!'));
gs_alert_stats();
});
});
})(jQuery);
Функция WordPress AJAX
function gs_update_p_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'));
// cross confirm to die
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'));
// cross confirm to die
wp_die();
}
// prepare for data validation
$type = sanitize_text_field($_POST[ 'type' ]);
$row_id = absint($_POST[ 'row' ]);
$id = absint($_POST[ 'id' ]);
$qty = absint($_POST[ 'qty' ]);
$group_user = absint($_POST[ 'group_user' ]);
if ($row_id <= 0) {
// throw error if validation fails
wp_send_json_error(__('Invalid item id', 'group-shop'));
}
if (empty($type)) {
// throw error if validation fails
wp_send_json_error(__('Undefined item type', 'group-shop'));
}
if ($id <= 0) {
// throw error if validation fails
wp_send_json_error(__('Invalid item', 'group-shop'));
}
if ($qty <= 0) {
// throw error if validation fails
wp_send_json_error(__('At lest one quantity is required', 'group-shop'));
}
// instantiate cart object
$cart = new Group_Shop_Cart();
if ($type == 'p') {
// update product
if ($cart->update_product($row_id, $id, $qty, $group_user)) {
// show success message once record updated
wp_send_json_success(__('Item is updated', 'group-shop'));
} else {
// throw error if fails to update record
wp_send_json_error(__('There is nothing to update', 'group-shop'));
}
// stop further execution once all process is done
wp_die();
} elseif ($type == 'pg') {
// update product group
} else {
// throw error if validation fails
wp_send_json_error(__('Invalid item type', 'group-shop'));
}
}
HTML-разметка
<table class="gs-orders-table">
<caption class="cart-total">Order Total</caption>
<tbody>
<tr>
<td class="content-cart-title">Products</td>
<td class="content-cart-price">5 042,00 kr</td>
</tr>
<tr>
<td class="content-cart-title">Product Groups</td>
<td class="content-cart-price">8 578,00 kr</td>
</tr>
<tr>
<td class="content-cart-title cart-total">Total</td>
<td class="content-cart-price cart-total">13 620,00 kr</td>
</tr>
</tbody>
</table>
К вашему сведению, у меня в классе есть метод, который возвращает различные значения для корзины. Так что, если я смогу использовать это для обновления итогов в корзине после успеха ajax.
Массив методов корзины
Array
(
[products] => Array
(
[count] => 5
[qty] => 15
[total_raw] => 5042
[total_formatted] => 5 042,00 kr
)
[product_groups] => Array
(
[count] => 3
[qty] => 6
[total_raw] => 8578
[total_formatted] => 8 578,00 kr
)
[cart] => Array
(
[count] => 8
[qty] => 21
[cart_total] => 13620
[cart_total_formatted] => 13 620,00 kr
)
)