Teach Yourself D3.js

D3 is a JavaScript framework used for data visualization.
Learning how to work with D3.js is very easy. If you begin with the basics, you’ll see how easy it is to use D3, because:

  • the DOM function names are much shorter than those in the legacy DOM library.
  • the same functions are used for both setting and getting values.
  • setters return a value, so you can keep working with the same element without repeating its name.

If you already know some framework, you probably feel that there’s nothing new under the sun, which is good because it makes learning the new stuff easier.

So, What’s New?

In D3, you can:
* add and remove SVG and HTML elements using the setters and getter.
* set and get the element’s properties, attributes, styles, text and… data

Getting Started

First, download the framework from http://d3js.org
After you include it in your script, you can use selections, that is wrappers for elements.
To get a selection, use one of the functions:

  • d3.select(selector) – to select the first element matching selector.
  • d3.selectAll(selector) – to select the all elements matching selector.

Like the d3 object, selections has their select and selectAll methods to select descendant.

If selection is a selection, it’s easy to understand what selection.text(), selection.attribute(), selection.style(), selection.insert(), and selection.append() do. But, what does selection.data() do?

Data And Update Selection

The selection’s method data() helps you use the HTML DOM as a database.
selection.data() returns an array of all data that belongs to the elements of the selectionץ The data is held in the property __data__ of the element.
selection.data(arr, func) – defines an update selection and distribute the elements of array arr to the elements of selection.
func(d,i)is a function that:

  • receives d an element of arr and its index i.
  • returns a record key.

If func is not passed, the key is the element’s index.

A recommended way to create an update selection is:
var updSelection = selection1.selectAll(selector).data(arr)

Now, updSelection is a selection of existing elements whose data has been changed.
In addition, updSelection has to methods:

  • updSelection.enter() – returns place holders for elements to be created under selection1.
  • updSelection.exit()– returns elements that have lost their data, and are usually to be removed.

Using the data

The methods attr, style, property, text and data can accept a function as a value to set. The function will be called for each element of the selection’s data. And its arguments will be the array element and its index.

Now, let us see it in an example.
The following code arranges data in a donut layout::

<!DOCTYPE html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing Pie Chart</title>
<script type="text/javascript" src="d3.min.js"></script>

