Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

User:Mat/AJAX in Plugins

Introduction

Cet article, à l'attention des développeurs de plugins, décrit comment ajouter de l'Ajax à un plugin. Avant de lire cet article, vous devriez être familiés avec les suivants :

  • Ajax - Vue d'ensemble de la technologie
  • Writing a Plugin - Comment écrire un plugin
  • Plugin API - Filtres et actions - Que sont-ils et comment les utiliser

Ajax dans la partie administration

Puisque l'Ajax est déjà intégré au coeur des écrans d'administration de Wordpress, ajouter plus de fonctionnalité liè à de l'AJAX est plutôt simple.

Ce court exemple utilise PHP pour écrire notre code JavaScript dans le footer de la page. Ce script lance alors une requète AJAX quand la page est complètement chargée :

<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Écris notre JS ci-dessous

function my_action_javascript() { ?>
	<script type="text/javascript" >
	jQuery(document).ready(function($) {

		var data = {
			'action': 'my_action',
			'whatever': 1234
		};

		// Depuis 2.8 ajaxurl est toujours défini dans le header de l'admin et pointe vers admin-ajax.php
		jQuery.post(ajaxurl, data, function(response) {
			alert('Got this from the server: ' + response);
		});
	});
	</script> <?php
}
NOTE: Depuis Version 2.8, The JavaScript global variable ajaxurl can be used in case you want to separate your JavaScript code from php files into JavaScript only files. This is true on the administration side only. If you are using AJAX on the front-end, you need to make your JavaScript aware of the admin-ajax.php url. A best practice is documented in the fourth example, below using wp_localize_script().

Then, set up a PHP function to handle the AJAX request.

<?php 

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {
	global $wpdb; // this is how you get access to the database

	$whatever = intval( $_POST['whatever'] );

	$whatever += 10;

        echo $whatever;

	wp_die(); // this is required to terminate immediately and return a proper response
}

Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below. This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.

You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin.

Notice the use of wp_die(), instead of die() or exit(). Most of the time you should be using wp_die() in your Ajax callback function. This provides better integration with WordPress and makes it easier to test your code.

Separate JavaScript File

The same example as the previous one, except with the JavaScript on a separate external file we'll call js/my_query.js. The examples are relative to a plugin folder.

jQuery(document).ready(function($) {
	var data = {
		'action': 'my_action',
		'whatever': ajax_object.we_value      // We pass php values differently!
	};
	// We can also pass the url value separately from ajaxurl for front end AJAX implementations
	jQuery.post(ajax_object.ajax_url, data, function(response) {
		alert('Got this from the server: ' + response);
	});
});

With external JavaScript files, we must first wp_enqueue_script() so they are included on the page. Additionally, we must use wp_localize_script() to pass values into JavaScript object properties, since PHP cannot directly echo values into our JavaScript file. The handler function is the same as the previous example.

<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
    if( 'index.php' != $hook ) {
	// Only applies to dashboard panel
	return;
    }
        
	wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );

	// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
	wp_localize_script( 'ajax-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}

// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
	global $wpdb;
	$whatever = intval( $_POST['whatever'] );
	$whatever += 10;
        echo $whatever;
	wp_die();
}