Ajax with JSON using PHP and DOJO

Buzzword alert! Buzzword alert! Synergisticly expedite transparent web-readiness! Buzzword alert! Buzzword alert!

Ok, now that I’ve got that out of the way…

Ajax is a web application development architecture that resembles more of a client-server architecture than traditional web development. In an Ajax application a client application is delivered to the browser consisting of HTML, CSS and JavaScript. The interactions of the client with the server send and receive data, data that the client then knows how to display to the user.

While Ajax has an ‘X’ which stands for XML in its name, Ajax really has nothing to do with XML at its core. In reality parsing XML is usually a lot more work than you need to do when you expect that a client will be a browser. Along comes JSON. JavaScript Object Notation is a structured format that corresponds to the needs of the client-side programming environment: JavaScript. JSON can be evaluated on the client into JavaScript object graphs, no parsing, no XML Sax or DOM parsing, just eval() into a JavaScript object and then call methods on it.

Ajax, as a hot technology, I was of course interested in learning more so I created a small example application that I could build and play with a bit. I thought I’d share it with everyone so they could use it as a quick-start example for trying some of these technologies.

I chose to use the DOJO Toolkit as my client-side framework because it seems to have a very broad library already built and a reasonable amount of documentation. DOJO is really engineered like a true software application. It really shows off the fact that you can write good code and good frameworks using the JavaScript language.

Show Me Some Code

Here’s an example of a simple blog application that talks to a single table to display articles.


A very simple HTML skeleton that imports the CSS, DOJO and the Application written in JavaScript.

	<link rel="stylesheet" type="text/css" href="blog.css" />
	<script type="text/javascript" src="dojo.js"></script>
	<script type="text/javascript" src="blog.js"></script>
	<div id="header">Blog</div>
	<ul id="articleList"></ul>
	<div id="article"></div>


The Application that is delivered to the Client.

getArticle() is called and initiates an asynchronous call to the getArticle.php code. When the response comes back DOJO automatically calls the showArticle() function and passes the response data to it. The showArticle() function handles formatting the data by manipulating the HTML DOM of the page.

function getArticle(id) {
	var idStr = "{\"id\":" + id + "}";
	request = {'action' : 'getArticle', 'data' : idStr};
    	url: "getArticle.php",
    	handler: showArticle,
    	mimetype: "text/json",
		content: request
function showArticle(type, data, evt) {
	appendArticlePart('title', data.title);
	var date = dojo.date.fromSql(data.time);
	appendArticlePart('time', dojo.date.toRelativeString(date));
	appendArticlePart('content', data.content);
	dojo.lfx.highlight(dojo.byId('article'), dojo.lfx.Color);
function appendArticlePart(id, value) {
	var element = document.createElement("div");


The code that lives on the server and responds to a given service request. This PHP code parses the HTTP request that the DOJO toolkit sends to the server. It parses the data from a JSON string into PHP objects, calls into the database and gets some values out. It then turns a PHP array into a JSON string to return to the web client.

header('Content-type: text/json');
$action = $_REQUEST["action"];
$data = $_REQUEST["data"];
$data = str_replace("\\\"","\"",$data);
$json = new services_JSON();
if ( $action == "getArticle") {
	$jsonArray = $json->decode($data);
	$article = getArticle($jsonArray);
	print $json->encode($article);
function getArticle($node) {
	$result = null;
	$link = connect_db();
	if ($stmt = $link->prepare("select id, title, publish_time, content from articles where id=?")) {
		$stmt->bind_param("i", intval($node->id));
		$stmt->bind_result($id, $title, $time, $content);
		if ($stmt->fetch()) {	
			$result = array(
				"id"=> $id,
				"title" => $title,
				"time" => $time,
				"content" => $content,
				"objectId"=> "article"
		return $result;
function connect_db() {
	$mysqli =  new mysqli("localhost", "root", null, "blog");
	/* check connection */
	if (mysqli_connect_errno()) {
		printf("Connect failed: %s\n", mysqli_connect_error());
	return $mysqli;

While this example is written in PHP, there is nothing that would prevent you from writing the server component in any language. There are JSON libraries for every language you’ve ever heard of (and a lot that you’ve never even heard of). The notation itself is fairly simple (it’s about 700 lines of code in PHP), so implementing it in another language should be relatively easy as well.

Consider using implementation neutral URIs for your service calls and then using something like Apache mod-rewrite to map those URIs to the proper calls in whatever language you use to implement the server code. Doing this and you should be able to completely decouple your web client from the server components.


DOJO Toolkit
Dojo: The Definitive Guide
Mastering Dojo: JavaScript and Ajax Tools for Great Web Experiences (Pragmatic Programmers)

Published by

Geoff Lane

I’m Geoff Lane and I write Zorched.net as I figure things out about software development in the hopes that it can help other people facing similar situations. Also as a thanks to the larger web community for all of the information and knowledge that they have shared. I’ve been a professional software developer since 1999 working with a variety of different technologies. I’ve worked for startups in the Silicon Valley and Chicago, IL and now work as a consultant building custom applications for clients.

9 thoughts on “Ajax with JSON using PHP and DOJO”

  1. Sorry, you can publish th e source in zip o rar file


    I don’t understand, where are the file blog.css,
    the petition of server is getArticle.php, how
    the ejecution of getArticle(id), I declared in showArticle.html
    a button asda
    The error is

    404 Not Found

    Not Found

    The requested URL /dojo/dojo/event/*.js was not found on this server.

    Apache/2.2.3 (Ubuntu) PHP/5.2.1 Server at localhost Port 80


    dojo.io has no properties

    The is my error’s… Thanks…

  2. Great tut, I encoutered some problems though, I got a similar problem to the first problem, that was until I realized that the version of dojo I have doesnt need to import the litsed packages as they come as part of the base system, After that was solved I encountered some further problems with running the app, I think mainly because of the version, Im getting dojo.dom is undefined. investigating, maybe one day I will crack it, right now I have to go home

Leave a Reply

Your email address will not be published. Required fields are marked *