AJAXifying WordPress with jQuery: Step 1


2 Comments

This article is the first step in the five part series of getting you familiar with AJAX, WordPress and web interface development in general. Like it or not, web is here to stay as a platform and interface development will continue to play a large role as applications are ported from the traditional windows forms to a rich, interactive web interface. But enough about the development, you’re reading this to see how to throw some eyecandy on your blog, right?

Step 0: Start Planning

I know, I know – show me the demo! But first step in any successful code is putting together a plan, outlining it and thinking of how you’re going to get it done. So what are we trying to do?

We’re trying to create a Facebook-like status update for your Wordpress blog that can be easily customized and syndicated to other sites. We want to be able to edit the status directly on our WordPress web page without having to modify the template, text file or anything else. The process should be even more effortless than making a blog post.

This will require:

  • Understanding of WordPress database functions
  • Basic understanding of HTML, Javascript and WordPress templates
  • Scripting libraries to keep the code simple and clean

That is as basic as it gets..

Step 1: Obtain jQuery

I originally used Scriptaculous and Prototype for interface and effects but switched to jQuery for a number of reasons good reasons, biggest of which is the plugin structure. jQuery has a ton of third party plugins to enable everything from visual effects to behaviors and the documentation that accompanied it made it easier to visualize exactly what I wanted to accomplish. So when it came to scripting Vladville I fell back on jQuery.

First, download the jQuery and the accompanying packages:

All of these play an important part in the interface for dynamic page updates and element display. jQuery is the base Javascript library, it is what makes a lot of the stuff possible without writing a lot of code yourself. Interface Elements is a jQuery addon for interface operations, such as hiding and showing a page element. Finally, jEditable is a jQuery plugin that allows us to edit text in place. That’s about all the software that you need to download.

Step 2: Load jQuery libraries into your template

You can either edit the WordPress templates directly on the file system (/wp-content/themes/default) or through the WordPress admin interface (/wp-admin). Either way, first step is to tell your WordPress to load jQuery and associated Javascript libraries and plugins.

To do this, add the following lines to your header.php file:

<script type=”text/javascript” src=”/js/jquery.js”></script>
<script type=”text/javascript” src=”/js/interface.js”></script>
<script type=”text/javascript” src=”/js/jquery.jeditable.js”></script>

In order for everything to work properly these scripts should be in the header section (between your <head></head> tags)

Save and close.

Step 3: Create a Status Container and enable jEditable

This is the hard part, finding the spot on your blog where you’re going to put your status updates for your blog readers to see. While the esthetics can be difficult, HTML code is fairly simple:

<div class=’editable’ id=’publicstatus’>

Vlad is teaching AJAX and WP hacking.

</div>

Simple right? Now, enabling that to be editable is a little trickier but involves just a simple copy and paste. Take the Javascript code below and paste it immediately above the <div> container you just made.

<script type=”text/javascript”>
// <![CDATA[
$(document).ready(function() {
    $(“.editable”).editable(“/wp-basic.php”, {
        indicator : “<img src=’images/loading.gif’>”,
        select: ‘1’,
        loadtype: ‘GET’,
        type: ‘textarea’,
        event: ‘dblclick’,
        rows: ‘4’,
        columns: ‘150’,
        tooltip   : ‘Click to update status..’,
        submit: ‘Update Status’
        });
});
// ]]>
</script>

Let’s break down what all of this stuff means. Line #4 first defines the object that you’re affecting along with the form actions once the object is modified and form submitted. Line #5 includes a link to the image that will be displayed while your browser is waiting for the AJAX process to return a  result from /wp-basic.php, which in turn is the script that takes care of the status update on the server. The remainder of the items are fairly self-explanatory and can be tweaked to your hearts content. I’ve chosen to have my element editable when I double click on it, I’ve chosen to have the current container contents put into a <textarea> tag and automatically selected (so I can hit backspace and type in the new status), the textarea should have 4 rows and 150 columns and when I hover over my container I want it to show me a tip saying “Click here to update status..“; Finally, my submit button will say “Update Status” – like I said, easy stuff.

Tip: You can open jquery.jeditable.js file and look at the header file for syntax (usage) and available options. 

Step 4: Alter the database table

Because we have high hopes of one day allowing blog readers update their own status we’re going to take this a few floors up. We’re going to keep the “public status” content in the WordPress database, in the same table that contains our username, password, group memberships, etc.

