How to Use Ajax in WordPress

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</a>

Function

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.

Admin Ajax:

WordPress uses already built-in admin-ajax.php to perform all the Ajax related functions. The url  myAjaxData.ajaxurl used in the below js function should be first localized.

wp_enqueue_script( 'custom', plugin_dir_url( __FILE__ ) . 'js/team-manager-admin.js', array('jquery'), $this->version, false );
wp_localize_script(
'custom',
'myAjaxData',
array( 'ajaxurl' => admin_url('admin-ajax.php') )
);

Note that this admin.ajax url will be used in the ajax function below.

 

Accepting and Sending data via JS

Finally, create a js file custom.js (enqueued above) and put the below js function to receive the response from ajax and checks if the response is success. The post_id from the above link is received here.

jQuery(".order").click( function() {
post_id = jQuery(this).attr("data-post_id"); //get post_id
nonce = jQuery(this).attr("data-nonce"); //get data-nonce
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjaxData.ajaxurl,
data : {action: "jfo_add_order", post_id : post_id, nonce: nonce}, //send post_id and nonce back to above main php function
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. This is shows the headers, that is what is being transfered via that ajax action.

1 comment found

Leave comment

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