Posts Tagged ‘ Ajax ’

WordPress and Twitter API, Plugin

Introduction:

You can connect to WordPress.com to follow your favorite blogs and receive notifications when new posts are published. You can even publish status updates to the WordPress.com blog of your choice. You’ll see the author’s gravatar in your timeline with excerpts and links to full posts. This way you can be notified of each new post within minutes. In some ways our service is different from Twitter. A Twitter user has a timeline of status updates which is like a blog. On WordPress.com one user can write for many blogs and one blog can have many authors. And then there are comments which can be left by anonymous users.

Twitter is an online social networking and micro-blogging tool which basically allows users to post their facebook-like “status” on their twitter page using various devices such as your cell phone, pda, or computer. Their idea revolves around the “what are you doing” concept; letting people know what you’re up to.

Since Twitter’s launch and exponential growth of other social media networks and blogging tools such as Digg, Facebook, WordPress and Blogger, there have been further Twitter developments in the form of plugins and widgets based on the Twitter API to further the cause.

The Twitter API basically allows developers to play around with Twitter’s functions and use twitter’s xml based data on custom applications.

Using the Twitter API, web developers can integrate their latest twitter into Flash, PHP, JAVA, PERL, Python, .NET, Ruby (and more ).

WordPress enables posting and reading via Twitter API

Megablogging, meet microblogging. WordPress now supports posting to and reading your WordPress blogs through any Twitter client that allows custom APIs. Following a WordPress blog on Twitter means you get snippets and links to new posts, just like you’d get any other tweet. Connecting your own WordPress blog to Twitter means you can tweet and blog simultaneously.

WordPress’ Matt Mullenweg wrote a blog post explaining how to connect Twitter and WordPress using Tweetie 2 on the iPhone. Basically, you just need to find your Twitter client’s Custom API settings (for Tweetie 2, they’re behind the little gear icon on the Add Account screen) and enter https://twitter-api.wordpress.com/ as the API root.

WordPress can also attach geotagging information from Twitter to your posts, if your client supports it. If you’ve got multiple blogs, you can go to the profile settings in your WordPress dashboard and choose which one to associate with each of your Twitter accounts. We’re used to thinking of tweeting and blogging as two separate things, but the WordPress team sees them as closely related, and API support is a pretty cool extension of that philosophy.

Using WordPress.com through the Twitter API

If you’re a software developer interested in talking to WordPress.com using the Twitter protocol–you’ve found the right page. If you’re a user, visit our Twitter API page to learn how to get real-time access to your blog subscriptions using a Twitter client that supports WordPress.com.

Twitter is a communication protocol where one can send a message without specifying a recipient. There are a lot of possibilities for Twitter as a protocol and we’re exploring this at WordPress.com.

Through the Twitter API, WordPress.com users can:

  • Read and receive new post notifications from blogs they’re subscribed to using the Blog Surfer feature
  • Post a “status update” to one of their WordPress.com blogs

On this page you’ll learn which Twitter APIs WordPress.com supports, the WordPress.com Twitter API conventions, and other resources to look at.

API Basics

The WordPress.com Twitter API supports Basic AUTH. OAuth is not supported at this time. Users should use their WordPress.com username and password.

Our end-point for the Twitter API is http://twitter-api.wordpress.com. We also support secure connections at https://twitter-api.wordpress.com

The Twitter API is a RESTful API. Requests are made over HTTP and the response is returned using the format you specify. The general format of a Twitter API request is:

http://twitter-api.wordpress.com/category/method_call.format

The available categories and methods are shown in the next section. The formats available are RSS, XML, and JSON. The WordPress.com Twitter API supports each of these.

API Methods

This list of API methods is organized similar to Twitter’s API Documentation. Missing categories are not implemented on WordPress.com.

Timeline Methods

statuses/friends_timeline

Individual blog posts on WordPress.com are status updates. With this call you will receive recent posts from the blogs the user is subscribed to.

statuses/home_timeline

Same as statuses/friends_timeline

statuses/user_timeline

Users can request their most recently blog posts using this call.

↑ Table of Contents ↑

Status Methods

statuses/update

This method is similar to its Twitter counterpart. It lets you make a blog post. You may specify a post with a title using “post title::post body”. If you specify an identifier for a blog, the post will go there. Otherwise the post goes to the default blog of the authenticated user.

