Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Ajax requests in Wordpress

Olivia Rhye

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");
}
}
});

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy