Using Client side templating with AJAX and PHP

Using Client side templating with AJAX and PHP

Using Client side templating with AJAX and PHP

A small tutorial on how you can easily use client side templating with AJAX and PHP. This flow is ideal when creating PHP webapplications, with easy customizable templates.

Allright now cut the crap!
For a personal project I’m working on I needed the possibility to use templates instead of creating the same layout for each item in my library. The easiest way to understand this is by imagining a guestbook for example,every time a post is added to a database the layout of this entry needs to look exactly the same then the previous and next one.

There are allot of possibilities when it comes to templating in javascript. During my internship we used a javascript class called trimpath, but in this tutorial and also in my project I am working with  jqote . jQote is a plugin for the fabolous jquery javascript library. Actually is it a ported version of the “javascript micro-templating” created by John Resig.

What does this templating system makes it so useful and attractive
The main reason I prefer using jQote is simplicity. It takes only one rule to render all the results coming from a database in JSON format. That does sound incredible doesn’t it?

I show you how it works
Before I start I want to tell you that it is necessary to have skills in AJAX,  jQuery, JSON  and PHP   to finish this tutorial with success.

Allright here we go!
First we need a javascript function to gather the data we want to display in our template. In this example we use a list of books matching the letter we like to display as shown below.

ajaxpost

What this code does:
First it creates a JSON object which contains all parameters we needed in the PHP page, then it converts the JSON object into a string. This step is required because we can only send strings a a parameter to php and no objects. And at then it calls “searchForBooksWithLetter.php” and simulates a POST. The second parameter is the jsonobject which is passed as the variable “data”. BookListResult is the resultfunction which will be called when my SQL query on the PHP page returns the books stored in my database.

allright, now the first step is finished. Next we need to store the global parameters into php variables which we can use afterwards. I told you  before we are using JSON in the POST. This means we first need to decode the JSON string when asking for parameters in. This can be accomplished by using the json_decode() function which is included in PHP 5. The total script to store the global variables into php variables looks like this:

phpGlobalVar
Now we stored the variables it is time to do a database call to gather the data we want to display. This can be done by using a SELECT statement. The result of the SQL will be stored into an array object which will be added to the global  array called “$books”. After the data has been stored to the array “$books” you only need to encode the json object and send it to the client.

The PHP code to accomplish the SELECT statement and to store the elements into an array is displayed below.

sqlStat

What this code does:

To clearify the code: first I ask the database to give me all books which title starts with parameter I gave. ( letter in alphabet from a-z). Next I ask to loop all results returned from the database. During this loop I create a array for each book and at on line  74 I add this line to the global arrays “$books”. The only thing left on the PHP side is to convert the global array “$books” to an JSON object. This can be done by using the json_encode() method. When the array is converted to a JSON object all we need to do is echo the result to the client. This is the point where the PHP code ends and the AJAX request is finished succesfully.

echoResult

Now the function defined in the post function in the beginning of this tutorial is fired (called booklistresult). Inside booklistresult we need to parse the JSON string to a JSON object. This can be done by using the JSON.parse() function.

when the string is parsed to an object you can read all properties of the JSON object which makes it very easy to use. The only thing left is to loop every item in the collection (the result returned from the php page).

By using this line of code every item will be parsed to a template defined in the parameters.

jqote

Extra info about the parameters and the function: This line calls the jqote  function inside “jqote.jquery.js”. As a parameter you need to define the JSON object which you parsed earlier (objectList). And the template which should be used to display all the books (#templ_Book). the last step is to append the template to a div which is defined in your HTML page (#searchR for example).

Now I show you how the HTML looks like in my case. Keep in mind that jQote works with commented CDATA which is converted to HTML during runtime. Make sure that you call the jqote.jquery.js in the body! Not in the header!

The template:

templateHTML

The target where the template will be added

targetHTML

Allright that is it! All you need to know is in this article. I understand that this article contains allot of new information, so do not hesitate to ask if you have questions about this tutorial!

Tips and trouble shooting:

  • Before using SQL statements in PHP test them in the PHP myadmin console
  • make sure you imported the required files (jquery.js, jquery.jqote.js,json.js to complete this tutorial succesfully)
  • if you have any questions about PHP visit http://www.php.net
  • if you have any questions about jQuery visit http://www.jquery.com
  • if you have any other questions just fire it in the comment section.

Have fun!

What this code does:

About the Author

Lode is a Creative-Geek with passion for webdesign, SEO and everything related to online marketing. In January 2014, he has started his own company Magnefk, which specialises in online marketing and website optimization.