↑ Table of Contents ↑

User Methods

users/show

Shows profile information about the specified blog and returns its latest post.

statuses/friends

Shows which blogs the authenticated user is subscribed to.

↑ Table of Contents ↑

Friendship Methods

friendships/create

Subscribe to a blog

friendships/destroy

Unsubscribe from a blog

friendships/exists

Check whether the current user is following the specified blog or not

friendships/show

Shows the relationship between two users

↑ Table of Contents ↑

Social Graph Methods

friends/ids

Returns the blogs the current user is subscribed to as a list of ids

↑ Table of Contents ↑

Account Methods

account/verify_credentials

Use this method to authenticate a user and test if their credentials are valid (uses BASIC AUTH)

API Fields

Each of the API methods returns different fields. Here are how these fields map onto WordPress.com.

description is the tag line description of the blog.

id is a number that identifies a blog.

name is the WordPress.com username of the author of the post.

profile_image_url is a link to the Gravatar of the post author. If no Gravatar is available the Blavatar for the blog is used instead.

screen_name is the address of the blog without the http://.

text is an excerpt or shortened snippet (up to 140 characters) of the post.

url is the URL of the blog.

Recommended Reading

Here’s a list of Twitter Plugins and links:

WordPress Twitter Plugins, Tools, Widgets

  • Wickett Twitter Widget – Display tweets from a Twitter account in the sidebar of your blog. As seen on WordPress.com. The easiest and best way to add Tweets to WordPress.
  • TweetSuite -� a Twitter-WordPress integration plugin that includes server-side TweetBacks, ReTweet-This buttons, digg-like Tweet-This Button, automatic tweeting of new posts and some widgets.
  • Tweet This – A plugin that adds a Twitter icon to every post and page, so your readers can share your blog entries on their Twitter accounts with ease.
  • TweetMeme button – easily allows your blog posts to be retweeted.
  • Simple Twitter Link – simply returns a URL, which is a link to Twitter with your post/page URL within it.
  • WP Twitip ID – Plugin adds an extra field to the comment form for user to enter their twitter username
  • Twitter Badge – Official javascript codes that display badges showing what you are posting on Twitter.
  • The Twitter Updater – a wordpress plugin that automatically sends a Twitter status update to your Twitter account when you create, publish, or edit your WordPress post. You can specify the text for the updates, and also have the option to turn the auto update on/off for the different post actions in the admin panel.
  • TwitThis is an easy way for people to send Twitter messages about your blog post or website. When visitors to your website click on the TwitThis button or link, it takes the URL of the webpage and creates a shorter URL using TinyURL. Then visitors can send this shortened URL and a description of the web page to all of their friends on Twitter.
  • Twitter Tools – This wordpress plugin creates an integration between your WordPress blog and your Twitter account. Pull your tweets into your blog and create new tweets on blog posts and from within WordPress.
  • Twitter WordPress Sidebar Widget – Customise the number of updates shown in your sidebar, individual links to each status update on Twitter, style your Twitterings using CSS, choose whether to display your Twitter name before each post and customise text between the post text and the relative time.
  • Twitter Feed – Posts your blog updates to your twitter account. Login to twitterfeed using your OpenID, provide the URL for your blog RSS feed, and how often to post to Twitter.
  • Twitt-Twoo – is a simple little plugin that will allow you to update your Twitter status right from your blog�s sidebar. It is AJAX powered and allows for quick and easy status updates.
  • Twitter Sharts – ‘Shart’ your twitter status anywhere within your wordpress blog posts or pages.

title-twitterSince Twitter launch in Year 2006, it has grown to create network what most people would call a social media revolution and it became one of the most popular social media networks, which if you’re serious about blogging, you can’t ignore.

Twitter has their own tools for displaying Twitter status on website, but they are pretty slow and not too varied or maybe you just need don’t know about such plugins, that’s why I chose to take research and create comprehensive list with Twitter related WordPress plugins and tools that will help you unite Twitter with your blog.

Twitter Tools

Twitter Tools is a plugin that creates a complete integration between your WordPress blog and your Twitter account.

