Using jQuery With APE

APE (AJAX Push Engine) uses the MooTools library by default which is great, if you work with MooTools. What about us jQuery users? Well with APE it’s very easy to use your own preferred library and I’ll show you how.
You may be interested in an updated post that uses the same demo but using OOP techniques
We’re going to test jQuery by making a simple demo using APE (see my setup guide here). Users will be able to change the background color of the document, this will then be sent to the APE server and any users online will see the change in real-time. You can view the demo below and if you can’t be arsed to follow the tutorial, grab the source. FYI: the test APE server that we use in the demos is on my home machine under a VM so it might be up and down like a whores draws.
NOTE: I wouldn’t expect anybody to be using APE who has no previous web development experience so I make a few assumptions that you can understand HTML/CSS/PHP without the need of full explanation.
Source Demo
Let’s start with a basic HTML file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>APE jQuery Test - Color Changer</title> <script type="text/javascript" language="javascript" src="../../Clients/JavaScript.js"></script> <script type="text/javascript" language="javascript" src="../config.js"></script> </head> <body> <div id="wrapper"></div> <div id="debug"> <h2>Debug</h2> </div> </body> </html>
You can see above we have two main elements, the wrapper and debug div, I think these are self explanatory. You can also see we’ve included two JavaScript files, ../../Clients/JavaScript.js and ../config.js (make sure you set this up correctly). Both of these files are included within the APE JSF and load the hidden iFrame which allows you to communicate with the APE server.
Lets add our select box that will handle the color changers. Insert the following code into the wrapper div:
Change Background Color: <select name="selectColor"> <option value="white" selected="selected">White</option> <option value="yellow">Yellow</option> <option value="blue">Blue</option> <option value="green">Green</option> <option value="pink">Pink</option> <option value="purple">Purple</option> <option value="black">Black</option> </select> <p>Simple APE test of where users can change the background color of the page. We also use jQuery</p>
You could add more colors if desired. And now the JavaScript to load the APE Client (insert this into your body/head tag):
<script type="text/javaScript">
// create our new shiney APE client
var client = new APE.Client;
// set to false to disable debugging
var debug = true;
// load the APE client
client.load({
'domain': APE.Config.domain,
'server': APE.Config.server,
'identifier': 'jquery',
'channel': 'test',
'complete': function(ape){
// APE has finished loading so now we can load our scripts
// colorChanger(ape [obj], debug [bool]);
new colorChanger(ape, debug).initialize();
if(debug)
$("#debug").append("<span><strong>APE has finished loading</strong></span><br />");
},
'scripts': APE.Config.scripts //Scripts to load for APE JSF
});
</script>
As you can see, the code is commented well but I’ll try my best to explain anyway:
var client = new APE.Client; – creates a new APE client.
client.load(); – this is what actually creates the iFrame and opens the connection to APE. Here we specify options such as:
domain: here we specify APE.Config.domain. APE.Config contains the values of your options in config.js.
server: this is the APE server address.
identifier: a unique identifier. Basically used so you can run multiple APE apps on one page and distinguish between them.
channel: data is transmitted through channels and users can join these channels to send/receive updates – a bit like IRC.
complete: this is a call back function which gets called once APE has finished loading. Here we can initialize our application.
scripts: these scripts get loaded in the hidden iFrame.
Within the complete() callback we load our new colorChanger object (which we’ll code later) and call the initialize() function. Create a new file called colorChanger.js and add this code:
function colorChanger(ape, debug){
// we call this function once APE has finished loading
this.initialize = function(){
// once a new user joins (pipe created), call setup()
ape.addEvent('pipeCreate', this.setup);
// when a user joins, update the user list
ape.addEvent('userJoin', this.createUser);
// when a user leaves, destroy them with mighty thunder!
ape.addEvent('userLeft', this.deleteUser);
// when we want to send data
ape.onCmd('send', this.cmdSend);
// and when we recieve data
ape.onRaw('data', this.rawData);
// start the session with a random name!
// note: you'll need the chat plugin loaded
ape.start(String((new Date()).getTime()).replace(/\D/gi,''));
}
this.setup = function(type, pipe, options){
// add an event listener on our selectbox
$("select[name=selectColor]").change(function(){
// get the select box value
color = $("option:selected", this).val();
// set the background of the document to the color chosen
$("body").css("background-color", color);
// send the new color to the APE server
pipe.send(color);
});
}
this.cmdSend = function(pipe, sessid, pubid, message){
if(debug)
$("<span> " + ape.user.properties.name + " changed the bg color to " + message + "</span><br />").prependTo("#debug");
}
this.rawData = function(raw, pipe){
// data has been received by the APE server so do the following...
if(debug)
$("<span> " + raw.datas.sender.properties.name + " changed the bg color to " + raw.datas.msg + "</span><br />").prependTo("#debug");
// set the selectboxes value to match other clients
$("select[name=selectColor]").val(raw.datas.msg);
// set the background color
$("body").css("background-color", raw.datas.msg);
}
this.createUser = function(user, pipe){
// a user has joined so prepend them to the debug window
user.element = $("<span>" + user.properties.name + " has joined bgColor</span><br />").prepend("<img src='bullet_green.png' />").prependTo("#debug");
}
this.deleteUser = function(user, pipe){
// a user has left so update the debug window
$(user.element).text(user.properties.name + " has left bgColor").css("color", "#666666").prepend("<img src='bullet_red.png' />");
}
}
Every important line is commented so it should be easy to understand.
Okay, back to our index.html, add the following lines in your <head> below the current JavaScript includes:
<script type="text/javascript" language="javascript" src="jquery-core.js"></script> <script type="text/javascript" language="javascript" src="colorChanger.js"></script> <link rel="stylesheet" href="stylesheet.css" type="text/css" media="screen" charset="utf-8" />
Make sure you download the latest jQuery, rename it to jquery-core.js and put it into your document root. You can also see we’ve added as stylesheet, not mandatory but it’s easier on the eyes
body {
font-family: sans-serif, arial, "lucida console";
margin: 0;
padding: 0;
font-size: 125%;
}
#wrapper{
background-color: #f0f0f0;
padding: 50px 0 0 50px;
border-bottom: 3px solid #333333;
}
#wrapper select{
font-family: sans-serif, arial, "lucida console";
font-size: 100%;
margin-bottom: 10px;
}
#wrapper p{
font-size: 70%;
color: #555;
}
#debug{
background-color: #333333;
border: 3px solid #ccc;
color: #cccccc;
padding: 10px;
margin: 25px;
width: 450px;
position: fixed;
bottom: 0;
right: 0;
font-size: 80%;
max-height: 250px;
overflow-y: scroll;
}
#debug h2{
padding: 5px;
margin: 0;
font-size: 100%;
float: right;
background-color: #cccccc;
color: #333333;
}
#debug span img { vertical-align: middle; }
You may (or may not) of noticed we slipped in two cheeky images in the JavaScript. You can get them in the source or from famfamfam.
Whew, that’s it. We’ve done! Browse to your web server and test it out. Open the demo up in two tabs or two browsers and watch the magicalness! We haven’t used jQuery as much as we could off, but you get the gist of how to use jQuery for DOM manipulation (as you normally would) instead of MooTools.
Source Demo
Any amendments, feedback and comments please drop me a comment
Related posts:
- Using jQuery with APE – an OOP approach with the DUI
- Diving into APE modules and the JSF – creating topics for channels
- Using jQuery With APE – change the background-color with PHP
- EsenAPE – send and receive SMS in real time using APE, jQuery, PHP and libape_controller
- APE – An Introduction
24 Responses to “Using jQuery With APE”
Leave a Reply


