Ajax ( Asynchronous JavaScript and XML ) allows us do action in asynchronous way – without page reloading. It is very useful and has affect on better user experience. We can for example add, hide or delete some content from site and there’s no need to reload whole page.
In WordPress ajax calls works a little bit differently than normally. Normally, if we want to load file with code, that would be called in ajax method, we must pass url to that file:
But in WordPress we pass url to early prepared object with data, that we want to pass through ajax. First, we must add script file, and then localize it, to let WordPress know, what data we want to use. We use wp_localize_script() to do it:
$.ajax({
url : lovecoding_script_ajax_object.ajax_url, // from functions.php file: wp_localize_script -> $object_name.$key_with_url
method : 'post',
dataType: 'json',
data : {action: 'my_function_ajax', _ajax_nonce: lovecoding_script_ajax_object.ajax_nonce, some_data: my_data }, // action: function, that is invoked by ajax
success : function(response) {
//do something with response
})
Now we must just write function which do what we want to do and add it do wp_ajax_$action or wp_ajax_nopriv_$action hook:
functions.php
function lovecoding_my_function_ajax {
// check nonce
check_ajax_referer( 'lovecoding_ajax_nonce', '_ajax_nonce' );
// get data sent by ajax and do something with them
$my_data = sanitize_text_field( $_POST['some_data'] );
// return data to jQuery ajax
echo json_encode("your returned data - you must echo it, not return!");
die();
}
add_action( 'wp_ajax_my_function_ajax', 'lovecoding_my_function_ajax' ); // to logged in users
add_action( 'wp_ajax_nopriv_my_function_ajax', 'lovecoding_my_function_ajax' ); // to not logged in users or users without permissions
When we send data from PHP to jQuery ajax using echo json_encode(data), we must use die() function at the end of code, to avoid generate extra output, which may break our data.
Author: Joanna
I write code that (usually) works. I tame WordPress, learn React, explore the world of DevOps, and click around in the Linux console. I optimize code as a hobby, because laziness is the purest form of productivity. I do my best not to lose my mind somewhere between a bug and a deadline.