Twitter Tools integrates with Twitter by giving you the following functionality:

  • Archive your Twitter tweets (downloaded every 10 minutes)
  • Create a blog post from each of your tweets
  • Create a daily or weekly digest post of your tweets
  • Create a tweet on Twitter whenever you post in your blog, with a link to the blog post
  • Post a tweet from your sidebar
  • Post a tweet from the WP Admin screens
  • Pass your tweets along to another service (via API hook).

TwitterDash

TwitterDash is a WordPress plugin that adds your friends timeline from twitter into your dashboard.

twitter-dash-wordpress-plugin

Thread Twitter

Thread Twitter fetch your tweets and display them in thread style.

Elegant Twitter Widget

A WordPress widget that displays twitter updates in yummy valid semantic XHTML code. The code is heavily commented and the output is in template functions so everything is fully customizable.

Twitt-Twoo

twitttwoo-released

Twitt-Twoo is a simple little plugin that will allow you to update your Twitter status right from your blog’s sidebar. AJAX takes cares of the hard work, and means that your page doens’t even have to reload, allowing for quick and easy status updates.

twitt-twoo-wordpress-plugin

Twitter Retweet

Twitter ReTweet provides a function that displays a ReTweet link which gives visitors the ability to ReTweet the current post; supports custom URLs (perfect for Google Analytics Campaign Tracking

Tweet Tweet

Tweet Tweet is a plugin for WordPress that polls Twitter and archives your tweets and the tweets of those you follow so those insightful conversations you have at 1am are never lost.

Twitter Widget

Adds a sidebar widget to display Twitter updates (uses the Javascript Twitter ‘badge’)

twitter-widget-wordpress-plugin

Twitter Widget Pro

A widget that properly handles twitter feeds, including @username, #hashtag, and link parsing. It supports displaying profiles images, and even lets you control whether to display the time and date of a tweet or how log ago it happened (about 5 hours ago, etc). Requires PHP5.

twitter-widget-pro-plugin

Tweet Rooster

Add the code from this website and you can enable users to tweet directly from your website or blog.

WP-Twitip-ID Plugin

Add a twitter field to your comment form (easily).

wp-twitip-id-plugin

Top Twitter Links by Twitturls

Widget that displays currently popular links that have been tweeted.

TwitterFountain

Have you ever wanted to see what was happening at that one event you could not go to? Did the plain text-backchannels somehow left you feeling disappointed?

Twitterfountain comes to your aid mashing up tweets and Flickr-images that share the same tags into a spectacular visual. Below is a sample, that you can copy and embed in your own site.

twitter-fountain-wordpress-plugin

TweetSuite

The first version of TweetSuite, a Twitter-WordPress integration plugin that includes the following features:

  • Server-side (no-JS or remote calls) TweetBacks
  • ReTweet-This buttons for each TweetBack
  • A digg-like Tweet-This Button
  • Automatic Tweeting of new posts
  • A Most-Tweeted Widget
  • A Recently-Tweeted Widget
  • My-Last-Tweets Widget
  • A My-Favorited-Tweets Widget

TweetBacks

People are talking about your posts, and not only in the comments to your post. A lot of that conversation is happening on Twitter, and now, you can take that conversation right back to your blog! This plugin imports those tweets about your posts as comments. You can display them in between the other comments on your blog, or display them separately.

Tweet Stats

This plugin adds two widgets to your site: “Most Tweeted Posts” and “Recently Tweeted Posts”. It depends on the Tweetbacks plugin by Yoast, so make sure you have that plugin installed.

tweet-stats-wordpress-plugin

Twitter Remote (beta)

This widget shows which twitter users recently visited your blog or website.

twitter-remote-wordpress-plugin

Tweet This

Adds a “Tweet This Post” link to every post and page. Shortens URLs in advance through Th8.us, eating up only 19 of 140 characters. Also included: Plurk, Yahoo Buzz, Delicious, Digg, Ping.fm, Reddit, and StumbleUpon. Includes the post’s title after the link (can be customized). If your titles are really long, they get cut off at 136 characters with “…”. Customize under Settings > Tweet This. Includes your choice of six buttons.

tweet-this-wordpress-plugin

ComenTwitter

Ultimately plugin’s goal is to give the commenter the option of sending their comment to twitter and allowing people to follow that blogs comments both in the blog and in twitter. The main reason for this is to generate a buzz and encourage commenting on peoples blogs. It will also improve the quality and value of people’s tweets revolving around blog posts.

commentwitter

TweetRoll

This widget shows your friends avatars on your blog/website and encourages more people to follow you. Colour customization and localization options available.

tweet-roll-wordpress-plugin

Twitme

This plugin allows you to automatically post your new posts on the twitter website. This is good because for example the iPod and iPhone for example have a large amount of twitter clients to pick from. Your blog posts will arrive to people while they are walking the streets.

Twitter Poster

The Twitter Poster is a plugin which allows wordpress publishers to automatically post their new posts to their Twitter account. The Twitter Poster will take the title of a new post and will subit it to the Twitter account specified in the options. It will also add the link back to the post, allowing your twitter followers to access the post details

Twitter Friends Widget

Twitter Friends is a WordPress plugin that displays your Twitter friends/ followers in your sidebar in the same way that they appear on your Twitter homepage.

twitter-friends-widget

Tweetable Twitter Plugin

Tweetable is a WordPress Plugin intended to help integrate Twitter into your blog. It can tweet your blog posts as they are published, shortening the URLs with either Tr.im or Is.gd and optionally including Google Analytics campaign tags. You can display your latest tweet(s) in your blog sidebar with a customizable widget, which can even display your follower count.

tweetable-twitter-plugin-wordpress

Twitter Feed

The application will display the latest tweet from all of the active accounts and then displays those latest tweets in date order. So the newest tweet across all of the accounts will always be shown first. It is also possible to switch between allowing/disallowing PM (Private Message) tweets to be included in the display.

twitter-feed-wordpres-plugin

Add Twitter RSS

Add Twitter RSS is a simple plugin that adds your Twitter RSS link to the header of your blog. It allows your readers to easily find your Twitter feed.

add-twitter-rss-wordpress-plugin

TwitterCounter

Allows you to integrate TwitterCounter.com badges on your blog. Additionally, you can add the Twitter Remote to your blog, which shows which twitter users recently visited your blog or website. Manually add where you would like to display the badge / remote or use the WordPress sidebar widgets instead.

@ Reply

This plugin allows you to add Twitter-like @reply links to comments. When clicked, those links insert the author name and a link to the comment you are replying to in the textarea.

reply-wordpress-plugin

Bird Feeder

Bird Feeder is a WordPress plug-in that simply tweets when you publish a post. It doesn’t do anything else, nor will it ever.

Twitter Updater

This plugin will let you automatically update your Twitter.com status with your most recent blog post. There are a few options to how the display will look when it updates.

TweetMeMe

At last I found this beautiful website which tracks the hottest links on Twitter, interesting analysis.

tweetmeme-twitter-links

Example:1 AJAX Twitter plugin for WordPress

image I have been working on a plugin which I had early posted on my personal blog. I have finished the Twitter plugin for WordPress now and ready to release for public download.

This plugin is using the Twitter API to get and post the updates. You need to have a twitter account to post updates. I am sure now almost all the bloggers use twitter.

Features

  1. You can update your twitter status from your blog
  2. You can view and display public updates on your blog
  3. You can view and display your followers updates on your blog
  4. You can view and display your followers on your blog and increase your followers
  5. Simple installation
  6. Widget Ready, just need to enable to use
  7. Can you displayed anywhere on your blog, by just adding a simple code if you do not want to display using the widget
  8. Widget fully customisable, size, font, font size, colour, number of updates, number of followers, etc
  9. Enable and disable different features
  10. Regular Updates

Installation

Installation is very simple, just upload the unzipped files to the plugins directory and activate the plugin. If you wish to display on the sidebar, just go to the widgets option as shown below

image

Settings

After activating the plugin, just go to the setting link , you will find the Kish Twitter settings link

image

Once you go to the settings, you will find all the options to customize the view of the “Kish Twitter” Widget

image

Options Explained

  • Twitter Enabled – If you want this plugin to work, you need to check this option or nothing will be shown even if the plugin is activated
  • Enable Public Updates – You can enable or disable public updates on your widget
  • Enable Followers Say – By enabling this, you can display the messages from your followers on your widget
  • Enable Rel = nofollow – You can add rel tag by enabling this
  • Enable Follow Me- You can enable this to get your followers details
  • Twitter User Name – You need to enter your username and password for this plugin to work
  • Maximum Info Lines – The maximum number of updates that you want to show on your widget. You will need to set this according to the size of the widget.
  • Maximum Users- You need to set this to display the number of followers and the number of twitters you follow
  • Font- Family – Name of the font that you want to use for this widget, example a series of fonts or font name
  • Font Size – Font size of the widget
  • Message – You can display a message on the footer of the widget
  • After you make the changes, just save the options

You can display the widget anywhere on your blog by just adding the following to your blog template

<? if (function_exists('printKishTwitter')) printKishTwitter(); ?>

If you have a questions please post it here.

UPDATE – Please check the latest version of Twitter WordPress Plugin – Kish Twitter

Download Now

Example:2

WordPress Twitter Plugin is a cool plugin that will add a beautiful Tweets widget to your wordpress blog.

You can choose to display your Twitter timeline or your friends’ timeline in the widget. You can even choose to display tweets on a keyword, depending upon your blog’s niche. For eg., if your blog is about wordpress, its themes and plugins, you can choose to display tweets on the keyword “wordpress”.

If you have a blog on iphones then you may add a WordPress Twitter widget that displays all tweets on the keyword “Iphone”!!! This makes your blog more useful to your readers, as they will be able to discover some cool tweets (links) related to your niche.

The widget is available in three different themes – blue, green and red. You can preview the widget live here on Bestindianbloggers

How to install WordPress Twitter Plugin?

  • 1. Download the plguin zip file and upload it via “Plugins” –> “Add New” –> “Upload” in wordpress. Alternatively, you can choose to search for the term “Wordpress Twitter” and install it directly from wordpress.
  • 2. Activate the plugin through the ‘Plugins’ menu in WordPress
  • 3. Go to “Settings” –> “Wordpress Twitter” and specify the Twitter user name, password, Widget’s width, height, theme (style), number of tweets to display etc. If you want to display tweets on a keyword, choose “Search” against “Timeline” and specify the keyword
  • 4. Go to Widgets and add the “Wordpress Twitter” widget to your sidebar.
  • 5. Alternatively, you can also directly add the following code to wherever you want to display the widget.
<?php $bibtweets=new bibtweets(); $bibtweets->printBox(); ?>

That’s all folks!!! Install WP Tweets and enjoy the widget.

WordPress Twitter Plugin Options:

The following image shows the various configurable options in wordpress twitter plugin.

WordPress Twitter Widget:

The following image is a red themed widget as seen on a wordpress blog. It is showing Bestindianblogs Friends Timeline.

Wordpress Twitter

WordPress Twitter Keyword Widget:

The following image is a blue themed widget as seen on a wordpress blog. It is showing tweets for the keyword “Wordpress”.

Wordpress Twitter Keyword, WordPress Tweets

WordPress Twitter Keyword Widget:

The following image is a green themed widget as seen on a wordpress blog.

Twitter for WordPress

Download WordPress Twitter Plugin from wordpress repository @ http://wordpress.org/extend/plugins/wordpress-twitter/!!!

Thanks to Ptwix for being the inspiration behind this plugin. Ptwix can be used on any PHP based site, but lacked the automation of a wordpress plugin. WordPress Twitter Plugin is easily configurable and can be used on wordpress blog.Besides, it can automatically detect the presence of Curl and use it for retrieving Tweets.If Curl is not enabled on your wordpress server, the plugin uses file_get to retrieve the tweets. We have plans to extend the capabilities of this plugin beyond what is there currently.Until then, enjoy showing beautiful WordPress Tweet widgets on your wordpress blog.

FAQs:

Can I adjust the width and height of the widget?

Yes for sure.You can easily configure the width and height via the plugin settings (Settings — >Wordpress Twitter)

Can I determine the number of tweets to show in the widget?

Yes.You can configure the number of tweets to show in the widget via the plugin settings (Settings –> WordPress Twitter).

Can I hide my “Follow me on twitter” link in the widget?

Yes. It is turned off by default.You can turn it on to let your blog readers follow you on twitter.

Can I display the widget at any place other than the sidebar?

Yes. You can do so by placing the php code (refer above) in the appropriate theme file.

What version of PHP does this plugin require?

The plugin needs PHP 5.0 and above.Most good webhosts would have already migrated to the latest version of PHP. If you don’t have PHP 5.0 or above, ask your webhost to upgrade PHP.
Version 1.4 of the plugin can work even on earlier versions of PHP.

Bookmark and Share
Advertisements

Ajax in WordPress Plugin

Introduction

Ajax (Asynchronous JavaScript And XML) is a technology that allows a web page to update some of its information without a full page reload. It is used in the Administration sections of WordPress for auto-save of post edits, adding new categories, and other purposes. Some WordPress Plugins also use AJAX for things like voting on post ratings and map refreshes.

This article, aimed at plugin developers, describes how to add Ajax to a plugin. Before reading this article, you should be familiar with the following:

* Ajax – Overview of the technology
* Writing a Plugin – How to write a plugin
* Plugin API – Filters and actions – what they are and how to use them
* How to add HTML to the appropriate WordPress page, post, or screen — for instance, if you want to add Ajax to administration screens you create, you will need to understand how to add administration menus to WordPress; if you want to add Ajax to the display of a single post, you’ll need to figure out the right filters and actions to add HTML to that spot on viewer-facing blog screens. This article does not cover these topics.
* You will also need to know something about client-side JavaScript programming, PHP programming, and HTML, in order to use Ajax in WordPress.

It turns out that the techniques for adding Ajax to a plugin are quite different, depending on whether you want the Ajax functionality to be part of the WordPress administration screens, or to appear on the viewer-facing side of WordPress. So, this article treats those two possibilities separately (after discussing common considerations).

Ajax Implementation Basics

There are three steps in an Ajax request, in general:

1. The user does something (such as clicking or dragging the mouse), and JavaScript embedded in the HTML of the web page responds by composing a “request” and sending it to a special URL on the web server. Due to security restrictions, the URL the request goes to must be on the same web site that the file containing the JavaScript came from.
2. A script or program on the web server (in WordPress, this will generally be one or more PHP functions) processes the request and sends information back to the browser.
3. The returned information is displayed using JavaScript.

Unfortunately, much of Ajax is JavaScript, which runs in the user’s web browser, and the different web browsers have not all implemented the Ajax calls and responses in the same manner. So, to make things easier, most Ajax developers choose to use a tested cross-browser library that wraps the particular browser idiosyncracies in a standard class with a documented API. In this article, we’ll use one such library, SACK (Simple Ajax Code-Kit), which is included in WordPress. The Further Reading section (see bottom of page) has several references for how to use JQuery to do AJAX — JQuery is another library included in WordPress, and the concepts are pretty much the same, but the syntax is a bit different.

So, we’ll need to make sure both the SACK library and the JavaScript functions that compose the Ajax request get included in the HTML head section of the web page where the Ajax request will take place; the sections below will show how to do that for both the administration and viewer-facing sides of WordPress.

When creating an Ajax request using the SACK library, we’ll need to supply the following information; the sections below will fill in the details of what this information should be for the administration side and the viewer-facing side:

* Request URL: The URL on the server that will process the Ajax request.
* Custom request variables: SACK allows us to set arbitrary request variables, which are sent via POST or GET to the server. Cookie information can also be sent.
* What to do if there is an error: a JavaScript function to call if there is an Ajax error.

By default, SACK assumes that the returned information from the server is JavaScript code, which is executed when it comes in (asynchronously). In the examples below, we’ll use this default behavior, so the PHP functions that are processing Ajax requests will need to compose their results into JavaScript commands. If you want to do something else with the returned information in your plugin, you might want to visit the SACK Project Home Page, download the zip file, and read the documentation, because there are definitely other possibilities.

One other detail is that the PHP function that processes the Ajax request should use the PHP die function at the end.

Ajax on the Administration Side

Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it. As mentioned above, if you want to use Ajax on the blog-viewer-facing side of WordPress, you can completely skip this section of the article.

Here’s a short example. All this will be in one file.

First, add some javascript that will trigger the AJAX request:

jQuery(document).ready(function($) {

var data = {
action: ‘my_special_action’,
whatever: 1234
};

// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert(‘Got this from the server: ‘ + response);
});
});