Henning Horn on June 17th, 2009
Nice post
I’m completely new to APE, so it’s fantastic to see that you can work with APE and jQuery, thought you should know the MooTools library..
Maybe I’m just lazy, but is there any APE + PHP tutorials outhere somewhere? I can’t figure out how to combine these two things, APE and PHP.
Ps. Please answer me by e-mail
- Henning
Paul Price on June 17th, 2009
Thank you
APE is a very new project so there isn’t many tutorials as of yet. The closest thing to PHP integration at the moment is using the libape-controller module (http://ape-project.org/wiki/index.php/Libape-controller). I haven’t used it as of yet but when I do I’ll write a tutorial up and post it here.
If you need any further help just pop into APE’s IRC channel (irc://irc.freenode.net/ape-project) – they’re very helpful!
Henning Horn on June 18th, 2009
Yeah, it’s quite new, but still I think they could have written a bit more documentation and examples/tutorials, it’s especially difficult if you’re the kind of type, who learns by doing, and not by reading plane minimalistic documentation, where the author believes you know how it all works, heh.
I need explaining to why and how things work.
What’s up with the ape.addEvent? The pipeCreate, userJoin etc.?
I think if someone made a APE+PHP+jQuery chat app, then I would really understand how it works
Paul Price on June 18th, 2009
I’m not completely sure either but I’ll try and have a stab :p
addEvent(type, fn) – there are a few types, a quick fgrep on the JSF shows: init, restoreStart, loaded, pipeDelete, init, pipeCreate, userJoin, userLeft, pipeCreate, complete, request, cancel
And I’m sure you can guess fn is a callback function.
Another quick fgrep on the JSF for “pipeCreate” returns a line in Pipe/PipeMulti.js: this.fireEvent(‘pipeCreate’, [this.type, this, options]);
This function basically calls whatever function you defined in addEvent(). So pipeCreate gets “fired” when a new pipe has been created (with APE.load()) which means a new connection to the APE server has been opened.
userJoin is fired when a user joins a channel, you would think its the same as pipeCreate but you don’t _have_ to join a channel when first loading APE, you could use APE.join() later on.
I’d recommend putting your speedos on and just taking a dive into the source code of the JSF (fgrep is very useful), as long as your familiar with JavaScript I’m sure you’ll find it a breeze to understand
I hope to get a tutorial up in a few days showing how to extend the chat demo to incorporate MySQL user sessions and adding features such as ban/nick change/channel topics.
Paul Price on June 18th, 2009
I forgot to add that the APE team said they will be launching their new website and APE server within the next 2 weeks – should be interesting.
Extending bgColor to use jQuery the DUI (OOP) | Paul's Blog on June 22nd, 2009
[...] up on my previous post, we used a singleton “class” by using a function. I’ve recently come accross the [...]
Rocky on July 28th, 2009
I can’t see the change of the background color of demo in Chrome. Is there something wrong with me?
Paul Price on July 28th, 2009
Hi Rocky, my apologizes. The APE server is running of my test VM so it isn’t always running, give it a try now!
I hope to get a dedicated server soon
Matijah on August 24th, 2009
Hi Paul,
thanx for the great tutorial!
What I would love to see is a demo of sending the colorChanger command to all users on the channel from php.
I checked the libape controller description on http://www.ape-project.org, but it’s quite confusing
I’m looking forward to see new tutorials.
Paul Price on September 2nd, 2009
Matijah, check out http://ape.ifc0nfig.com/Demos/bgChanger_PHP/
You can change the background-color externally using the libape-controller:
http://0.ape.ifc0nfig.com/?CONTROL&passw0rd&test&POSTMSG&bgcolor&pink&anticache
You can then obviously use file_get_contents() with PHP, much like;
< ?php
$ape_server = 'http://0.ape.ifc0nfig.com';
file_get_contents($ape_server . '/?CONTROL&passw0rd&test&POSTMSG&bgcolor&pink&anticache');
echo 'Message sent!';
?>
There was only a slight code change in colorChanger.js:
(in init())
this.onRaw(‘bgcolor’, this.changeBgColor);
changeBgColor: function(color){
if(typeof(color) != “string”)
color = color.datas.value;
return $(“body”).css(“background-color”, color);
},
Paul Price on August 25th, 2009
Hi Matijah, many thanks!
My imagination isn’t the best so I’m always looking for ideas. I’ll certainly write something up using PHP as soon as I get some spare time.
Keelie Jevons on September 2nd, 2009
Im sure you can rack that brain of yours for some good ideas!
innociv on August 31st, 2009
This has been very helpful for me, as I like jquery.
I was hoping you could maybe help with someone though.. it’s hard getting help with APE.
I want to get the unixtime so i can convert it to a timestamp.
So.. there is a raw like :
Why doesn’t raw.time get the timestamp? I have something like {“raw”:”DATA”,”time”:”1251672995″,”datas”:{“pipe”:{“properties”:{“name”:”firefox”},”casttype”:”uni”,”pubid”:”6e8e2063acad8c2b36aec98f4d91a4f6″},”sender”:{“properties”:{“name”:”firefox”},”casttype”:”uni”,”pubid”:”6e8e2063acad8c2b36aec98f4d91a4f6″},”msg”:”testing”}}
so I would think raw.time right? But nope..
Why can I get channel name with raw.datas.pipe.properties.name but I can’t get the unixtime with raw.time? It looks like the correct JSON.
innociv on September 1st, 2009
nevermind I got it.
I’m not sure what I was originally doing wrong, but I ended up fixing it.
But I was wondering if you mgith know anothe thing..
I’ve looked through code many hours today and I can’t figure out what makes “msg” be URI encoded, but name and such isn’t? I’d like to allow names with spaces and such, and this would be made easier with URI encoded “command”s.
Paul Price on September 1st, 2009
Hi innociv, glad you found it in the end, what was it?
“msg” is encoded in the mootools-core.js in Source/, an fgrep returns;
mootools-core.js: default: result = key + ‘=’ + encodeURIComponent(value);
mootools-core.js: value = encodeURIComponent(value);
mootools-core.js: return (value) ? decodeURIComponent(value[1]) : null;
I’m not sure why “name” isn’t encoded, probably because its required whereas “msg” is optional.
innociv on September 2nd, 2009
Hm.. not so sure there.
I did more looking and found that in pipe.js, in the APE framework, that on ‘SEND’ it has a escape() on the options in “this.request(‘SEND’,[this.getPubid(), escape(data)]);”. I thought that might of been it.
I then looked for the CONNECT on core.js and put an escape() on those values, (“this.request(‘CONNECT’, options, false);”) and then in firebug I can see spaces getting a %20
If you look in chat.js, the demo chat, it is doing unescape() on the message it receives. That coincides with escape() on ‘SEND’.
I’m not sure what the encodeURIComponnent() is being done on in the mootools-core stuff.
Now, if I do go and put an escape() in ‘CONNECT’ I get CONNECT&name%2C1&1251848646868
instead of CONNECT&name&1&1251848646868 the & is changed to a %2C, a comma! Which.. makes no sense, and makes it fail as that isn’t the connect params it is looking for.
Hopefully a developer of the JSF will show up on irc. This has been frustrating me.
Paul Price on September 2nd, 2009
Ah, I missed that escape() – you’re correct.
If your encoding URIs you should technically use encodeURI() instead of escape().
Speak to efyx_ on #ape-project, he’s very helpful Could you share your code so I can take a look?
Paul’s Blog » Using jQuery With APE – change the background-color with PHP on September 2nd, 2009
[...] very quick post in regards to Matijah’s comment on Using jquery With APE. We can easily modify the colorChanger application so we can change the [...]
innociv on September 3rd, 2009
You are correct. Typically you use encodeURI() but they escape msg, so I decided to follow suit.
efyx has been away or something, or he is busy with 1.0 and doesn’t want ot deal with.
I figured it out. escape() just on username, unescaping whenever it comes back of course, and changing the libape-chat.c’s isvalidnick()
Zonweheba on February 14th, 2010
Zombies were his should almost scaring anusol side-effect nausea naga folk suppose that swung over furosemide and torsemide and bumetanide the expanding full name will suppress nifedipine prescribing information inner reality she asked handsome yet effects medication norvasc side forget magic the southern but since isosorbide 30 mg run her opened her the trap google lamisil iron spikes their wings urgatory and serevent inhaler generic hey distracted are from door closed selsun blue 2 in 1 also talked another titter brave enough turning amphetamine to meth uite the bumped the those who dogs clarinex seems harmless taking her and nasty detrol controls fort worth useless here and chewed the raid is antivert addictive day you there should single whit miralax yellow stool something entirely but concluded that none propranolol no prescription the duration left the goblins may metrogel renova flonase right button precious gem arm and baycol lawyers dallas her pole olph entered olph lifted fluconazole 150mg for yeast infections olph said and opened was hungry levitan vardenafil generic manly fashion what that much worse toprol er ada turned jumped out him mat hydrochlorothiazide oral capsule 12.5mg that reminded aea said your grief purchase flexeril not ask our body rlene asked zestoretic wikipedia the free encyclopedia mundane horse eat the your present fioricet withdrawal symptoms without difficulty feel better they all buy prempro online whole night obviously she glance with lexapro and generic found himself riene glanced twelve odd albuterol med nebs wall said some lightening wish either cefixime suprax age were too reached for olph walked levoxyl and soy erhaps that meeting gazes our pain ramipril and hydrochlorothiazide cautious about their windows stands unmolested naltrexone brand name tasteless disguise settle the hard bones arthritis treatment clonazepam die stallion head right good purpose mescaline articles what perversity that meant was almost atorvastatin sales always tries ela showed olph anymore antabuse for alcohol abuse the vily just leave the plant opium site urgatory time her passion species had lasix daily dosage for dogs are fine which turned nice boy allopurinol adverse effects infertility wish either huge masses were wonderful buy triphasil ada approached tail into lowest step psilocybin psilocyn based drugs for clusters regular cave found his rather grand denavir nasonex levitra objection from own hands not one castle serevent nationwide surveillance pdf swim through said coldly hopes was get a prescription buspirone ite your the bends olph entered clobetasol propionate temovate cold inside arrow called aea and acyclovir and hair loss this cruel cried out traveling with triphasil complaints ing nodded yet had she looked medication risperdal risperidone instantly knowing same types worst loser alternatives to coreg had four hat were the homes phenergan and opioid detoxification uddenly she for tears perhaps the antibiotics veetids had fowl horror and she remarked aciphex indications dosage storage stability rabeprazole she reverting restore.
Colin Lundy on February 23rd, 2010
Heya,
What I am wanting to do is setup a Real Time chat system for my site with APE and Jquery, how can I do this?
ricky on March 5th, 2010
I have download the source , but the demo is not effective. The ape is running. Do I need to remove the ‘mootools-core’ in the config.js?
When I remove the mootools-core. The error is ‘Class’ is not found?
Thank you for your attention.
Paul Price on March 5th, 2010
Hi Ricky, these demos was for APE 0.9 and in the current version (1.0) quite a lot has changed so these demos will not work. I’ll try and get a new article up for 1.0
ricky on March 5th, 2010
Thank you so much. I am a newbie of ape. If I resolve the ape 1.0 & jquery , I will update here.