AJAX in WP Plugins Using jQuery

If you’ve ever programmed a plugin for Wordpress, you know what a hassle it is to connect to the WP database during AJAX requests. In this post, I will show you that you should NEVER touch the wp-config file EVER. Including the wp-config file in a plugin could possibly pose as a security hole. Here are a few simple steps to get you up and running with AJAX without having a college doctorate. We’re going to code a simple plugin using WP shortcode to display a simple form in a post or page that will return an AJAX response.

1. Register your variables with WP

//Register your REQUEST variables with WP
// Sample URL: www.mydomain.com/?submit=true&name=Brian

add_filter('query_vars', 'my_form_vars');

function my_form_vars($public_query_vars){
    $public_query_vars[] = 'myName';
    $public_query_vars[] = 'mySubmit';
    return $public_query_vars;
}

2. Assign Your Variables To An Array

function get_my_vars(){
    global $myVars;
    if(get_query_var('myName')):
        $myVars['myName'] = mysql_real_escape_string(get_query_var('myName'));
    endif;
    if(get_query_var('mySubmit')):
        $myVars['mySubmit'] = mysql_real_escape_string(get_query_var('mySubmit'));
    endif;
    return $myVars;
}
//Now all you have to do is call get_my_vars() in your other functions
//Your requests can be accessed by typing: $myVars['myName']

3. Create Your jQuery Script

Create a file named ajax_tutorial.js with the following code

$(document).ready(function() {

	      $('#mySubmit').click(function(){

	          var myName = $('#myName').val();
		  var mySubmit = $('#mySubmit').val();
		  $.ajax({
	                url: "http://www.yourdomain.com",
	                type: 'GET',
	                data: "myName=" + myName + "&mySubmit=" + mySubmit,

	                success: function(result) {
	                      $('#ajaxResponse').append(result);
                        }
	       });
	      return false;
      });
});

4. Include The Latest jQuery And Your Custom Script

add_action('init', 'queue_scripts');

function queue_scripts() {
    wp_enqueue_script('wp_jq_script', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
    wp_enqueue_script('wp_my_script', 'http://brian.fegter.com/js/ajax_tutorial.js');
// You can also use the included jQuery in WP
// Look up wp_enqueue_script() in the CODEX
}

5. Add Shortcode To Insert Your Form In Pages/Posts


add_shortcode('my_form', 'plugin_form');

function my_form(){
	$my_form = '
'; if(is_single() || is_page()): return $my_form; endif; } //Notice the empty DIV near the bottom for your AJAX response. }

6. Add A Template Redirect For AJAX Requests

The template redirect hook simply processes whatever function you’ve selected prior to sending the headers or rendering the template. We are going to use this to process our AJAX requests. This is the Wordpress magic that lets you access $wpdb without including wp-config.

add_action('template_redirect', 'form_ajax');

function form_ajax(){
     global $myVars;
     get_my_vars();
     if($myVars['myName'] && $myVars['mySubmit']):
	echo "

Thanks for visiting ".$myVars['myName'].". "; exit; endif; if($myVars['myName'] == null && $myVars['mySubmit']): echo "

You didn't enter a name! "; exit; endif; }

Check Out The Demo Here

Download Source Files

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

2 Responses to “AJAX in WP Plugins Using jQuery”

Leave a Reply

Spam protection by WP Captcha-Free

comments-bottom