2

I'm trying to understand why using admin-ajax.php is advantageous over doing something like this:

add_action ('wp_loaded', 'my_ajax');
function my_ajax() {
   // Do Ajax, Check $_POST
   die();
}

With the JQuery ajax just pointing to the blog's index.

admin-ajax.php seems rather convoluted to do something simple, with having to register scripts and add hooks and set up a js variable url to point to the admin-ajax.php and then with wp_ajax_nopriv_ vs wp_ajax_. Not to mention it's kind of weird that back end is being mixed with the front end. I'm pretty sure there's an analogy there.

So why use it? Does admin-ajax.php have less overhead? Is it purely a standards thing? Is there something magical about it? What do you miss out by not using it?

1
  • Have you read the actual admin-ajax.php file? There's nothing stopping you from doing it your way, but using admin-ajax.php offers some functionality that developers may want to take advantage of without having to recreate for each AJAX function.
    – cfx
    Jul 27, 2014 at 17:27

1 Answer 1

4

First, like many things in WordPress, it's not like someone decided "let's make this neat and convenient". It was more like someone slapped it together for something, then it got used more in admin, then it got used a lot in admin, then it became kind of practice to use it for non-admin as well. Or something along these lines.

Second, it's not as much what it does, as knowing that it always does same thing. You have no idea what request to the arbitrary part of front end is doing. What if analytics plugin is running, counting it as page view? What if there is complex redirect logic that handles seasonal URLs? What if, what if...

Ajax endpoint is meant for ajax:

  • it declares DOING_AJAX constant for context, many things look for it to skip doing whatever they are doing
  • it sets up HTTP headers and stuff
  • it gives you basic code organization convention, including user/anonymous distinction
1
  • Awesome! Thank you. That was just the answer I was looking for. I'll go the WP route.
    – true
    Jul 27, 2014 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.