How to manage ajax calls and JSON in wordpress

Ajax Handler

It is indeed a bit confusing that the Ajax handler is in the wp-admin/ directory, but yes, you can and should use it for non-admin requests too. You then register a handler for the wp_ajax_nopriv_[action] hook, instead of the normal wp_ajax_[action]. In this case you only have to follow the first lines of admin-ajax.php, since a request done by a user that is not logged in will already leave the page around line 50.

So register a function for the hook wp_ajax_nopriv_get_custom_post_data, and it will get called if you ask for admin-ajax.php with the action parameter set to get_custom_post_data. Be sure to call die() at the end of your handler yourself, otherwise the default die(-1) will be returned. And also register the logged-in version, wp_ajax_get_custom_post_data (to the same handler function, no problem), since if you are logged in to your site, you will not hit the nopriv hook.

Server-side config to Javascript

The trick to send server-side configuration data (like the admin-ajax.php url), is wp_localize_script(). You pass it an array of keys and values which will be included in the top of the page. This was probably originally created only for localizable strings, but you can use it to pass configuration data too.

wp_localize_script('storm_json_config', 'storm_config', array(
    'ajaxurl' => admin_url('admin-ajax.php'),
));

storm_json_config is the handle name (if you want to dequeue it later), storm_config is the name of the Javascript object that will contain your data. So your static Javascript file can contain a line like jQuery.post(storm_config.ajaxurl, ...).

See also bueltge’s answer to a similar question.

Static Javascript from the plugin dir

To load a static Javascript file from your own plugin dir, you use wp_enqueue_script(). That would look something like this:

wp_enqueue_script('storm_json', plugin_dir_url(__FILE__) . 'js/json.js', array('jquery'), '20101105');

Where storm_json is again a handle name, then you give the link to the file, then the dependencies (can be null), and then a version number that will be added after the request to beat browser caches on updates.

Leave a Comment