Why use admin-ajax.php and how does it work?

The question:

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!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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?

  1. It loads the WordPress Core, meaning you can use things like $wpdb
    and $WP_Query. That is through about line 25.
  2. It sends a few headers– lines 37 – 41.
    1. A content type header
    2. A header to tell browsers not to cache the results
    3. The interesting headers are those sent by send_nosniff_headers()
    4. and nocache_headers().
  3. The admin_init hook fires.
  4. 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.
  5. The “heartbeat” API hook fires– line 75
  6. 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.

Method 2

admin-ajax.php is part of the WordPress AJAX API, and yes, it does handle requests from both backend and front.
here what i figure-out for your question that is:

2) How does admin-ajax.php work?

for the logic you can visit here.

This assumes you already know how to enqueue JavaScript, etc.

JavaScript Piece:

jQuery(document).ready(function($) {

    // We'll pass this variable to the PHP function example_ajax_request
    var fruit = 'Banana';

    // This does the ajax request
    $.ajax({
        url: ajaxurl,
        data: {
            'action':'example_ajax_request',
            'fruit' : fruit
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });   

});

PHP Piece:

function example_ajax_request() {

    // The $_REQUEST contains all the data sent via ajax 
    if ( isset($_REQUEST) ) {

        $fruit = $_REQUEST['fruit'];

        // Let's take the data that was sent and do something with it
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }

        // Now we'll return it to the javascript function
        // Anything outputted will be returned in the response
        echo $fruit;

        // If you're debugging, it might be useful to see what was sent in the $_REQUEST
        // print_r($_REQUEST);

    }

    // Always die in functions echoing ajax content
   die();
}

add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

// If you wanted to also use the function for non-logged in users (in a theme for example)
 add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

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?

may be this helpful.admin-ajax.php vs Custom Page Template for Ajax Requests


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment