<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Brian Brain &#187; Code</title>
	<atom:link href="http://brian.fegter.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://brian.fegter.com</link>
	<description></description>
	<lastBuildDate>Sat, 19 Jun 2010 23:42:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>AJAX in WP Plugins Using jQuery</title>
		<link>http://brian.fegter.com/blog/wordpress-ajax-programming/</link>
		<comments>http://brian.fegter.com/blog/wordpress-ajax-programming/#comments</comments>
		<pubDate>Fri, 29 May 2009 13:09:46 +0000</pubDate>
		<dc:creator>Brian Fegter</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.fegter.com/code/130/</guid>
		<description><![CDATA[If you&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;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&#8217;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.</p>
<h2>1. Register your variables with WP</h2>
<pre name="code" class="PHP">
//Register your REQUEST variables with WP
// Sample URL: www.mydomain.com/?submit=true&#038;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;
}
</pre>
<h2>2. Assign Your Variables To An Array</h2>
<pre name="code" class="PHP">
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']
</pre>
<h2>3. Create Your jQuery Script</h2>
<p>Create a file named ajax_tutorial.js with the following code</p>
<pre name="code" class="javascript">
$(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 + "&#038;mySubmit=" + mySubmit,

	                success: function(result) {
	                      $('#ajaxResponse').append(result);
                        }
	       });
	      return false;
      });
});
</pre>
<h2>4. Include The Latest jQuery And Your Custom Script</h3>
<pre name="code" class="PHP">
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
}
</pre>
<h2>5. Add Shortcode To Insert Your Form In Pages/Posts</h2>
<pre name="code" class="PHP">

add_shortcode('my_form', 'plugin_form');

function my_form(){
	$my_form = '
<form id="myForm">
<input type="text" id="myName" name="myName">
<input type="submit" name="mySubmit" id="mySubmit" value="Submit">
	</form>
<div id="ajaxResponse"></div>

';
	if(is_single() || is_page()):
		return $my_form;
	endif;
}
//Notice the empty DIV near the bottom for your AJAX response.
}
<?php } ?>
</pre>
<h2>6. Add A Template Redirect For AJAX Requests</h2>
<p>The template redirect hook simply processes whatever function you&#8217;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.</p>
<pre name="code" class="php">
add_action('template_redirect', 'form_ajax');

function form_ajax(){
     global $myVars;
     get_my_vars();
     if($myVars['myName'] &#038;&#038; $myVars['mySubmit']):
	echo "
<p class='myFormResponse'>Thanks for visiting ".$myVars['myName'].".

";
         exit;
     endif;
     if($myVars['myName'] == null &#038;&#038; $myVars['mySubmit']):
	echo "
<p class='myFormResponse'>You didn't enter a name!

";
        exit;
     endif;
}
</pre>
<h3><a href="http://brian.fegter.com/code/wp-ajax-tutorial-demo/">Check Out The Demo Here</a></h3>
<h1><a href="http://brian.fegter.com/wp-content/uploads/2009/05/ajax_tutorial.zip">Download Source Files</a></h1>
]]></content:encoded>
			<wfw:commentRss>http://brian.fegter.com/blog/wordpress-ajax-programming/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
