Posts Tagged ‘AJAX’

Your Responder

November 25th, 2008

Newmedias are about to release a new plugin to go with the ‘Your Brand’ family called Your Responder. It is an autoresponder plugin for Wordpress that integrates nicely with the Your Members plugin.

It allows your readers to sign up to email series’ on your site through an AJAX powered sidebar widget. It fully supports the CAN-SPAM Act requirements although the malicious spammers among you can turn it off on the settings page.

It supports fully configurable auto-email messges and landing pages for confirmation of signup or unsubscribe.

We will be releasing a Beta in a week or two (Early January 2009)

SACK of AJAX

September 30th, 2008

For those of you that don’t know what AJAX is, please read my simple tutorial here. For those of you that do, carry on reading…

I wanted to use some AJAX within a wordpress plugin i’m writing called Your Responder to handle a form submission and feedback without having to refresh the page.

I was reading through the Codex looking for anything AJAX related and came across a bundled script called SACK. It actually stands for Simple Ajax Code Kit and i’m happy to say it does exactly what it says on the tin. I haven’t even looked at the advanced features yet but a basic ajax request can be made in a few small lines of easy to follow code.

The full wordpress example is here but I thought I would give a explanation of my own…

The first stage is to incorporate the SACK library. Of course there is a special way to do this in wordpress but it’s very simple:

wp_print_scripts(array('sack'));

Copy that somewhere into your plugin and it does the same as putting a ‘<script src=”" />’ into the head of the html page.

Next comes the actual call:

  var mysack = new sack("www.yoursite.com/wp-content/plugins/myplugin_ajax.php");    

  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar("vote", vote_field.value);
  mysack.onError = function() { alert('Ajax error in voting'); };
  mysack.runAJAX();

  return true;

Does it look complicated? If your answer is yes then I urge you to have a look at the actual AJAX code to accomplish a POST request. I shall go through this line by line to help it make a little more sense:

The first line sets up a new variable called mysack which is actually an occurence of the mysack object. It allows you to call any function from the library and set up variables within it without interfering with any other SACK requests on the same page. The url in the call is an absolute link (I have yet to test with relative links) to the PHP script that the request will be sent to, much like the ‘<form action=”">’ tag.

Ignore the execute line. For a simple example just appreciate it has to be there. The method line is directly the same as ‘<form action=”">’ so can accept, to my knowlege,  either GET or POST.

The next line ’setVar’ you can duplicate for each field you want to send to your back end script. So if you wanted to send something that will appear to the server as $_POST['field1'], you simply write:

mysack.setVar("field1", document.getElementById("input_field_id").value);

Remember this is a JS function so where I put my document.getElement… call, you can write anything that javascript understands (although to keep it tidy, it’s probably best to sort it out earlier and store in a variable).

On error is probably best to leave empty unless you want to show a div on the screen saying something like ‘invalid request’. Remember this will be shown to your site users to an alert box probably isn’t the best approach.

Finally we fire off the request using runAJAX().

The PHP backend

At this stage your user is looking at your site and has, in some way or another, fired off an AJAX request. If the request was intentional (ie: not triggered by something passive) then they most likely expect something like a message back from the server or event to occur.

In the above example we declared a new instance of the SACK library with the url we want to send a request to (www.yoursite.com/wp-content/plugins/myplugin_ajax.php). The PHP script we need to write obviously needs to be at this location.

There are two things you really need to remember with this:

  1. AJAX requests accept anything echoed as it’s response and will throw an error if it’s not sent proper JS code.
  2. Use a PHP ‘die’ statement to send your response to the client.

All the first one means is that, when testing, a print_r($_POST); will not work properly and if you can see AJAX/JS errors (via Firefox and Firebug or similar) then you will most likely be prompted to fix your code.

The second one is simply a recommendation from the Wordpress development team which I agree with. If you concatenate your response JS code into a variable and then run a ‘die’ with your variable as the argument then it’s likely to work.

See the following example of what would be your ‘myplugin_ajax.php’ file:

