Dojo Tutorial with a grid: part 2 – english version
Here’s the second part of the dojo tutorial – covering an AJAX call and the answer from the webserver in PHP.
3.2 Step-2 Create a HTML-Form
Let’s have a closer look at the following code
<form name="form_search" id="form_search" action="gridtut_request.php" method="post">
<input type="text"
name="txt_name"
id="txt_name"
value=""
dojoType="dijit.form.TextBox"
trim="true"
propercase="true" />
<input type="submit" id="find" value="Find!" />
</form>
<br />
<div id="gridContainer" class="gridDiv"></div>
As you can see, we just use a textfield and a search button. Everything looks like we’re used to (well, except the textfield), and that’s good because the site is usable without javascript. We only use typical html element like <form> or <input>. When the browser loads the site, the dojo parser looks for the attribute “dojoType” (case sensitive) and decides which elements to be included. Dojo calls these elements dijits (Dojo Widgets).
Because those html elements are changed by the dojo parser, you could also use <div> or <span> tags. And it would be even faster, not to parse for html tags, but to generate them directly via Javascript. But in both ways the site wouldn’t be usable without javascript. And robots would find anything too.
Allright, back to the topic
The form is followed by a <div>-Container, which is meant to be a placeholder for the grid.
We’re done for html, time to see some javascript!
3.3 Step-3 First javascript
Up for now, our tutorial looks a little disappointing. The file gridtut.js is totally empty, but we already called the function “init” from it, thus creating an error. We’re going to change that now!
// This function is called first
function init() {
searchbutton = dojo.byId("find");
// connect the submit button with the proper function
searchbuttonConnection = dojo.connect(searchbutton, 'onclick', null, my_submit);
}
function my_submit(event) {
dojo.stopEvent(event);
alert('Yohoo!');
}
The function “init()” is called by dojo, as soon as the parser finished loading the site. By the way, the more code you have in your html-file, the longer it takes to parse it.
We now use the init-Function to replace the form’s standard submit with our own custom function. For this, dojo likes to use element ids, not names.
dojo.connect is used to connect the search button and the browser event “onclick” with our custom function, the last command “dojo.stopEvent(event)” is used to disable the standard submit.
For getting this to work, we need an additional parameter (I used “event”) in the parentheses of our new submit function.
Dojo.connects uses the parameter automatically,
Now if we did everything right, we should get an alert with “Yohoo!” instead of the submit
3.4 Step-4 Time for some AJAX.
Of course we want to use Ajax! Since it is one of the main reasons we use dojo and you can’t present a new project without it.
function my_submit (event) {
dojo.stopEvent(event);
var kw = {
url: "gridtut_request.php",
load: function(data){
var result = eval('('+data+')');
alert ("There is some data: " + data);
},
error: function(data){
alert("An error occured: " + data);
},
form: "form_search"
};
dojo.xhrPost(kw);
}
Now this looks more complicated than it is.
First of all, KW is just a shortcut for keywords, but you can freely choose a different name. Most dojo functions accept javascript objects as parameter, so it’s very convenient to create an object with all needed parameters and pass it to “dojo.xhrPost” afterwards.
Here’s what we need to make an AJAX call.
URL:
Here we specify the location of our dynamic web site. This could also be .jsp or .asp – I try to keep the php specific part a small as possible.
LOAD:
When the webserver sends a response, this function is being called. Out of laziness I used an anonymous function without an own name. But you’re free to call a function which is buried somewhere else in the code.
The parameter “data” contains the responded payload – for this example a JSON string.
ERROR:
Same as load, if we get an error, this function is being called.
FORM:
The form, we’re going to transmit (referenced by its id)
All these parameters are now packed in a single object (kw), which we are passing to “dojo.xhrPost”.
So what we did now, would have been already possible with pure html: sending a form to the webserver. But much more complicated
Being asynchronous and having error-handling makes the difference. Not to mention, that this code is very expandable.
3.5 PHP – Generate some JSON
For all friends of php, here’s some code creating a JSON string for us.
JSON, btw. means Javascript Object Notation and is one way, to exchange data between client and server (XML is the other popular way. Actually JSON is just a piece of javascript code which creates a javascript object once it is executed. So our PHP array is going to converted into a construction plan for a javascript object.
Important: The JSON string has to returned by echo, not by return. This is because the string has to be the response of the server.
<?php
// some sample data
$data = array ();
$data[] = array ('id' =>1,
'surname' =>'Petersen',
'givname' =>'Bob',
'job' =>'cop',
'age' =>32);
$data[] = array ('id' =>2,
'surname' =>'Petersen',
'givname' =>'Elvis',
'job' =>'dog catcher',
'age' =>25);
$data[] = array ('id' =>3,
'surname' =>'Petersen',
'givname' =>'Peter',
'job' =>' photographer',
'age' =>52);
$data[] = array ('id' =>4,
'surname' =>'Petersen',
'givname' =>'Joe',
'job' =>'dike reeve',
'age' =>61);
$data[] = array ('id' =>5,
'surname' =>'Schröder',
'givname' =>'Petra',
'job' =>'baker',
'age' =>31);
$data[] = array ('id' =>6,
'surname' =>'Schröder',
'givname' =>'Elvira',
'job' =>'meat salesperson',
'age' =>23);
$data[] = array ('id' =>7,
'surname' =>'Schröder',
'givname' =>'Martin',
'job' =>'cook',
'age' =>37);
// the searchresult
$result = false;
// Array counter, since the JSON function need a clearly ordered array from zero on
$counter = 0;
// main part
if (!empty($_REQUEST['txt_name'])) {
// search for the data
foreach ($data as $row => $value) {
if ($value['surname'] == html_entity_decode($_REQUEST['txt_name'])){
// first search hit
if (!$result) $result = array();
// put the search result into an array
$result[$counter]['id'] = $data[$row]['id'];
$result[$counter]['surname'] = htmlentities($data[$row]['surname']);
$result[$counter]['givname'] = htmlentities($data[$row]['givname']);
$result[$counter]['job'] = htmlentities($data[$row]['job']);
$result[$counter]['age'] = $data[$row]['age'];
$counter++;
}
}
// empty search result
if (!$result) $result[] = array ('id' =>0,
'surname'=>'found',
'givname'=>'No data',
'job' =>' ',
'age' =>0);
$temp = Array ('identifier'=>'id', 'items'=>$result);
echo json_encode($temp);
}
?>
So we’re searching for the given name and return the result as JSON. Of course this looks a little different in jsp or asp.
It’s good to know, that PHP’s JSON function can’t handle foreign characters, so I convert everything html entities (auml instead of ä).
If you start a new project (or are already using it), converting to UTF-8 makes your dojo life a lot easier. Unfortunately I still have to work with ISO-885-91.
Here’s how a JSON string should look like (having searched for Petersen):
{"identifier":"id","items":[{"id":1,"surname":"Petersen","givname":"Bob","job":"cop","age":32},{"id":2,"surname":"Petersen","givname":"Elvis","job":"dog catcher","age":25},{"id":3,"surname":"Petersen","givname":"Peter","job":"\tphotographer","age":52},{"id":4,"surname":"Petersen","givname":"Joe","job":"dike reeve","age":61}]}
I you don’t have a webserver handy, you can also copy and paste this string to a textfile and using it as the response.