Using the new JQuery Templates with AJAX and PHP

Post to Twitter

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.

[ad name=”Google Adsense”]

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

  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">
    <strong>${manufacturer}:</strong> ${mobileDevice}

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:


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

<!DOCTYPE html>
<html lang="en">
    <title>JQuery Templates</title>
    <script src=""></script>
    <script src=""></script>

        $("#callAjax").click(function() {
            type: "POST",
            dataType: 'json',
            url: "http://localhost/JQTemplates/callajax.php",
            cache: false,
            async: true,
            success: onSuccess
        function onSuccess(data)

    <script id="mobileDeviceTemplate" type="text/x-jquery-tmpl">
        <strong>${manufacturer}:</strong> ${mobileDevice}
    <input type="button" id="callAjax" value="Call Ajax"></input><br /><br />
    <ul id="ajaxResult"></ul>

Here are the results:

Post to Twitter

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. Shiva says:

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


  2. Noel says:

    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. Chad Lung says:


    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.


Comments are closed.