[wp-hackers] Documenting AJAX for plugins in 2.1

Steve Lewis stevelle at gmail.com
Thu Dec 21 21:46:01 GMT 2006


I've been pouring over the source in HEAD, deciphering more about the
filter/action invocation system so I can figure out how to register an
ajax-target function with the $wp_filter global.  I wanted to validate my
thougnts in an effort to help develop the documentation for this.  I am
asking the wp-hackers community to review this for accuracy and fitness
before I take it to codex.


begin by defining the ajax function:
  function pluginajaxfunction()
  {
    // build the response
  }

then register the ajax function:
  add_action(wp_ajax_uniquepluginajaxtag, pluginajaxfunction, priority,
parameters);

    Note: You may choose your own "uniquepluginajaxtag" but care should be
taken, just as with naming plugin functions, toward preventing name
collisions [link to Writing_a_Plugin#Avoiding_Function_Name_Collisions].
When registering the function, prepend "wp_ajax_" to the tag.

Your AJAX call should request the url:

  [...]/wp-admin/admin-ajax.php

  via POST (not GET) with the parameters
      action=wp_ajax_uniquepluginajaxtag
      cookie= document.cookie

    Note: You must prepend "wp_ajax_" to your "uniquepluginajaxtag" in the
action parameter when invoking it, as well.
    Note: AJAX scripts must pass cookie=document.cookie to identify the
authenticated user session, as this invocation method is meant for the
administrative area.

Example of the server-side:

// within the scope of your plugin
function example_ajaxupdate()
{
    echo "<h1>Success!</h1>";
}

add_action('wp_ajax_example_update', 'example_update');


Example of the client-side:

[TBD]

(asside: hacking a bit to get around the check_ajax_referer() call and
allowing GET instead of POST, I was able to get this to work in 5 minutes)
http://localhost/wp-admin/admin-ajax.php?action=wp_ajax_example_update

Question:
prototype.js is *not* automatically included in all pages within the admin
area in 2.1.  What is the prefered means of adding it to a document head, or
should we resign ourselves to adding it through a script tag in the document
body when necessary?

regards,
-- 
SteveL


More information about the wp-hackers mailing list