Want to do something without even reloading the page on wordpress ?
Use WP Ajax.
Using WP Ajax, You can do stuff asynchronously like Add to Cart, Refresh Fragments, Change Quantity of Products, Load more posts and many more.
How to create Ajax Calls in WordPress ?
1. Create Ajax Actions on WordPress.
Example: Woocoommerce Add to Cart with Quantity using Ajax
Add this inside your theme’s functions.php file.
<?php
// Add AJAX for logged in users.
add_action("wp_ajax_cmw_add_to_cart", "cmw_add_to_cart");
// Add AJAX for not logged in users.
add_action("wp_ajax_nopriv_cmw_add_to_cart", "cmw_add_to_cart");
function cmw_add_to_cart() {
// Verify Nonce
if ( !wp_verify_nonce( $_REQUEST['nonce'], "cmw_add_to_cart_nonce")) {
die("404 Access Denied");
}
if(isset($_REQUEST['product_id']) && isset($_REQUEST['quantity'])) {
$product_id = $_REQUEST['product_id'];
$quantity = $_REQUEST['quantity'];
WC()->cart->add_to_cart( $product_id, $quantity);
echo json_encode(array("added"=>true));
}
die();
}
2. Create jQuery to Trigger Ajax
Add this inside your theme’s functions.php file.
add_action('wp_enqueue_scripts', 'cmw_enqueue_js');
function cmw_enqueue_js() {
// Register Custom JS File (We will put Ajax Code inside this file);
// Use get_template_directory_uri for Theme.
// Use get_stylesheet_directory_uri for Child Theme.
wp_register_script( "cmw_script", get_template_directory_uri().'/css/cmw_script.js', array('jquery') );
wp_localize_script( 'cmw_script', 'cmw', array( "ajaxurl" => admin_url( 'admin-ajax.php' ), "nonce" => wp_create_nonce("cmw_add_to_cart_nonce")));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'cmw_script' );
}
Add this inside your theme’s YOUR_THEME_DIR/js/cmw_script.js file. (Create this file if not exists)
jQuery(function($) {
$.post(
cmw.ajaxurl,
{
"action": "",
"product_id": 1122,
"quantity": 1
},
function(data, status) {
data = JSON.parse(data);
if(data.added) {
window.alert("Product Added to cart");
}
}
)
});
It’s Done!
Using Ajax to load stuff asynchronously is pretty good idea. Use it to make your website better and faster.
Do you know ?
Using Ajax on WordPress reduces load on server as it reduces the number of reloads and loads only needed content.