Ajax is widely used in wordpress, it is very easy to use by using admin-ajax.php. In this tutorial, we will introduce how to implement an ajax function in wordpress.
Get the url of admin-ajax.php
In order to use ajax, we need to know the url of admin-ajax.php first. We can do like this:
<?php $admin_url=admin_url( 'admin-ajax.php' ); ?>
Define the function to process the ajax request and data that will be sent
Client will send some data to server, the data should be a dictionary.
The function that process the ajax request also be sent to server. For example:
<script type="text/javascript"> jQuery(document).ready(function($){ var data={ action:'loadx', key:'<?php echo urlencode(get_the_title());?>' } $.post("<?php echo $admin_url;?>", data, function(response) { $("#book_cloud").html(response); }); }); </script>
var data contains the method that process the ajax request, which is defined as: action: method_for_ajax.
action:’loadx’, which means wordpress will use a function named loadx to process ajax request.
key: value, which means value will be sent to wordpress, we can get it by name key. Of course, you also can send more data to wordpress server using different key name.
$.post: which means browser will use http post method to send data to wordpress server.
Process ajax request
WordPress can receive and process the request sent by ajax.
We first create a function named loadx to process the ajax request, this name is determined by action: loadx
<?php function loadx(){ $key = $_POST['key']; //process die(); } ?>
We can use $_POST to receive data sent by ajax. If ajax use http get method to send data, we can use $_GET to get the data sent by ajax.
Then we should tell wordpress to use loadx function to process ajax request, here is the example code.
add_action('wp_ajax_loadx', 'loadx'); add_action('wp_ajax_nopriv_loadx', 'loadx');
We can find wp_ajax_loadx and wp_ajax_nopriv_loadx, both of their name ends with loadx, which is the name of function that process ajax request.
Finally, wordpress will use loadx to process ajax request.