<?php
}

Then, set up a PHP function that will handle that request:

<?php

add_action('wp_ajax_my_special_action', 'my_action_callback');

function my_action_callback() {
global $wpdb; // this is how you get access to the database

$whatever = $_POST['whatever'];

$whatever += 10;

echo $whatever;

die();
}

That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin.
NOTE: Since Version 2.8, The javascript global variable ajaxurl can be used in case you want to seperate your javascript code from php files into javascript only files.

Ajax on the Viewer-Facing Side

As of WordPress 2.8, there is a new hook similar to 'wp_ajax_my_action':

'wp_ajax_nopriv_my_action' executes for users that are not logged in.

So, if you want it to fire for both visitors and logged-in users, you can do this:

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

Note: In WP 2.8, if a user is not logged in ('wp_ajax_nopriv_my_action'), then GET requests are ignored (and return -1). This bug was fixed in WP 2.9.
Note 2: Unlike on the admin side, the "ajaxurl" javascript variable does not get automatically defined for you. Use this PHP code to generate the URL you need to call instead:

echo admin_url('admin-ajax.php');

Ajax on the Viewer-Facing Side ( WordPress 2.6 , 2.7, 2.8 )

Implementing Ajax on the viewer-facing side in older versions of WordPress is slightly more ad-hoc than doing Ajax on the administration side and this section describes how to do it.

