Using jQuery With APE

APE + jQuery

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 :)

Share

Related posts:

  1. Using jQuery with APE – an OOP approach with the DUI
  2. Diving into APE modules and the JSF – creating topics for channels
  3. Using jQuery With APE – change the background-color with PHP
  4. EsenAPE – send and receive SMS in real time using APE, jQuery, PHP and libape_controller
  5. APE – An Introduction

39 Responses to “Using jQuery With APE”

  1. 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

    Reply

    • 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!

      Reply

      • 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 :)

        Reply

  2. 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.

    Reply

    • 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.

      Reply

  3. 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 [...]

    Reply

  4. 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?

    Reply

  5. 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 :)

    Reply

  6. 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.

    Reply

  7. 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.

    Reply

    • Keelie Jevons  on September 2nd, 2009

      Im sure you can rack that brain of yours for some good ideas!

      Reply

  8. 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.

    Reply

  9. 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.

    Reply

    • 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.

      Reply

  10. 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.

    Reply

    • 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?

      Reply

  11. 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 [...]

    Reply

  12. 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()

    Reply

  13. 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?

    Reply

  14. 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.

    Reply

  15. 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

    Reply

    • 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.

      Reply

  16. mdbollman  on March 12th, 2010

    Hey, In my experience the start function call should be changed to the following:

    ape.start({‘name’: String((new Date()).getTime()).replace(/\D/gi,”)});

    Without it, I was getting a BAD_PARAMS error.

    Reply

  17. coup  on May 1st, 2010

    Hi
    I’m new to APE as well
    and try you script ‘Colour Changer’ on my server but it wont work.
    When I run the APE TOOLS CHECK script it says everything is working.

    The Colour Changer page displays ok & the debug box says ‘APE has finished loading’ but when I try to change the colour nothing ARRHHH!!!

    any ideas?

    Reply

    • Paul Price  on May 2nd, 2010

      Hi coup, the above example was for APE 0.9 and a little change to the code is needed to make it work for APE 1.0 – I haven’t tested it with APE 1.0 but from the comment above yours (mdbollman) you should change the start function to;

      ape.start({‘name’: String((new Date()).getTime()).replace(/\D/gi,”)});

      Reply

  18. Eppi  on May 30th, 2010

    hello,

    i tried here: http://rucksack.com/media/ape/Demos/test/index.html but it doesn’t work :-(

    Reply

  19. nkos  on September 14th, 2010

    Hi
    I’m new to APE as well.
    I tested some tutorials on my APE server. woks fine !
    But now, I’d like to understand how to combine that with PHP which runs with Apache !

    Many thanks !

    Reply

  20. sdgh as  on October 19th, 2010

    /**
    * @author Paul Price
    * Who needs MooTools’ Class() method?
    */

    function colorChanger(ape, debug){
    this.initialize = function(){
    // do the following every time we get a new user
    ape.addEvent(‘multiPipeCreate’, 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!
    ape.start({‘name’: String((new Date()).getTime()).replace(“/\D/gi,”)});
    }

    this.setup = function(pipe, options){
    // add an event listener on our selectbox
    $(“select[name=selectColor]“).change(function(){
    // get the select box value
    color = $(“option:selected”, this).val();
    console.log(“here”);
    // 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)
    $(“    ” + ape.user.properties.name + ” changed the bg color to ” + message + “”).prependTo(“#debug”);
    }

    this.rawData = function(raw, pipe){
    if(debug)
    $(“    ” + raw.datas.sender.properties.name + ” changed the bg color to ” + raw.datas.msg + “”).prependTo(“#debug”);

    // set the selectboxes value to match
    $(“select[name=selectColor]“).val(raw.datas.msg);

    // set the color
    $(“body”).css(“background-color”, raw.datas.msg);
    }

    this.createUser = function(user, pipe){
    user.element = $(“” + user.properties.name + ” has joined bgColor”).prepend(“”).prependTo(“#debug”);
    }

    this.deleteUser = function(user, pipe){
    $(user.element).text(user.properties.name + ” has left bgColor”).css(“color”, “#666666″).prepend(“”);
    }
    }

    Reply

  21. walter  on October 19th, 2010

    colorChanger.js file adjusts
    /**
    * @author Paul Price
    * Who needs MooTools’ Class() method?
    */

    function colorChanger(ape, debug){
    this.initialize = function(){
    // do the following every time we get a new user
    ape.addEvent(‘multiPipeCreate’, 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!
    ape.start({‘name’: String((new Date()).getTime()).replace(“/\D/gi,”)});
    }

    this.setup = function(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)
    $(“    ” + ape.user.properties.name + ” changed the bg color to ” + message + “”).prependTo(“#debug”);
    }

    this.rawData = function(raw, pipe){

    if (debug) {
    $(“    ” + raw.data.from + ” changed the bg color to ” + raw.data.msg + “”).prependTo(“#debug”);
    }

    // set the selectboxes value to match
    $(“select[name=selectColor]“).val(raw.data.msg);

    // set the color
    $(“body”).css(“background-color”, raw.data.msg);
    }

    this.createUser = function(user, pipe){
    user.element = $(“” + user.properties.name + ” has joined bgColor”).prepend(“”).prependTo(“#debug”);
    }

    this.deleteUser = function(user, pipe){
    $(user.element).text(user.properties.name + ” has left bgColor”).css(“color”, “#666666″).prepend(“”);
    }
    }

    Reply

  22. harmo  on November 8th, 2010

    Hi all !
    I’ve got a problem with this.cmdSend,
    the param message is undefined, I don’t understand why because on pipe.send(color), color is defined very well…
    an idea ?

    Reply

  23. harmo  on November 8th, 2010

    Okay I’ve modified with this :

    this.cmdSend=function(message,pipe)
    {
    if(debug)
    $(”+ape.user.properties.name+’ a modifié la couleur en ‘+message.color+”).prependTo(“#debug_test”);
    }

    But now I’ve got another problem, this.rawData don’t work, how to debug in firebug? no functions visible in DOM, really don’t understand, please help !

    Reply

  24. mediafire  on December 3rd, 2010

    I’ve, modified this to work with APE 1.0. Hope it helps someone.

    http://mediafire.co.uk/demo/bgColours/ (demo)

    http://mediafire.co.uk/demo/bgColours.zip (source)

    Reply

    • apeNoob  on August 14th, 2011

      @mediafire – don’t know if you are looking at this anymore, but your demo isn’t working in FF or Chrome.

      Reply

  25. goreorto  on January 25th, 2011

    Does anybody know if there’s a js framework agnostic version of apeCoreSession.js?

    Reply

  26. Bangon Kali  on May 4th, 2011

    @mediafire Thanks! It works great! This is really helping. It works on my setup.

    Reply

  27. Addison Hebert  on July 27th, 2011

    Neat post! a link to this website was provided by Christian Dillstrom – you must be doing a very good job as mobile + social media marketing expert is pointing towards you.

    Reply

  28. apeNoob  on August 14th, 2011

    @mediafire – don’t know if you are looking at this anymore, but your demo isn’t working in FF or Chrome.

    Reply

  29. Doulami  on August 23rd, 2011

    hey guys ! did any one tested this with the 1.0 version ? that really start make me suck ! plzz help ! shall i reinstall the 0.9 version ?
    this is the original post : http://mail-medical.com/APE_JSF/Demos/bgkhale/

    this is media fire post : http://mail-medical.com/APE_JSF/Demos/bgColours/

    Reply


Leave a Reply