My ajax call for json data works ok like this
functions.php:
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
//get data here
}
javascript:
var ajaxurl="http://"+window.location.host+'/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
etc.
I have 2 questions.
1) Why use admin-ajax.php instead of encoding your json in a separate file like themes/example/json.php
and encode your data there?
2) How does admin-ajax.php work? I don’t understand much from that file. Does it load all the functions so you are ready to use them?
Thanks!
1) Why use admin-ajax.php
instead of encoding your json in a separate
file like themes/example/json.php
and encode your data there?
Using admin-ajax.php
means that the WordPress Core is loaded and available. WIthout that, you would need to hand load the files you need, which is a complicated process and prone to failure if you don’t know the Core very, very well. And, how good are you with Javascript security?
2) How does admin-ajax.php
work? I don’t understand much from that
file. Does it load all the functions so you are ready to use them?
- It loads the WordPress Core, meaning you can use things like
$wpdb
and $WP_Query
. That is through about line 25.
- It sends a few headers– lines 37 – 41.
- A content type header
- A header to tell browsers not to cache the results
- The interesting headers are those sent by
send_nosniff_headers()
- and
nocache_headers()
.
- The
admin_init
hook fires.
- Core actions are defined and registered dynamically– lines 46 – 73.
These won’t be registered unless they are needed– that is, unless
they are requested via $_GET
or $_POST
.
- The “heartbeat” API hook fires– line 75
- The “logged in” status of the requesting user is checked and the
appropriate administrative or “no priviledge” hook is fired.
Items #1 and #6 are the primary reasons to use the AJAX API, in my opinion. You have the WordPress Core, which you almost certainly need, and you have the same login security system as with the rest of WordPress.