Quick introduction
This introduction shows how to quickly get started implementing a web application using the Ajax Messaging Library.
You might also be interested in reading the installation instructions to learn how to install the server-side scripts on your server (it's simple!).
Create a Messenger
object
First instantiate a Messenger
object by calling the Messenger.Create
function. You can also use the Messenger
constructor, but the Create
function is more convenient.
var messenger = Messenger.Create(url, service, options);
url
is the base url for the service, i.e. the directory containing the message.php
script. service
is the name of the service, which can be any string up to 20 characters long, containing the characters A-Z, 0-9, - and _. options
is an object with options, most importantly dispatch
, which specifies the function to call back to when a message is received. All available options are in the documentation.
A typical instantiation might look like this:
var messenger = Messenger.Create("http://henrikfalck.com/messagelib", "chat", { dispatch: onMessageReceived });
Start messaging
The start
function connects the Messenger
object to the service and starts listening for incoming messages. So make sure you are prepared to handle messages before calling this function.
messenger.start();
Send a message
Use the send
function to send a message. A message can be any string, or object implementing the toString
function.
messenger.send(message);
Receive a message
The function you registered as the dispatch
option when creating the Messenger
object will be called when a message is received.
The arguments are senderId
, which is a numeric id of the sender of this message, guaranteed to be unique. msg
is the message string, and delay
is an integer specifying the number of seconds ago the message was sent (if you're interested in knowing this, depending on your application you might just want to ignore it).
function onMessageReceived(senderId, msg, delay) {
// handle message here
}