How to Use Ajax in WordPress

Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to the plugin is fairly straightforward.

Example

Below is a simple example where a post id is sent via ajax and is used by a main handler function (here storing a post id in session) whenever a button(link) is clicked.

So, here is a link:

<a class="order" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="javascript:void(0);">Order

Next,
the main handling function where the main task is carried out. Here the received post id is being stored in the session. If the result is true, success message will be sent which will be later fetched by the below js.

function my_user_qty() {
$qty_count = '1';
if(isset($_SESSION['cart_item'][$_REQUEST['post_id']]))
{
$_SESSION['cart_item'][$_REQUEST['post_id']] = array(
'qty'=> ($_SESSION['cart_item'][$_REQUEST['post_id']]['qty'])+1,
);
$new_qty_count = $_SESSION['cart_item'][$_REQUEST['post_id']]['qty'];
}
else{
$_SESSION['cart_item'][$_REQUEST['post_id']] = array(
'qty'=> $qty_count,
);
}
if($_SESSION['cart_item'][$_REQUEST['post_id']]) {
$new_qty_count = $_SESSION['cart_item'][$_REQUEST['post_id']]['qty'];
$result['type'] = "success";
$result['qty'] = $new_qty_count;
}
else {
$result['type'] = "error";
$result['qty'] = $qty_count;
}
if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
{
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}

After that, the above function needs to be hooked in as shown below.
$this->loader->add_action( 'wp_ajax_jfo_add_order', $plugin_public, 'my_user_qty');
$this->loader->add_action( 'wp_ajax_nopriv_jfo_add_order', $plugin_public, 'my_user_qty');

Note the “jfo_add_order” in above hooks: wp_ajax_jfo_add_order, wp_ajax_nopriv_jfo_add_order. This must match with the ‘action’ in the js below.

Finally, the js function to receive the response from ajax and checks if the response is success. The post_id sent from the above link is received here.

jQuery(".order").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjaxData.ajaxurl,
data : {action: "jfo_add_order", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type === "success") {
jQuery(".order-msg").show();
setTimeout(function() { jQuery(".order-msg").fadeIn("slow"); }, 3000);
}
else {
jQuery(".order-msg-failed").show();
setTimeout(function() { jQuery(".order-msg-failed").fadeIn("slow"); }, 3000);
}
}
})
})

Ajax response:

Ajax response can be checked in browser’s console under ‘Network’ tab as below. This helps to debug (error if any) and also the kind of response that is being triggered.

Leave comment

Your email address will not be published. Required fields are marked with *.