<style type="text/css">
.slice text {
font-size: 12pt;
font-family: Arial;
<script type="text/javascript">
var width = 300, 
    height = 300, 
    radius = 100, 
    color = d3.scale.category20c(); //builtin range of colors

// Step 1: creating a container for the donut chart, and attach raw data to it.
var vis = d3.select("body")
            .append("svg")     //create the SVG element inside the <body>
            .datum([{"label":"first", "value":20},
                    {"label":"second", "value":10},
                    {"label":"third", "value":30},
                    {"label":"fourth", "value":25}])       
            .attr({"width": width, "height": height})  
            .attr("transform", "translate(" + radius + "," + radius + ")") //move the center of the pie chart from 0, 0 to r, r

// Step two: defining the accessors of the layour function. 
//           The function 'pie' will use the 'value' accessor to compute the arc's length.
var pie = d3.layout.pie() 
            .value(function(d) { return d.value; })
            .sort(function(a,b){return a.label<b.label?-1:a.label==b.label?0:1;});

// Step 3: Create the update selection. 
var updateSelection = vis.selectAll("g") 
                         .data(pie);    // This will use the function 'pie' to create arc data from the row data attached to the visualisation element.

// Step 4: Using the data in the update selection to create shape elements.
var arc = d3.svg.arc() 
            .innerRadius(radius / 2)
               .style("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
               .attr("d", arc);                                     // Create the arc from the arc data attached to each element.

                     function(d) { 
                       return "translate(" + arc.centroid(d) + ")"; 
               .attr("text-anchor", "middle")                  
               .text(function(d, i) { return d.data.label; }); 


And following is the chart:
enter image description here

For more funcions, see the API Reference.


Static Variables in JavaScript

How do you declare a static variable in a JavaScript function?
Not with the word “static“.
In JavaScript “function” is a variable type similar to “object“.
The difference is that the reference to a function inside itself is not this but arguments.callee.
An example of using arguments.callee is the following function that returns itself:

function func(){
    return arguments.callee;

Adding Static Variables

You can add arguments to arguments.callee. To initialize it the first time, check first if it is not defined. For example:

if (typeof(arguments.callee.myStaticVar)!="undefined")

Following is an example function in [rhino(http://rhino.org) JavaScript(run from the command line):

    function _example(){
        var thisFunction = arguments.callee;
        if (!thisFunction.static){
        print("This function has been called: " + thisFunction.static + " times");

In this example, you can change the static variable’s value without calling the function using _example.static = "some value";.

To prevent this, encapsulate your function using a function called once, for example:

    function _example(){
        var thisFunction = arguments.callee;
        if (!thisFunction.static){
        print("This function has been called: " + thisFunction.static + " times");


Now, each time example() is called, it will increment the variablestatic, but the variable cannot be incremented without calling example because _example is private.

Written with StackEdit.

HTML5 Canvases & Transforms

Browsers supporting HTML5 allow you to draw on the browser’s screen without preparing an image file before. Drawing on a canvas is done using the wonderful Javascript language. If you want to draw a 2-dimensional image on canvas element ‘cnv’, get the drawing context using:

var ctx = cnv.getContext("2d")

And use that context to draw everything using the standard functions:

moveTo, lineTo, arc, fillRect, etc.

Learn more about drawing here.

You can use the functions to create more complicated shapes easily thanks to transform functions:

Transformations: Linear Algebra Made Easy

The origin(0,0) of the canvas is defined to be the top-left pixel of the canvas element. And the coordinates are given in number of pixels. This can change by using transforms.

The transformation functions are:

  • scale(x,y): this will make every shape x times wider and y time taller.
  • translate(x,y): now coordinate (0,0) will be shifted x units to the right, and y units down.
  • rotate(angle): will rotete the axes by given angle in radians.
  • transform(a,b,c,d,e,f): If you want to use a transformation matrix
  • setTransfrom(a,b,c,d,e,f): reset all transform, and perform transform(a,b,c,d,e,f).

a,b,c,d,e,f are values in the matrix:

Transform Matrix
The values a,b,c,d are used for rotating and scaling. e,f for translating.

Other useful methods of the context are:

  • ctx.save() – to save current transform in a stack (Last In First Out).
  • ctx.restore() – to retrieve the trnasform from the top of the stack.

An Example – The Koch Snowflake

The algorithm for drawing the Koch Snowflake can be found in the post Drawing The Koch Snowflake Fractal With GIMP.

Here’s an example in Javascript:

        function drawSide(ctx, len){
          if (len > 1) {
            var thirdOfLen = len / 3.;

            var rotationAngles = [0, -Math.PI / 3, 2 * Math.PI / 3., -Math.PI / 3];

              if (val != 0){
                ctx.translate(thirdOfLen, 0);
              drawSide(ctx, thirdOfLen);

          } else {

        ctx.translate(startX, startY);
        for (i=0; i<3; i++){
          drawSide(ctx, sideLength);

Warning: using ctx.stroke() after every little line you draw might make your code inefficient, and slow down your browser.

Transformation functions are also part of the Processing language.

Processing: Sketches – Your Multi-Programs

When you start Processing, you get an editor with a sketch name. You will probably want another name for your program, a name that means something. So, to change the name generated by the tool, you choose file->save as. Choose a name, and the tool will create a folder with that name, and a file named <name>.pde.

When you run your sketch – by clicking the button with the triange or selecting ‘sketch->Run …’ (Run In Browser, Run on Device, Run In Emulator, Run, etc. Depending on the mode) – Processing will parse the ‘.pde’ files and the program used for running will create an instance each time you run it.

Setup and Draw

If you want have things to do upon initiation of your program, define a function named ‘void setup()‘.  To size your canvas call size(width, height). It is recommended to use ‘size’ only once in the setup function, and the whole sketch. A setup command is not called in run time. It is recommended to set the frame rate inside the setup function by calling ‘frameRate(rate)‘, the rate is the number of time the function ‘draw()‘ is supposed to be call every second. If you want an action to take place each time a frame changes, write a “draw” function in one of  your ‘.pde’ files.

More Than Just Pure Processing

Sometimes, pure Processing is not enough for your application. For example, sound functions do not exist in pure Processing. There are libraries, such as Maxim,  that extend Processing.

Another reason to use more than pure Processing is will to use native widgets (HTML elements, Android Menus & Dialogs, etc.). In pure Processing, you would have to draw the button and detect in the ‘mouseClicked‘ function if the mouse pointer is inside the button.

Here’s a little video example of using the android menu to change the number of polygon sides:

In addition, I’ve created a Javascript module, and added buttons to the HTML page displayed when running in Javascript mode.

The following sections will explain how to do it.

 The Common Part: Just Draw a Polygon

The sommon part that draws the polygon is found in a ‘.pde’ file in the ‘polygon’ sketch directory. The function ‘draw’ detects changes in the global variable n, the number of sides.

The functions ‘translate’ and ‘rotate’ make drawing rotated shapes and lines easier.

In addition, the module contains a call to a function named ‘alert’. This function exists in Javascript, so I’ve made another in the Android module using Toasts.

Following is the code:

// This program draws a regular polygon with n sides.
int n;
float halfVertexAngle; // Will be used for moving from the center
                      // of the sreen to a vertex of the polygon.
float rotateAngle;     

void set_no_of_sides(int inputN){
  if (inputN < 3){
    alert("Polygons must have at least 3 sides. Try again");
  halfVertexAngle = radians(180) / n; 
  rotateAngle = radians(360./n);

void setup(){

void draw(){

  // Center coordinates of the screen and circumbscribed circle.

  int centerX = width / 2;
  int centerY = height / 2;
  float radius = min(width / 2, height/2);  // The radius of the circumscribed circle.
  // Use the cosine theorem to find the length of a side. 
  float side = sqrt(2 * radius * radius * (1 - cos(2 * halfVertexAngle)));
  translate(centerX, centerY);  // Move the origin of axes to the center of the screen.
  rotate (-halfVertexAngle);    // Rotate the axes to find the first vertex without
                                // dealing with trigonometry.
  translate(0, radius);
  rotate(halfVertexAngle);      // Rotate back to make the first side horizontal.
  for (int i=0; i<n; i ++){

The Android Module

I found that in my Linux system Android files are created in the ‘/tmp’ directory. Processing Android mode generates an extension of the class PApplet from your pde files. The good news is that PApplet extends the android Activity class, which makes adding event handlers easy.

Additional functions to a class extending PApplet should be written in a separate pde file. Following is the extension’s code:

import android.os.Bundle;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import android.app.AlertDialog;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.content.DialogInterface;

AlertDialog.Builder alertDialog=null;

public void alert(String text){
  Toast toast=Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);

public void onCreate(Bundle savedInstanceState){

 public boolean onCreateOptionsMenu (Menu menu){
   super.onCreateOptionsMenu (menu);
   menu.add(Menu.NONE, 37, Menu.NONE, "Change Number of sides");
   return true;
 private void createAlertDialog(){
     // Create a dialog to change the number of polygon sides.
  alertDialog = new AlertDialog.Builder(this);
  alertDialog.setTitle("Polygon Settings");
  alertDialog.setMessage("Enter number of polygon sides:");
  final EditText input = new EditText(polygon.this);
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
    new DialogInterface.OnClickListener(){
      public void onClick(DialogInterface dialog, int which){
        int numberParsed;
        try {
          numberParsed = Integer.parseInt(input.getText().toString());
        } catch (NumberFormatException ex){
          alert("Not an integer. Try again.");

    new DialogInterface.OnClickListener(){
      public void onClick(DialogInterface dialog, int which){

 public boolean onMenuItemSelected(int featureId, MenuItem menuitem){
   super.onMenuItemSelected(featureId, menuitem);
   switch (menuitem.getItemId()){
     case 37:
   return true;


  • If you have an Android module, but you want to run in another mode, renaming the Android mode’s pde file with a ‘.bak’ extension is recommended.
  • If the Android module is not installed, you can install it from a Processing editor window, by selecting <mode button> -> Add more…

Javascript Functions & Changes to the HTML Page

You can change the appearance of your output HTML page by editing the file <sketch-name>/template/template.html . If the file and directory do not exist yet, you can create them by choosing “Javascript->Start Custom Template”. If they do exist use “Javascript-.Show Custom Template”.

For example, I’ve added a button in the HTML template as follows:

<input type="button" value="Change Number of Sides" onclick="get_no_of_sides(this);" />

In addition, I’ve added an ‘onload’ event to change the size of the canvas after the polygon object is created. This function works fine in my favorite browser, Firefox. Fortunately, from ‘.js’ module one can call ‘size’ to resize the canvas:

    <body onload="new_size(640, 480);">

From this page you can learn about accessing Processing from Javascript.

Following is my javascript code defined in ‘js_functions.js’:

function new_size(w, h){
  var divElement=document.getElementById('content');
  divElement.addEventListener("DOMSubtreeModified", function(event, func){
    if (window.Processing.getInstanceById("polygon")){
      divElement.removeEventListener("DOMSubtreeModified", arguments.callee);
      divElement.style.width = w + "px";

function get_no_of_sides(obj){

  var k=prompt("How many sides?");
  var num=Number(k);
  if (isNaN(num) || num != parseInt(k)){
    alert("Please type an integer");


Now, when you run your application, the product will be found in ‘<sketch-name>/web-export’.
Learn more about Javascript modules here.

The Processing Language…

Processing is a programming language used mainly for animations and graphical applications. If your program is written in pure Processing, the same code can be run in many tools that use their own language: Windows with Java applets, HTML pages with Javascript, Android applications, etc. Running an application  is done by choosing a mode from the Processing GUI tool.

Here’s a screen shot of a Processing Window containing a program to draw a regular polygon:

Drawing a Polygon

Now, to run the program , push the “Play” button, or choose Sketch->Run, and you’ll see the result:

The polygon in a Java applet.

Now, to run this on Android, I commented out the call to the function ‘size’, following is the result on in an emulator window:

Polygon in Android

You can add to your programs command specific to the mode in which you run. For example you can  add an ‘alert’ command in Javascript mode. Better do it in separate files.

You can download Processing here.

To learn more about pure Processing function go to the function reference.


Adding Java Classes to Rhino JavaScript

In the post LibreOffice Javascript, I wrote about Rhino Javascript, which is a Javascript interpreter written in Java. This tool has been developed by Mozilla. With this tool you can instantiate Java classes and to access them via Javascript commands ‘importClass’ and ‘importPackage’.

How to ass classes and packages you can load ?

This is not too hard: the ‘rhino’ command is a shell script. In linux, you can find it using the command:

which rhino

You’ll see the response:


Then you can look into the file with a text editor or the ‘more’ command, and see that this is a script that performs a Java class. Jar files and classes that a Java programs uses are found in the environment variable ‘CLASSPATH” or after the directive ‘-classpath’. In this script you’ll find that the class path the content of the variable ‘JAVA_CLASSPATH’.

I decided to add the ‘Tidy’ package. In my computer the path of this package is ‘/usr/share/maven-repo/net/sf/jtidy/jtidy/debian/jtidy-debian.jar’, so the script looks like:


export LD_LIBRARY_PATH=/home/amity/myWs
## Remove bootclasspath overriding for OpenJDK since
## it now use a mangled version of Rhino (in sun.org.mozilla.rhino package)
## References:
## <https://bugs.launchpad.net/ubuntu/+source/openjdk-6/+bug/255149&gt;
## <http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=179&gt;
## <http://www.openoffice.org/issues/show_bug.cgi?id=91641&gt;


BTW, in Window, environment variables are enclosed by ‘%’ signes. For example: ‘%JAVA_CLASSPATH%’.

How To Develop Firefox Extensions – Files And Directories (Actually Coding It)

In the previous post, How To Develop Firefox Extensions – Intro, we discussed the Chrome document’s DOM. In this post, we’ll learn how to create an add-on that can be installed.  In this post, we’ll learn how to access the Chrome document’s nodes, and to organize an XPI (Cross Platform Installer) file.

XPI files are ZIP files

A file having an ‘.xpi’ suffix, is a compressed file in ‘.zip’ format. If we use Firefox as the opening program for those files, it will install an extension. We can refer to a zipped file as a root directory, containing files and sub-directories.

Following is a recommended directory structure:

  • /
    • install.rdf
    • chrome.manifest
    • content/
      • <filename>.xul
      • <filename>.js
    • locale/
      • <language code>/
        • <filename>.dtd
      • <language code>/
        • <filename>.dtd
      • .
      • .
      • .
    • skin/
      • <filename>.css

The XUL File

The XUL file is located in the content directory. XUL is an acronym for *XML User-interface Language’. The XUL file is a data file that makes the development of Mozilla extensions easier. The following example is an Overlay XUL file, i.e. an XUL used for adding a component to the browser’s Chrome, the great UI container.

<?xml version="1.0"?>

<overlay id="imageinnewtabextensionOverlay"

 <script src="imageinnewtab_extension.js">

    <menupopup id="contentAreaContextMenu"  >
        <menuitem id="context-imageinnewtab"


This overlay contains the required data for adding an “Open Image In New Tab” option to the context-menu that pops up when you right-click in the HTML document area. This file contains a link to a script and instructions to add a new menu item to the popup menu with the unique id ‘contentAreaContextMenu’.

Note that the value of the label attributes begins with an ampersand(‘&’) and ends with a seni-colons; this means that the value is variable. The actual value is translated according to the definitions found in the DTD file specified in the ‘!DOCTYPE’ tag.

The ‘oncommand’ attribute defines how Firefox should response to command events, i.e. the function called when the menu item is selected either by a mouse click or by a keyboard shortcut.

Learn more about XUL here.

The Javascript file

In this example, ‘content/imageinnewtab_extension.js’, the Javascript file, defines an object that response to the ‘command’ event. The object is initialized as a response to the “load” event, i.e. after the UI components has completed loading. When the Chrome document has completed loading, the new menu item is defined. The ‘init’ member is a function that defines what callback function to call when the context menu pops up.

Following is the code:

if ("undefined" == typeof(ImageInNewTab)) {
  var ImageInNewTab = {};

ImageInNewTab.BrowserOverlay = {
    hideIfNoImage: function(event){
      var element=document.popupNode;
      var whatWasClicked = document.getElementById("context-imageinnewtab");
      whatWasClicked.hidden = !(element instanceof Components.interfaces.nsIImageLoadingContent &&

    init: function (event){
        var contextMenu = document.getElementById("contentAreaContextMenu");
        contextMenu.addEventListener("popupshowing", ImageInNewTab.BrowserOverlay.hideIfNoImage, false);

    openInNewTab: function (event){



The Install RDF file

The ‘install.rdf’ file includes information for the browser. The information includes information shown to the installing end-uder, and for the browser to know if the extension supports the current browser version.

Following is an example:

<?xml version="1.0"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
    <Description about="urn:mozilla:install-manifest">
        <em:name>Image in New Tab</em:name>
        <em:description>Add a new Menu Item in the context menu to view an image in a new tab.</em:description>
        <em:creator>Amit Yaron</em:creator>
        <em:type>2</em:type> <!-- type=extension --> 

           <!-- Firefox -->
                <!-- Since Firefox's numbering scheme is unpredictable, users
                are encouraged to edit this field to the current max value.

Note: don’t change the ’em:id’ tag value.

Learn more about the install.rdf here.

The Chrome Manifest

The ‘chrrome.manifest’ file is a simple text files that contains instructions on how to access Chrome URL addresses (beginning with ‘chrome://’.

Following is an example manifest:

content imageinnewtab_extension content/
skin imageinnewtab_extension classic/1.0 skin/
locale imageinnewtab_extension en-US locale/en-US/
locale imageinnewtab_extension he-IL locale/he-IL/

overlay chrome://browser/content/browser.xul chrome://imageinnewtab_extension/content/imageinnewtab_extension_overlay.xul
  • The ‘content ‘ instruction tells Firefox where to find ‘chrome://imageinnewtab_extension/content’, where the XUL and code are found.
  • The ‘skin ‘ instruction tells Firefox where to find ‘chrome://imageinnewtab_extension/skin’, where the CSS files are found.
  • The ‘locale ‘ instruction tells Firefox where to find ‘chrome://imageinnewtab_extension/locale’ according to the ‘LANG’ environment variable, This is where the DTD file, used for label translation, is found.
  • The ‘overlay’ instruction tells Firefox the role of the overlay XUL file, which extends the great UI container.

Learn more about the manifest here.

The Example Add-on

The example add-on, that opens an image in a new tab, can be downloaded here.

How To Develop a Firefox Extension – Intro

Firefox users can add functionality to their browser by installing an add-on.  To install an add-n click on Tools->Add-ons.

Add On

You can then search for your requested add-on: add-on to download movies from a site, to share a page in Facebook, to add a Delicious bookmark, etc. Another useful add-on is DOM Inspector, which allows you to locate and modify document elements. Firefox add-ons are written in Javascript and access document elements, just like Javascript scripts within HTML documents, except that the document an add-on accesses is named Chrome Document.

Accessing the Chrome Document

The Chrome document contains more than just the “window” element, accessed from a web page using Javascript. Chrome also contains menus, toolbars and other widgets. Let’s make changing one of the Chrome document’s elements your first step in add-on development. If you don’t have DOM Inspector installed in your browser, you can get it here. Now, you can use it to play around a little bit. For example, let’s change the ‘Tools’ menu’s name to ‘Fools’.

To do so, perform the following steps:

  1. Tools->Web Developer->DOM Inspector:
  2. In the DOM Inspector menu bar, choose: File->Inspect Chrome Document->(tab name)
  3. In the DOM Inspector Window, click the magnifying-glass icon.
  4. In the browser’s window click ‘Tools’ menu
    IMPORTANT! This will NOT work if the “Global Menu BAR Integration” add-on is enabled!!!
  5. Open the DOM Inspector window.
    The ‘tools-menu’ node will appear on the right-hand part of the window.
    Now, you can see that the value of the node’s “label” attribute is “Tools”
  6. Right click the “Label” attribute, then left-click “Edit”.
  7. In the “Edit Attributes” window opened change the Node Value and click “OK”.
  8. Nice work!!!

Congratulations! Now you know how to access chrome elements and modify them. This will help you later when you learn how to do it in Javascript.

Learn more about add-on development here.

Asynchronous Operations In Node.js

Node.js is a JavaScript server-side framework. One of the things you can do easily with it is write a HTTP server.

a simple “Hello, world” server looks like:

http = require ('http');
http.createServer(function(request, response){
  response.write("Hello, world");

Now, if you run the simple server and type ‘; in the URL bar of your browser you’ll see the text “Hello, world” in the browser’s window.

I’m sure you’re going to use Node.js for things more complicated than “Hello, world” programs. This server is one process that receive a request and sends a response. Other servers may perform operations that take longer, and we don’t want an operation to block the server from performing other tasks, such as handling other requests.
Node.js allows you to performs those operation in a non-blocking manner by providing the developer with function that accept a callback function as their last parameter. Those function are performed in another thread, and call the callback function upon completion.

The example I want to show you is a code fragment for disk I/O opeerations:


fs.open('a.txt','w', function(err, fd){
  if (err)
    throw err;
  buffer=new Buffer("some long text");
  bytesWrittenSoFar = 0;
  (function writeIt(){
    console.log('Buffer Len ' + bufferLen + ', Bytes Written ' + bytesWrittenSoFar);
    fs.write(fd,buffer,bytesWrittenSoFar, bufferLen - bytesWrittenSoFar, null, function(err,writtenBytes){
      if (err)
        throw err;
      if (bytesWrittenSoFar == bufferLen){
      } else {
        bytesWrittenSoFar += writtenBytes;

How Does It Work?

In this example you can see two asynchronous function:

  • ‘fs.open’, that opens the file, and as the file is open calls the callback function, its 3rd argument.
  • fs.write – that attempts to write the output, and then calls the function ‘writeIt’.

This callback functions are called upon completion of opening a file, or writing it. The completion may be successful or unsuccessful. If unsuccessful, error handling should take place.

The Function WriteIt

The function ‘writeIt’ is a function which is defined and immediately performed. This function is called asynchronously, and until all the data is written, it keeps calling itself. We cannot perform this task using a loop, because a loop will create threads running in parallel. Therefore we use “asynchronous recursion”.

File System function with a simpler syntax have the suffix ‘Sync’ at the end of their names. Those functions you would usually want to avoid, so instead of having the default names, they have a name with a suffix.

Learn more about how to program in Node.js here, and maybe purchase a tutorial with exercises.

Find documentation about Node.js modules and functions here.

Communication Between Backbone.js And PHP

Backbone.js is a Javascript framework known as MV* (Model, View and stuff). This framework has the Backbone.sync function to perform CRUD (Create, Read, Update, Delete) operations. In order for a model object to perform these operations, it should have a property named ‘url’. The ‘sync’ function receives 3 arguments: method, model and options. Model objects also have functions that call the ‘sync’ functions, these functions are: ‘fetch’, ‘save’ and ‘destroy’. The function Save does both Create and Update operation: If the property idAttribute is defined, and the idAttribute is set, ‘save’ sends an update request, otherwise it sends a ‘create’ request. The content type of the request is ”application/json”.

How Does The Server Know What Request Type It Receives?

The client-side developer specifies one ‘url’ only per model. The server-side program can determine the type by checking the value of $_SERVER[‘REQUEST_MOTHED’]:

  • ‘GET’ – a read (or fetch) request.
  • ‘POST’ – a create(save a new model) request.
  • ‘PUT’ – an update(save existing model’s detail) request.
  • ‘DELETE’ – a delete(destroy) request.

What To Send and How To Read?

Backbone.sync uses AJAX to send requests to the server. What you have to pass is the method and model. You better not skip the 3rd arguments, options, which contains at least two member:

  • ‘success’ – a function called when the server processes the request successfully.
  • ‘error’ – a function called when the server fails to process the request.

For example:

Backbone.sync(‘GET’, myModel, {

success: function(resp){

// process the response


error: function(resp){

// Recover or print an error message.



If you call Backbone.sync from an object don’t use ‘this” inside the success and error function as a reference to your object.

For example, if you call ‘sync’ from a view, write ‘myView=this;’ before your call to the ‘sync’ function.

Read Requests

If you send a ‘fetch’ request, specify ‘data’ in the ‘options’ argument, for example:


data: {‘attr1′:’value1’, ‘attr2′:’value2’, … , ‘attrN’:”valueN’},





In the Server Side

The request attributes are taken from $_GET or $_REQUEST, as usual.

Save Requests

Send the attributes and the options.

For example:

myModel.save(myModel.attributes, {





In The Server Side

The data should be read from the file “php://input”, a filename used for reading data from the request body. The content is a string, and should be parsed, but since the incoming request data is JSON encoded, you should use the PHP method “json_decode”.

For example:

$post_vars = json_decode(file_get_contents(‘php://input’), true);

Destroy Requests

This time, you should set the ‘data’ member of the options argument to a JSON string. For example:

Backbone.sync(‘delete’, myModel,{
data: JSON.stringify(myModel),  // This time the developer encodes the data.

success: function(model, resp) {



error: function(){


} );

In The Server Side

Read the data from ‘http://input&#8217; and decode it using json_decode. For example:

$post_vars = json_decode(file_get_contents(‘php://input’), true);

Anyways …

You can make sure you read the data correctly by sending the contents of ‘$_SERVER’, $post_vars and ‘$_REQUEST’ to the error_log. To print an array use json_encode.

Sending a Response To the Client

The response is everything the server side application prints to the standard output. You should print your response data encoded into JSON, as follows:

echo json_encode(responsedata);

Reading a Response

The response returned from the server is the first argument passed to the ‘succss’ callback function. It is not a model object, and you should get values from there using the method ‘get(attr-name’ or the member ‘attributes’.

For example:

{success: function(msg){
switch (msg.get(‘status’)){  // Get the value of the attribute ‘status’ in the server’s response.

To debug your code, you can use ‘alert(JSON.stringify(msg));’.