<?php
if (isset($_POST['vote']) {
    //Perform some DB bits here
    $feedback = 'alert("Your vote was successfully recorded");';
    die($feedback);
}
?>

If you now understand what to do then I recommend trying it before reading the next section because it will only confuse matters if you are just getting to know either AJAX or Wordpress.

We are checking in $_POST for a variable called ‘vote’ and notice there is no ‘else’ statement. We don’t need an else unless you want to report error messages back to the server which in this case I don’t.

Wordpress doesn’t allow immediate access to any files inside it’s directory structure so things like Database access and shared function usage won’t be possible. The only way we can make this work is to incorporate the handing code into the main plugin itself. Simply add your version of this code to your main plugin PHP file which will be called from within wordpress.

This also means that your setup URL for SACK will simply be the homepage of your blog. This will work because wordpress scans it’s plugin directory when it initiates its framework looking for hooks. As long as your plugin is active it will run your logic. The die statement will also stop that instance of the script from running hence the if statement with no else.

Good luck and let me know if you need any help, spot a mistake or just want to say something :)

Simple AJAX

June 24th, 2008

I’ve been teaching myself AJAX over the last month or so. I’ve written a simple version of the ever popular Autocomplete field but for now I want to give a quick example of what AJAX is and how it can be used simply and implemented quickly.

What is AJAX?
The acronym if I remember correctly stands for Asynchronous Javascript And XML but i’m likely to be wrong :)

What you do need to know is that it uses Javascript to fire off custom requests wherever you want without having to reload the page. I have already mentionned the Autocomplete example above so I’ll use that as an example. At work we use something similar for a UK town search. A user starts to type in the name of a town and after a couple of keystrokes a list of suggestions appears.

Now for the technical bit…
In the above example, when the input field gets to a pre-determined number of characters the Javascript sends an asynchronous request to the server then does nothing. It does nothing because of course its asynchronous! The beauty of this is that the client machine doesn’t have to wait for a response so if a response comes then something will happen otherwise it fails seamlessly.

Putting this back into the example I gave, If the server returns something then the list of suggestions pops up or refreshes with the new data, otherwise it just wont do anything.

A callback function is declared and sent to the server as part of the request. If a number of conditions are met (ie: the server url is valid and it’s set up to receive such requests) then if the server echos anything it will be passed to the callback function. The callback then runs whatever code you have written and does what it wants with the returned result. This is better explained in some code so let’s see how it all works!

This script to use a remote server to echo a random number is the simplest thing i could think of:

<script>

function ajax_request() {
	var request = false;

	if (navigator.appName == "Microsoft Internet Explorer") {
		request = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		request = new XMLHttpRequest();
	}

	request.abort();
	request.open("GET", "ajax.php", true);
	request.onreadystatechange=function() {

		if(request.readyState == 4) {
			alert(request.responseText);
		}
	}
	request.send(null);
}
</script>

Ill take you through it section by section…

First we need to create an AJAX request object, this is done is every proper browser using

request = new XMLHttpRequest();

Of course Microsoft have to be different and don’t support this call (at the time of this post) so we have to put in the nasty if statement that calls this code

request = new ActiveXObject("Microsoft.XMLHTTP");

Next we actually have to set up the request, ie: tell it where to call and what callback function to run

request.open("GET", "ajax.php", true);
request.onreadystatechange=function() { }

In this example we are telling it to call ajax.php using GET (POST is also an option) and to alert the response as the callback (alert(request.responseText);).
Finally we need to fire off the request using

request.send(null);

There are a few bits i’ve missed out for the time being, namely

if(request.readyState == 4) {

}

This readyState option is checked in the callback and only does anything when it is  set to 4. This is the stage when a script actually does something. There are several other requests which i’m sure you can research but for the basic script, just leave the IF statement in. I also haven’t mentionned the XML side of things but we will leave that for another day.

The code that responds to all of this is a simple PHP script. It can simply echo out its data to be picked up by the callback as follows

<?php
echo rand(1,99);
?>

So that’s really it in terms of getting a basic example going but if you consider the possibilities of something rooted in something so simple then you will soon begin to see where you can easily place it into your script.

For example, the posting section in wordpress uses AJAX for an autosave feature in the post window. It probably has a bit of JS on a timer loop that takes the contents of the ‘Post’ box and sends it to a script which updates a DB table and then returns the flag to say whether it saved properly or not. See! easy and very functional!

Alternatively if you like the idea of AJAX but can’t be bothered to play with the proper stuff then there’s always JQuery and Scriptaculous