As an example, let's consider a plugin that allows a blog viewer to vote on or rate something (which could be a generic poll plugin, a post rating plugin, or something else like that). When the blog viewer submits a vote, we want the submission to go via Ajax, so that the viewer doesn't have to wait for the page to refresh; after the vote is registered, we'll want to update the running vote total display. For this example, we'll assume the voting and display are text-based, for simplicity, and we'll assume you've either edited the theme or used a WordPress filter or action to add HTML to the appropriate WordPress viewer-facing screen. The added HTML will look something like this:

Your vote:

(previous results output from your PHP function)

Next, we need to define the JavaScript function myplugin_cast_vote, the onClick action for the button, which will read the information the user entered, compose a request with SACK, and send it to the plugin for processing. As mentioned in the introductory section, this JavaScript function and the SACK library need to get added to the HTML head section of the web page the user is viewing. One way to do that is to add it to all viewer-facing screens using the wp_head action (you could also be a little more selective by using some of the is_xyz() Conditional Tags tests). Let’s drop this in a plugin file myplugin.php:

add_action(‘wp_head’, ‘myplugin_js_header’ );

function myplugin_js_header() // this is a PHP function
{
// use JavaScript SACK library for Ajax
wp_print_scripts( array( ‘sack’ ));

// Define custom JavaScript function
?>

//

<?php
} // end of PHP function myplugin_js_header

Next activate the plugin and reload the HTML where the form is. By looking at the HTML source you should see the SACK Javascript library being loaded:

The next step is to fill in the body of the myplugin_cast_vote JavaScript function, which is supposed to read the vote from the form field, compose an Ajax request with SACK, and send the request to the server. Given the list of generic SACK information from the introductory section, here is what we need to set up for this example:

* Request URL: We need to send our request to a plugin PHP file. This should be the main plugin PHP file. In case you want it to be a separate PHP file, bare in mind that you won’t be able to access the WordPress global variables, e.g. $wpdb, since separate files have absolutely no visibility to any part of WordPress at all.
* Custom request variables: We need to send the vote and the ID of the div where the results go to the server, and also the function that will be called to process the vote in this simple example.

Putting this together, the body of the JavaScript function becomes:

function myplugin_cast_vote( vote_field, results_div )
{
var mysack = new sack(
“/wp-admin/admin-ajax.php” );

mysack.execute = 1;
mysack.method = ‘POST’;
mysack.setVar( “action”, “my_special_action” );
mysack.setVar( “vote”, vote_field.value );
mysack.setVar( “results_div_id”, results_div );
mysack.onError = function() { alert(‘Ajax error in voting’ )};
mysack.runAJAX();

return true;

} // end of JavaScript function myplugin_cast_vote

