Using the new JQuery Templates with AJAX and PHP

Posted on April 4, 2011 by Chad Lung

spacer

The JQuery team and Microsoft have been working on adding templates to JQuery. Today I’ll show you how to use the JQuery Templates and load data from PHP via AJAX.


Note: This was written against beta 1 of the JQuery Templates, things most likely will change and this code might need to be modified to continue working in future releases.

The PHP page is very easy and simply writes back some JSON.

File name: callajax.php

<?php
  echo json_encode(array(array('manufacturer' => 'Apple', 'mobileDevice' => 'iPad2'),
                        array('manufacturer' => 'Motorola', 'mobileDevice' => 'Xoom'),
                        array('manufacturer' => 'Samsung', 'mobileDevice' => 'Galaxy Tab')));
?>

The HTML markup I’m going to use will look like this:

<script id="mobileDeviceTemplate" type="text/x-jquery-tmpl">
  <li>
    <strong>${manufacturer}:</strong> ${mobileDevice}
  </li>
</script>

This will get rendered into this unordered list:

<ul id="ajaxResult"></ul>

When the Ajax is triggered it calls the PHP page and the onSuccess function is called to render the template to the browser:

$("#mobileDeviceTemplate").tmpl(data).appendTo("#ajaxResult");

The full code listing for the index.html page looks like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JQuery Templates</title>
    <script src="/img/spacer.gif"> 

Here are the results:

spacer

spacer

spacer

This entry was posted in AJAX, JavaScript, Open Source, PHP. Bookmark the permalink.

3 Responses to Using the new JQuery Templates with AJAX and PHP

  1. spacer Shiva says:
    April 4, 2011 at 8:47 pm

    Good basic description of jquery templates. Would like to see more of this as well as using the templates with jsonp data

    Thanks!

  2. spacer Noel says:
    May 13, 2011 at 3:38 am

    yes…its quietly simple tutorial but it’s usefull.. if i have to implement jQuery template in real world apps then my client side script with full of large of bunch of html template..would that cost roundtrip performance?? ..thanks

  3. spacer Chad Lung says:
    May 13, 2011 at 7:32 am

    @Noel,

    You just need to determine how much data your pushing to the client. Typically this won’t be anything to be concerned about. Nowadays most people/places have good amounts of bandwidth available to them as they are streaming video and audio, etc. Depends on what your target devices are, ie: mobile? desktop? With mobile you might want to take into consideration the slower 3g networks, etc.

    There is always compression you could tinker with on the web server.

    Chad