Ajax requests in WordPress using jQuery

0
95
How to write Ajax requests in WordPress using php and js? To create an ajax request, you need to register an action handler (method) in the functions.php file:
// Mini cart ajax in functions.php


add_action( 'wp_ajax_minicart', 'mcart_ajax' );
add_action( 'wp_ajax_nopriv_minicart', 'mcart_ajax' );


function mcart_ajax(){
    require get_template_directory() . '/inc/wc-custom-mini-cart.php';
     echo custom_wc_mini_cart_toggle();
    die;
}
You also need to write the ajax request itself in the js file of your WordPress theme.
// updateMiniCart function


function updateMiniCart() {
  $.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: 'action=minicart',
beforeSend: function (xhr) {
  // $('.header-mini-cart').text('Загрузка...');
},
success: function (data) {
  $('.header-mini-cart').empty();
  $('.header-mini-cart').append(data);
}
  });
}


// Actions after click buttons


$('.woocommerce-js').on('click', 'form.cart .button', function() {
setTimeout(updateMiniCart, 1500);
//updateMiniCart();
});
$('.woocommerce-js').on('click', '.add_to_cart_button', function() {
setTimeout(updateMiniCart, 1500);
});

LEAVE A REPLY

Please enter your comment!
Please enter your name here