add_action(‘wp_ajax_my_special_action’, ‘my_action_callback’);
add_action(‘wp_ajax_nopriv_my_special_action’, ‘my_action_callback’);

Take special note of the Javascript code which has an “action” variable. Also take note that it is calling the admin-ajax.php file. Then note that my_special_action is part of the first parameter in the add_action call (wp_ajax_my_special_action). These are all significant.

The final step in this example is to define my_action_callback, which is what gets called when the Ajax request gets to the server. This will need to read the posted information, verify that the vote is valid, add the vote to the database, figure out what the new running totals are, and send that back to the browser. Leaving aside all the details of processing the vote, here’s what needs to go into the file:

That’s it! You will need to add a few details, such as error checking, escaping quotes, processing the vote, and verifying that the request came from the right place, but hopefully the example above will be enough to get you started on your own viewer-side Ajax plugin.

AJAX accessibility for websites

AJAX or Asynchronous JavaScript and XML, is an innovative way of using existing technologies to create highly interactive web applications. AJAX allows portions of the page to be updated without having to refresh and reload the entire page. It can increase site performance significantly and provide cutting edge user interfaces. Unfortunately it can also be a source of concern for delivering fully accessible web sites.

What is AJAX?

AJAX is not a new technology in itself but a new approach to programming websites based on the following web standards:

  • JavaScript
  • XML
  • HTML / XHTML
  • CSS

