In order to populate and dynamically update a table on one of our Zend framework based pages without refreshing the page we had to use a combination of JQuery, JSON and standard Zend views/forms. The JQuery is part of the view and is inserted in <script> blocks while a standard Zend form is used to populate the page with dropdown menus, text boxes etc. JSON is used to handle passing data between the client side JQuery and the server side Zend action.
The following is a simple example, which passes JSON stored by JQuery in a hidden field to a Zend action on the server to update a database. Where possible the code has been simplified (so no long winded database connection etc etc). As getting Zend framework up and running can be a bit difficult from scratch, this is not covered here. The Zend Framework Quickstart is useful although personally I think it could be clearer for first time users. Although I use modules in Zend to split different sections of my web application into self contained areas, for this example I will keep it as simple as possible and not use modules. To keep things even more simple I am not going to describe any validation or POST handling of the Zend action, we are only concerned with JQuery/Zend integration.
The example action we are going to call is the LIST action in the VISIT controller, which will show a list of visits and allow us to add a new one using a simple one textbox interface. JQuery will be used to pull all the required table data from the server and handle the visual client side aspect of adding a new visit.
The controller VisitController.php will have a very simple LIST action that looks like the following:
public function listAction()
All this action does is set the view title, generate a Form object from a Zend form Form_ListVisit() and set the view form to this object (thereby placing the form on the page). The action will not do anything without a corresponding view script and Zend form, which both need to be created as separate files in the correct location in your file structure (more than likely /views/scripts/visit/list.phtml and /forms/ListVisit.php). Again, use of views and Zend forms is standard Zend Framework practice and is beyond the scope of this simple example.
For the view, currently without any JQuery, it will also be very simple:
All this does is place the title and the form on the page that is displayed to the user, both the title and the form are set in the controller (see above). In a moment the JQuery will be placed in a <script> tag above this <?php ?> section, although it is a good idea to refactor your code to keep the view as simple as possible by having the JQuery code in a separate .js file. The “statusmessage” div will be used by JQuery to place success/error message on screen when we update the database.
The ListVisit.php Zend form file is more complicated and in the real world can take a while to write, including all the objects, decorators, subforms, validation options etc. In this case we keep it very simple and just add a single hidden field that we will use to store a single JSON string and a textbox to handle user input:
class Form_ListVisit extends ZendX_JQuery_Form
So on loading the NEW action on the VISIT controller we end up with a blank page with only a title that says “Visit List” and a single textbox. The hidden field placed on the page by the Zend form is there but is empty, there is no table on screen and no other links. In this example we are going to add everything else we need, such as the table of visits, link to add new visit and link to save to the database, using JQuery. The communication between the client side and the server is handled using JQuery’s .post method and another Zend action which is set to take in JSON and only return a JSON string.
JQuery is used to generate a simple single column table and add two links to the page. The first link “Add New Visit” will add whatever is in the textbox to our very simple single column table. The second link “Save to Database” will update the database with the values of our table by calling the SAVEDATA action on the VISIT controller. The SAVEDATA action takes in a JSON string, does something to the database and returns a JSON string to the client. The possibilities that result from passing JSON between client and server using this JQuery method are amazing and make it trivial to create AJAX interfaces with JQuery and Zend.
IMPORTANT: I had to include the well known json2.js script by Douglas Crockford in order to get my JSON encoding and decoding working correctly in all browsers. This script saved a lot of headaches and is only 17k (and can probably be minified).
In the view, in the <script></script> at the top we first need to add in the JQuery that will be loaded on document ready (standard JQuery practice):
Note that the click handling functions that have been added to the 2 links call either addvisit() or savedata(). These 2 functions are described above and outside the JQuery $(document).ready() as follows:
When a row is added to the table the hidden field is updated to contain a JSON string describing the whole table. It is this JSON string that is passed to the SAVEDATA action of the VISIT controller by the savedata() function’s .post(), where it is converted to an object by some simple PHP code and then stored in the database:
The SAVEDATA action is a standard Zend action on the VISIT controller with the addition of a couple of important lines of code to avoid rendering a view:
public function savedataAction()
So now you can pass JSON objects between the client and the server using JQuery and json2.js. In this example JQuery is used to populate a table client-side and then pass the data for storage in the database on the server.
// note that we don't actually post any data this time, we only retrieve data
// clean up and convert the returned JSON to a string
// (this step required as sometimes Zend JSON is not always "correct")
var json = JSON.stringify(data);
// convert JSON string to object
var jparsed = JSON.parse(json);
// create a blank string ready to store a single html row of the table
var rowstring = "";
// iterate through the JSON object adding the html for a row of the table each time
rowstring += "<tr class='datarow'>";
var obj = jparsed[i];
// iterate through each column of the row, adding the html for a table cell each time
rowstring += "<td>" + obj[j] + "</td>";
rowstring += "</tr>";
// append the newly formed rowstring to the table
// set the hidden field to the JSON string
The RETRIEVEDATA action (simplified to remove database queries) looks like:
public function retrievedataAction()
// get array of objects from database using ORM
// alternatively, use standard SQL connection etc etc
// e.g. $arr = SomeORMMethod("visits");
$output = array();
foreach($arr as $key => $value)
$row = array();
$row = $value->visitName;
$row = $value->visitDate;
$output = $row;
$json = Zend_Json::encode($output);
You may have noticed that all of this can be done without Zend at all. If you read the JQuery .post() documentation it becomes a bit clearer, especially if you end up not using JSON at all. I know there are other methods out there to do this, but since I’m heavily involved with Zend at the moment I thought it would make sense to try and explain this example, as I used it in my own code. Also note, there is no security at all on this example; you will need to manage sessions, use encrypted data etc to make this secure.
The basic framework of JQuery/JSON/Zend means you can easily create rich MVC apps with AJAX and the flexibility of JQuery means that you don’t even have to use Zend at all! You can apply the same basically identical approach with Microsoft MVC, CakePHP or even with your own frameworks, all you need to do is modify the actions.