In order to make that happen we do need to alter the wp_users table that drives our WordPress blog. SQL and database management are a little beyond the scope of this tutorial so here is a simple oneliner to create a new database field called publicstatus that we’ll keep our data in:

ALTER TABLE `wp_users` ADD `publicstatus`

VARCHAR( 256 ) NULL ;

All done. You’ve altered the wp_users table and added publicstatus field that can accept variable strings (letters, numbers, spaces, special characters, etc).

Step 5: Sit back and enjoy!

For a moment at least, bask in the glory that is a dynamic container on your blog. It doesn’t actually make any changes now but if you double click on the container it will let you play around with a form for a moment.

Now it’s time to lock things down. You want to make sure that the container can only be edited by one person – you. You don’t want to make every visitor update your page without permission, right?

By default, the first user in the WordPress deployment has a user ID of 1. We want to make WordPress only create an editable object if the user is currently logged in and that logged in user has ID 1. See how sounding it out starts to make sense and give you a picture of what you’re trying to do?

Ok, first, edit your template and remove your newly created <div> container. I know, I know, but its fulfilled its purpose. You’re going to embed some PHP into the WordPress template, to do that you have to tell the web server that the page its parsing is now going to contain an executable piece of code, which is done by inserting <? ?> tags. So here we go, from top to bottom:

<?
global $user_ID, $user_identity;
get_currentuserinfo();

We’ve defined two global variables (one for user ID, other for user name). We’ve ten called a get_currentuserinfo() procedure which will fill those variables with the data from the user that is currently logged into WordPress.

$getpublicstatusquery = “select * from wp_users where ID=’1′”;
$res = $wpdb->get_row($getpublicstatusquery);

Now we build a SQL query, to get the information from table wp_users where user’s ID is 1. This query is constructed and executed and the result is placed in the array $res. It’s important to note that wp_users is the same table we modified up top and designated it as the place to hold publicstatus information.

The big idea here is to get the information for the administrative user (ie, you) and display it on the page each time it is loaded. This makes the aspect of the status display dynamic, that every time the visitor hits your site they get the latest status update. It also means editing 0 HTML and template code every time you want to change your status!

Now, that we have the entire row of data in our $res array we need to display it properly. Let’s pay a little attention to the security. If the user currently browsing the page is not admin (not you, not ID of 1) we want to just display the container in plain text. On the other hand, if the user is currently logged in and has the ID of 1, we want to display the container that can be editable (remember how we did that by setting class=’editable’ on our chosen div). Once you’ve got the concept the code itself is simple:

if($user_ID == 1)
{
echo “

  <div class=\”editable\” id=\”publicstatus\”>

  $res->publicstatus

  </div>”;
}
else
{
  echo “<div>$res->publicstatus;</div>”;
}

So let’s review. If the user is logged in and user_ID = 1 (logged in and admin) we’re going to let them edit the container that has our status. For everyone else its just plain text telling them what our publicstatus is. Simple. Oh, one last thing, lets make sure we close down the executable block of embedded PHP:

?>

All done! Here is the entire set of code that makes this possible:

<?
global $user_ID, $user_identity;
get_currentuserinfo();

$getpublicstatusquery = “select * from wp_users where ID=’1′”;
$res = $wpdb->get_row($getpublicstatusquery);

if($user_ID == 1)
{
echo “

  <div class=\”editable\” id=\”publicstatus\”>

  $res->publicstatus  </div>”;
}
else
{
  echo “<div>$res->publicstatus;</div>”;
}

?>

There you have it. We have embedded a piece of PHP code that first gets the current users info (if any), then we run a SQL query to obtain admin/owners public status information, then we display that information. If the logged in user is also the admin, we enable editable functionality on the container. Otherwise, we only show the public status.

Keep an eye out for the next step showing you how to enable the server-side of the AJAX functionality you’re trying to enable for your blog. But you have to admit that once you see all these pieces and how they fall into place the concepts and implementation are pretty simple. As I blogged previously, this stuff is pretty trivial, you just have to want to have fun with it.

2 Responses to AJAXifying WordPress with jQuery: Step 1

  1. Pingback: Vlad Mazek - Vladville Blog » Blog Archive » AJAXifying Wordpress with jQuery: Step 1

  2. Pingback: Vlad Mazek - Vladville Blog » Blog Archive » Stalking Vlad Simplified

Leave a Reply

Your email address will not be published. Required fields are marked *