The key word is asynchronous – AJAX applications work ‘behind the scenes’ with the web server to dynamically update the content of a web page. JavaScript plays an important role in this process, trading data with the server and manipulating the information on the page.

Accessibility benefits of AJAX

As well as significantly improving the user experience AJAX applications can also enhance accessibility. For example:

  • Auto-suggest dropdowns can help both users with reading difficulties and motor impairmentse.g. City and airport suggestions are offered as users enter text Screenshot of Kayak auto-suggest dropdown
  • Drag & drop sliders can help users with reading difficulties due to their illustrative naturee.g. A click-and-drag slider is used to filter search criteria Screenshot of Amazon drag & drop  sliders

Accessibility issues caused by AJAX

AJAX and JavaScript are usually used to update page content. When this happens screen readers respond in a variety of different ways, depending on both the screen reader and the browser:

  • Screen readers aren’t aware of the changes so will read out the unmodified version of the page. This means screen reader users don’t get the updated content of the page.
  • Screen readers are aware of the changes but will only read the modified content when they naturally reach it. This is fine unless the modified content precedes users’ current location. If this happens, they’re unlikely to hear this content.
  • Screen readers start reading the modified page but from the very top. This means that users have to essentially listen to all of the page content again. It can be difficult for these users to know which content has been updated and where in the page this content is.
  • Screen readers are automatically taken to the modified content so users instantly know that page content has been updated – this can however severely disorientate users.

Screen magnifier users might not notice changes that have occurred outside the areas they’re interacting with. They can therefore miss out on important information especially if the changed content takes place above their current location on the page.

Finally, AJAX requires JavaScript to be enabled. Although assistive technologies can now handle many uses of JavaScript they don’t all provide complete support.

Recommendations for AJAX and accessibility

There’s one key question to consider when planning the development of a website and the use of AJAX: Is there a real need to use AJAX?. If the answer is yes, then ensure the following is true to ensure AJAX accessibility is optimised:

Inform users early in the page that dynamic updates will occur
Not all users are familiar with AJAX interfaces. Let them know that changes may take place so they can expect and look for these changes. This is particularly important for screen reader and magnifier users as they may be unaware that changes have taken place.
Highlight the areas that have been updated
Using subtle changes to highlight areas that have changed, for just a short period of time, can be most helpful. It will inform users, in particular those with reading difficulties that updates have taken place.
Don’t change the focus
Do not move the focus of the page to where the change has taken place. Changing the focus can be disrupting for screen reader and magnifier users especially if there are no mechanisms to return to the previous position.
Offer the option to disable automatic updates
Allow users to manually request page updates, for example by providing links and/or form buttons to refresh the page on-demand. Screen reader and magnifier users may be unaware of on-the-page changes. It can also be difficult for users with reading difficulties to keep up with automatic updates. If possible, store users’ preferences for requesting page updates for future visits to the site.
Ensure the site works if JavaScript isn’t enabled
Build a standard application then overlay it with AJAX to improve its functionality. If JavaScript is disabled or not available then users will still be able to use the site.

In case of an advanced AJAX application, consider providing an HTML alternative. If the AJAX application is impossible to use by group of users (e.g. if it relies on the use of a mouse, such as the drag & drop sliders) then a link to an HTML alternative is a must.

Bookmark and Share