Ajax requests in WordPress
November 7, 2016
There are many reasons to use Ajax on a website as it allows the content to load into the page as needed. In the past i’ve always made a separate file for handling all these things, and performance wise they may be about the same. However, there is a built in way to do these things the official WordPress way that was actually easier to work with than creating new services.
WordPress Documentation
Demo example
Summarizing, there is a “wp_ajax_[ACTION]” hook that allows server side processing of the ajax request.
add_action( 'wp_ajax_nopriv_[ACTION]', 'ajax_process_function' );
add_action( 'wp_ajax_[ACTION]', 'ajax_process_function' );
function ajax_process_function() {
$filterpage = $_REQUEST['page'];
$filterformat = $_REQUEST['format'];
echo "Page:".$filterpage." Format:".$filterformat;
die();
}
This is accompanied by a jQuery ajax request that looks like:
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: 'post',
data: {
action: '[ACTION]',
filterpage : 1,
filterformat : "format"
},
success: function( html ) {
if(html){
$('#container').html( html );
}else{
alert("no content");
}
}
});