Wordpress: how to call a plugin function with an ajax call?

Posted by Bee on Stack Overflow See other posts from Stack Overflow or by Bee
Published on 2010-05-25T21:56:03Z Indexed on 2010/05/26 15:31 UTC
Read the original article Hit count: 365

I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.

I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?

(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)

I've got my code[1] set up as follows:

mu-plugins/sample.php:

<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
  class SamplePlugin {
    function SamplePlugin() {}
    function addHeaderCode() {
      echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
             '/wp-content/mu-plugins/sample/sample.css" />\n';
      wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
             '/wp-content/mu-plugins/sample/sample-ajax.js.php',
             array('jquery'), '1.0');

    }
    // adds the link to post content.
    function addLink($content = '') {
        $content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
        return $content;
    }
    function doAjax() { //
        echo "<a href='#'>AJAX!</a>";
    } 
  }
}
if (class_exists("SamplePlugin")) {
  $sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
  add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
  add_filter('the_content', array(&$sample_plugin, 'addLink'));
}

mu-plugins/sample/sample-ajax.js.php:

<?php
if (!function_exists('add_action')) {
    require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        var aref = this;
        jQuery(this).toggleClass('clicked');
        jQuery.ajax({
          url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
          success: function(value) {
            jQuery(aref).html(value);
          }
        });
    });
});

mu-plugins/sample/sample-ajax.php:

<?php
if (!function_exists('add_action')) {
  require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
  $sample_plugin->doAjax();
} else {
  echo "unset";
}
?>

[1] Note: The following tutorial got me this far, but I'm stumped at this point. http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin

© Stack Overflow or respective owner

Related posts about php

Related posts about jQuery