WordPress and Ajax

adding the Ajax URL to the theme head

The file that handles all Ajax calls on WordPress is /wp-admin/admin-ajax.php. The URL for this file should be recognized with the client by defining it as a local javascript variable with the theme head:

function print_zw_rating_scripts () {
wp_register_script( 'my_ajax', plugins_url( 'my_ajax.js' , __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'my_ajax', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('my_ajax');
}
if (!is_admin()) {
add_action('wp_print_scripts', 'print_zw_rating_scripts');
}

If all went well, viewing the page source on the browser, you should see this output:
bla
A new object ‘my_ajax’, has been created within the global scope, and may be reached from your other scripts.

Adding ‘nonce’

Along with all the data we are passing to the server, we will also pass a security key:

<?php
$nonce = wp_create_nonce("my_user_vote_nonce");
?>
<input type="hidden" value="<?php echo $nonce; ?>" name="ny_nonce" id="my_nonce" />

Setting the ajax function on the client side

this should go inside the javascript file:

jQuery(document).ready( function() {
jQuery(".my_action_button").click( function() {
ajax_data = jQuery('#ajax-data').val()
nonce = jQuery('$my_nonce').val();

jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_server_action", post_id : post_id, nonce: nonce, ajax_data: ajax_data},
success: function(response) {
if(response.type == "success") {
// do something
}
else {
// handle errors
}
}
})

})

})

Meanwhile, on the server side…

On our functions/plugin file we add the function that should take care of the data sent by the client:

function process_my_data() {
// validating the 'nonce' security key:
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}

$ajax_data = $_request['ajax_data'];

// if all is well - process the data ,and echo the results.
echo 'heres what you get back.';
// else: handle errors.
// always die at the end, otherwise, the admin-ajax.php will go on with a non relevant output...
die();
}

Adding our action to the ajax queue

We hook our action on 2 action hooks. One for admin mode, and on for the front-end mode:

add_action("wp_ajax_my_server_action", "process_my_data");
add_action("wp_ajax_nopriv_my_server_action", "process_my_data");

Keep in minde that this hook connects the client action that is defined with the javscript function (in this case it’s name is: my_server_action), with the function defined on the server side: (named in our case “process_my_data”)

That’s it!