Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
PHP Ajax Cookbook
PHP Ajax Cookbook

PHP Ajax Cookbook: Over 60 simple but incredibly effective recipes to Ajaxify PHP websites with this book and ebook

eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

PHP Ajax Cookbook

Chapter 1. AJAX Libraries

In this chapter, we will cover:

  • Designing simple navigation using jQuery

  • Creating tab navigation

  • Designing components using Ext JS

  • Event handling in MochiKit

  • Building tab navigation using Dojo

  • Building a chart application using YUI library

  • Loading dynamic content using jQuery slider

  • Creating an Ajax shopping cart using MooTools

  • Building an Ajax login form using prototype.js

In this chapter, we will learn how to work with the most famous JavaScript libraries and frameworks with capabilities of Ajax functionality. These libraries were selected by our subjective opinion and we are not trying to say which library/framework is better or worse. Each of them has its advantages and disadvantages.

Designing simple navigation using jQuery


jQuery is a development framework that allows us to use JavaScript in our HTML document. Now we will build a simple navigation using the basic jQuery features.

Getting ready

Before we can begin, we need to include the latest jQuery library. We can download it from the download section at www.jquery.com. We will save it in our JavaScript folder named js, in the root of our HTML document, for example, cookbook.

All libraries mentioned in this book are also available in an online cache such as http://code.google.com/apis/libraries/.

Note

You can download the example code fles for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the fles e-mailed directly to you.

How to do it...

Now, we can start coding our task1.html page. We'll place it in the cookbook folder.

<!doctype html>
<html>
<head>
  <title>Example 1</title>
</head>

<body>
  <ul id="navigation">
    <li id="home"><a href="#">Home</a></li>
    <li class="active"><a href="#">Our Books</a></li>
    <li><a href="#">Shop</a></li>
    <li><a href="#">Blog</a></li>
  </ul>
  <div id="placeHolder">
    <!-- our content goes here -->
  </div>

  <script src=js/jquery.min.js></"></script>

  <script>
    $(document).ready(function(){
      $('#navigation li a').each(function(){
      var $item = $(this);
        $item.bind('click',function(event){
        event.preventDefault();
          var title = $item.html();
          var html = title + ' was selected.'; 
          $('#placeHolder').html(html);
        });
      });
      $.get('ajax/test.html', function(data) {
        $('.result').html(data);
          alert('Load was performed.');
      });
    });
  </script>
</body>
</html>

How it works...

Now, let's explain what we have done in the preceding code snippet. The main idea of our script is to find each hyperlink <a> in the document, prevent its default functionality, and display the hyperlink content in our placeHolder. From the beginning, we started with doctype and the main HTML layout. The body of the page contains a navigation and a placeholder element for the dynamic content.

The most important part for jQuery functionality is to include our jQuery library. Let's place it before the closing <body> tag. This will allow the HTML of a page to load first:

<script src="js/jquery.min.js"></script>

After loading our HTML page and when the document is ready, we can define our JavaScripts scripts in the $(document).ready() function:

<script>
  $(document).ready(function(){
    alert("Hello jQuery!");
  });
</script>

This can be also shortened to $():

<script>
  $(function(){
    alert("Hello jQuery!");
  });
</script>

The dollar sign $() represents an alias to the jQuery() factory function. Within this function we can use all the CSS selectors like ID, class, or exact tag names. For example:

  • $('a'): Selects all hyperlinks in our document

  • $('#myID'): Selects the element with this ID

  • $('.myID'): Selects all elements with this class

In our case, we are selecting all hyperlinks in the navigation <div> and defining their own functionality with an event handler for click events:

$item.bind('click',function(event){
  // prevent default functionality
  event.preventDefault();
  // here goes the rest
});

And the last step of our example is creating the title VAR and HTML string, which goes to the placeHolder:

var title = $(this).html();
var html = title + ' was selected.';
$('#placeHolder').html(html);

There's more...

The preceding example was really simple. But there is a lot more that jQuery can offer to us. This includes special selectors, effects, DOM manipulation, or AJAX functionality.

We can specify our selectors more precisely. For example, we can specify which hyperlinks should be affected based on their href attributes:

$('a[href^=mailto:]').addClass('mailto);
$('a[href$=.pdf]').addClass('pdf');
$('a[href^=http] [href*=milan]').addClass('milan');

jQuery also covers all possible events (click, blur, focus, dblclick, and so on), visual effects (hide, show, toggle, fadeIn, fadeOut, and so on), or DOM manipulations (appendTo, prependTo, and so on). It has a full suite of AJAX capabilities, which are really easy to use, such as:

$.get('test.html', function(data) {
  $('.result').html(data);
});

But we will have a better look at more jQuery features in further tasks and chapters.

See also

Chapter 1, Ajax using jQuery

Chapter 2, jQuery UI

Chapter 3, Useful tools using jQuery

Creating tab navigation


jQuery UI is built from the core interaction plugins of jQuery. As a high-level framework, it makes creating effects and animation easy for every developer. Now we will build a tab navigation using jQuery UI.

Getting ready

First of all, we need to include the jQuery library from www.jquery.com, if we haven't done it in the preceding recipe. Then, we can download jQuery UI library from www.jqueryui.com/download. On this page, we can download specific modules or the whole library. We can select the theme we like or create our own one with advanced theme settings. For now, we will select the whole library with the ui-lightness theme.

How to do it...

  1. Now we are ready for coding. Let's start with the HTML part. This part will define a navigation element with three tabs and one accordion.

    <body> 
      <div id="navigation"> 
        <ul> 
          <li><a href="#tabs-1">Home</a></li> 
          <li><a href="#tabs-2">Our Books</a></li> 
           <li><a href="ajax/shop.html">Shop</a></li> 
        </ul> 
        <div id="tabs-1"> 
          <p>Lorem ipsum dolor 1</p>
        </div>
        <div id="tabs-2">
    
          <p>Lorem ipsum dolor 2</p> 
        </div>
      </div> 
    </body> 
  2. When the HTML is ready, we can continue with CSS and JavaScript CSS styles in the <head> tag, as shown in the following code:

    <head>
      <link href="css/ui-lightness/jquery-ui.custom.css" 
      rel="stylesheet" />
    </head>
  3. We will add JavaScript before closing the <body> tag:

      <script src="js/jquery.min.js"></script> 
      <script src="js/jquery-ui.custom.min.js"></script> 
      
      <script> 
        $(document).ready(function(){
          $('#navigation').tabs();
        });
      </script> 
    </body>
  4. Our result looks like the following:

How it works...

The downloaded jQuery UI contains the whole CSS content of the selected theme (jquery-ui.custom.css). All we need to do is to include it in the <head> tag:

...
  <link href="css/ui-lightness/jquery-ui.custom.css" 
  rel="stylesheet" />

After CSS, we include jQuery and the jQuery UI library:

  <script src="js/jquery.min.js"></script> 
  <script src="js/jquery-ui.custom.min.js"></script> 

The JavaScript part is really simple:

$('#navigation').tabs();

It is important to fit the required HTML structure. Each hyperlink is targeting the HTML content in selected <div> tags. To create a relation between them we will use #id in each hyperlink and the ID of the selected <div> tag (for example, tabs-1).

There is an exception in the third tab, which loads the requested data via Ajax. In this case, we do not define any target area, as it will be created automatically. As you can see, using the Ajax in jQuery UI is really easy and comfortable.

There's more...

jQuery UI offers us a lot of options. We can use just a default functionality as was presented in the preceding code snippet or some additional functionality:

Content via Ajax:

$( "#navigation" ).tabs({ajaxOptions: {} });

Open on mouseover:

$( "#navigation" ).tabs({event: "mouseover"});

Collapse content:

$( "#navigation" ).tabs({collapsible: true});

Sortable:

$( "navigation" ).tabs().find( ".ui-tabs-nav" ).sortable({ axis: "x" });

Cookie persistence:

$( "#navigation" ).tabs({cookie: { expires: 1 }});

See also

Chapter 3, Useful tools using jQuery

Designing components using Ext JS


Ext JS is a JavaScript framework that offers a lot of cross-browser user interface widgets. The core of Ext JS is build-on component design, which can be easily extended to meet our needs.

Getting ready

We can download the latest version of Ext JS framework from www.sencha.com, Ext JS section. Now, we are ready to build a classic Ext JS layout with two columns and one accordion. We can also prepare a simple HTML file ajax/center-content.html to test the Ajax functionality:

…
<body>
<p>Center content</p>
</body>
…

How to do it...

  1. First of all, we will include mandatory files like CSS and Ext JS library files.

    <link rel="stylesheet" href="css/ext-all.css" /> 
    
    <script src="js/ext-base.js"></script> 
    <script src="js/ext-all.js"></script> 
  2. We will continue with the onReady function, which will run our script:

    <script type="text/javascript"> 
    Ext.onReady(function(){
    
      var viewport = new Ext.Viewport({
        layout:'border',
          items:[{
          region:'west',
          id:'west-panel',
          title:'West',
          split:true,
          width: 200,
    
          layout:'accordion',
          items: [{
              html: 'Navigation content',
              title:'Navigation'
              },{
            title:'Settings',
            html: 'Settings content'
            }]
          },{
        region:'center',
        layout:'column',
        autoLoad:{
          url: 'ajax/center-content.html', 
          method:'GET'
           }
        }]
      });
    }); 
    </script> 
  3. Our layout with an accordion navigation is ready:

How it works...

Ext JS is built for developers, to make their lives easier. As you can see in the source, we have built a layout with a simple JavaScript object. We have a "Viewport" with two items. One is positioned to the left (region: West) and the second to the right (region: East). We don't have to take care of the CSS in this case. Everything is handled directly by Ext JS through our variables like width, margins, cmargins, and so on. The layout property is really powerful. The inner layout on the West side is an accordion with the items Navigation and Settings. In the center column, we can see content loaded via Ajax, using the autoLoad method.

There's more...

The possible options for layout are: Absolute, Anchor, Card, Column, Fit, Table, Vbox, and Hbox.

Event handling in MochiKit


The next lightweight library in this chapter is MochiKit. In this task we will build a script for listing the onkeydown and onkeypress events. After each event we will display which key was pressed with its key code and key string.

Getting ready

All mandatory files, documents, and demos are available on www.mochikit.com. We need to download the whole MochiKit library and save it in our js folder. Be careful, MochiKit.js is just the main file that includes all necessary sub-modules from MochiKit (such as, base.js, signal.js, DOM.js, and so on). The landing page for Ajax requests will be ajax/actions.php:

<?php 
  if($_GET["action"] && $_GET["key"]) {
    // our logic for processing given data
  } else {
    echo "No params provided";
  }
?>

How to do it...

  1. Let's start with HTML code:

    <table> 
      <tr> 
          <th>Event</th> 
           <th>Key Code</th> 
           <th>Key String</th> 
      </tr>
      <tr>
          <td>onkeydown</td> 
        <td id="onkeydown_code">-</td> 
        <td id="onkeydown_string">-</td> 
      </tr> 
      <tr> 
        <td>onkeypress</td> 
        <td id="onkeypress_code">-</td> 
          <td id="onkeypress_string">-</td> 
      </tr> 
    </table>
  2. Include the MochiKit framework:

    <script type="text/javascript" src="js/MochiKit/MochiKit.js"> </script> 
  3. Define the JavaScript functionality:

    <script>
    connect(document, 'onkeydown', 
        function(e) {
            var key = e.key();    
            replaceChildNodes('onkeydown_code', key.code);
            replaceChildNodes('onkeydown_string', key.string);
          doSimpleXMLHttpRequest("ajax/actions.php", 
            { action: "keydown", key: key.code});
        });
        
    connect(document, 'onkeypress', 
        function(e) {
            var key = e.key();
            replaceChildNodes('onkeypress_code', key.code);
            replaceChildNodes('onkeypress_string', key.string);
          doSimpleXMLHttpRequest("ajax/actions.php", 
            { action: "keypress",  key: key.code});
        });
    </script>
  4. Our result is:

How it works...

The connect() function connects a signal (Mochikit.Signal API Reference) to a slot. In our case, we are connecting our document to the onkeydown and onkeypress handlers to call a function(e). Parameter e represents our event object, when the key() object reference returns key code and string.

replaceChildNodes(node[, childNode[,...]]) is a function of Mochikit.DOM API Reference, which removes all children from the given DOM element and then appends the given childNode to it.

After each onkeydown and onkeypress event we are sending an Ajax call using the doSimpleXMLHttpRequest() function. In our example, the request from our page looks like ajax/actions.php?action=onkeydown&key=87.

There's more...

Any object with connected slots can be disconnected by the disconnect() or disconnectAll() functions. In the case that we want to use connect() just once, we can use the connectOnce() function and this will disconnect the signal handler automatically once it has fired.

MochiKit allows us to make the most of existing browser-generated events, but some of them are not natively supported by all browsers. MochiKit is able to synthesize these events, which include onmouseenter, onmouseleave, and onmousewheel.

Building a tab navigation using Dojo


Now we will have a look at Dojo JavaScript Library. We will build a simple tab navigation using the basic functionality of the Dojo Toolkit (dojoToolKit).

Getting ready

We need to include the Dojo Toolkit from websites such as Google CDN (http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js) or AOL CDN (http://o.aolcdn.com/dojo/1.5/dojo/dojo.xd.js).

If you want to download the whole Dojo SDK you can find it at www.dojotoolkit.org/download.

The landing page for Ajax requests will be ajax/content1.html:

<body>
  <h1>Operation completed.</h1>
</body>

How to do it...

  1. We will include styles from the claro theme (included in dojoToolKit) in the <head> tag of our document:

    <link rel="stylesheet" type="text/css" href="js/dojoToolKit/dijit/themes/claro/claro.css" />
  2. We will define our HTML code in the body of our document:

    <body class="claro">
    <div>
      <div dojoType="dijit.layout.TabContainer">
        <div dojoType="dijit.layout.ContentPane" 
          title="Our first tab" selected="true">
            <div id="showMe"> 
              click here to see how it works
            </div> 
        </div>
        <div dojoType="dijit.layout.ContentPane" 
            title="Our second tab">
          Lorem ipsum - the second
        </div>
        <div dojoType="dijit.layout.ContentPane" 
      title="Our last tab" closable="true">
        Lorem ipsum - the last...
        </div>
      </div>
    </div>
    </body>
  3. When the HTML and CSS is ready, we will include DojoToolkit with required modules:

    <script type="text/javascript"
      src="js/dojoToolKit/dojo/dojo.js" 
      djConfig="parseOnLoad: true"></script>
        
    <script type="text/javascript">
      dojo.require("dijit.layout.TabContainer");
      dojo.require("dijit.layout.ContentPane");
    </script>
  4. Adding JavaScript functionality gives us the following:

    <script type="text/javascript">
      dojo.addOnLoad(function() {
        if (document.pub) { document.pub(); }
        dojo.query("#showMe").onclick(function(e) {
          dojo.xhrGet({
            url: "ajax/content1.html",
            load: function(result) {
              alert("The loaded content is: " + result);
            }
          });
          var node = e.target;
          node.innerHTML = "wow, that was easy!";    
        });
      });
    </script>
  5. When the preceding code snippet is ready and saved, our result will be a simple tab navigation with three tabs.

How it works...

As you can see in the source, we are using the Dijit-Dojo UI component system. Dijit is included in Dojo SDK and includes UI components with four supported themes (nihilo, soria, tundra,and claro). We can set which theme we want to use by selecting a class within our <body> tag. In the preceding example we have class="claro".

We need to provide the djConfig attribute with parseOnLoad:true when we include the dojoToolKit script. Without this, Dojo won't be able to find the page elements that should be converted to Dijit widgets.

When we want to use a specific widget, we need to call the required class for the widget (dojo.require("dijit.layout.TabContainer")) and provide its dojoType attribute (dojoType="dijit.layout.TabContainer"). As an example of using Ajax in Dojo, we use the dojo.xhrGet() function to get the content of ajax/content1.html each time we click on showMe div.

Building a chart application using YUI library


In this task we will use a UI library developed by Yahoo! to build a chart.

Getting ready

The YUI library is available for download on Yahoo!'s developer website (http://developer.yahoo.com/yui/3). After we save it in our js folder, we are ready to start programming.

How to do it...

  1. We have to start by including the YUI library in the <head> tag of our document along with styles for the placeholder of our chart:

    <script type="text/javascript" src="js/yui-min.js"></script> 
    <style> 
    #mychart {
        margin:10px;
        width:90%; max-width: 800px; height:400px;
    }
    </style>
  2. We will place our HTML in the <body> tag to mark where our chart will be placed:

    <div id="mychart"></div> 
  3. Our JavaScript is as follows:

    <script type="text/javascript"> 
    (function() {
        YUI().use('charts', function (Y){ 
            //dataProvider source
            var myDataValues = [ 
            {date:"January"	, windows:2000, mac:800, linux:200}, 
            {date:"February", windows:3000, mac:1200, linux:300}, 
            {date:"March"  , windows:3500, mac:1900, linux:1400}, 
            {date:"April"  , windows:3000, mac:2800, linux:200}, 
            {date:"May"    , windows:1500, mac:3500, linux:700},
            {date:"June"    , windows:2000, mac:3000, linux:250} 
            ];
           
            //Define our axes for the chart.
            var myAxes = {
                financials:{
                    keys:["windows", "mac", "linux"],
                    position:"right", type:"numeric"
                },
                dateRange:{
                    keys:["date"],
                    position:"bottom",type:"category"
                }
            };
     
            //instantiate the chart
            var myChart = new Y.Chart({
                type:"column", categoryKey:"date",
                dataProvider:myDataValues, axes:myAxes, 
                horizontalGridlines: true,
                verticalGridlines: true,
                render:"#mychart"
            });
        });
    })();</script>
  4. The results after saving and opening our HTML document are as follows:

How it works...

YUI Charts are defined in the Chart object. For the "document ready" function we will use the (function(){...})() syntax. We need to specify that we want to use YUI() 'charts'.

The main part is creating a Y.Chart object. We can define how this chart will be rendered, how our gridlines will look, where to display our chart, and which data to display. We will define axes with the myAxes object, which handles the legend on the sides. Our data are stored in the myDataValues object.

There's more...

There are many possibilities and ways to style our charts. We can split the chart to the smallest parts and set each property. For example, rotation of the label or margin:

styles:{ 
  label: {rotation:-45, margin:{top:5}}
}

YUI also covers an AJAX functionality. This is how a simple AJAX call will look:

<div id="content"> 
  <p>Place for a replacing text</p> 
</div>
  
<p><a href="ajax/content.html" onclick="return callAjax();">Call Ajax</a></p> 
 
<script type="text/javascript"> 
//<![CDATA[

function callAjax(){
  var sUrl = "ajax/content.html";
  var callback = { 
    success: function(o) {
      document.getElementById('content')
        .innerHTML =  o.responseText;
    }, 
    failure: function(o) {
      alert("Request failed.");
    }
  } 
  
  var transaction = YAHOO.util.Connect
    .asyncRequest('GET', sUrl, callback, null);
  return false;
} 
//]]> 
</script>

We created the callAjax() function, which is triggered by clicking on the Call Ajax hyperlink. The Ajax call is provided by YAHOO.util.Connect.asyngRequest(). We defined the HTTP method (GET), requested URL ajax/content.html, and callback functionality with the success method, which displays response text in the 'content' <div>.

Loading dynamic content using jQuery slider


In this task, we will learn how to load the content of the page dynamically using jQuery slider.

Getting ready

In this task, we will use the jQuery UI library as well. We can either include the jQuery UI library from http://jqueryui.com/download or from some CDN. Then we will create a folder for our little project, let's say packt1. There will be more folders in our packt1 folder; these are ajax folders for our HTML files loaded via AJAX, CSS for our styles, and js for our JavaScript libraries.

The folder structure will look like the following:

Packt1/
  ajax/
    content1.html
    content2.html
    content3-broken.php
    items.html
  css/ - all stylesheets
  js/
    ui/ - all jQuery UI resources
    jquery-1.4.4.js
  index.html

How to do it...

Since everything is set, we are ready to start.

  1. We will start with basic HTML layout and content. This part already includes a link to our CSS given from the jQuery UI library. We can save it as index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Ajax using jQuery</title>
    
      <link href="css/ui-lightness/jquery-ui.custom.css" 
        rel="stylesheet" />
    </head>
    <body>
    
    <div class="demo">
      <div id="tabs">
        <ul>
          <li><a href="#tabs-1">Home</a></li>
          <li><a href="ajax/content1.html">Books</a></li>
          <li><a href="ajax/content2.html">FAQ</a></li>
          <li><a href="ajax/content3-broken.php"> 
            Contact(broken) </a>
          </li>
        </ul>
        <div id="tabs-1">
          This content is preloaded.
        </div>
      </div>
    </div>
    </body>
    </html>
  2. Now we will add JavaScript libraries and their functionality:

    <script src="js/jquery-1.4.4.js"></script>
    <script src="js/ui/jquery-ui.min.js"></script>
    <script>
    $(function() {
      $("#tabs").tabs({
        ajaxOptions: {
          success: function(){
            $("#slider").slider({
              range: true,
              min: 1,
              max: 10,
                values: [1,10],
              slide: function( event, ui ) {
                $("#amount").val(ui.values[0] + " to " +   
                  ui.values[1]);
                },
              change: function(event, ui) {
              var start = ui.values[0];
              var end 	= ui.values[1];
                $('#result').html('');
                for(var i = start; i <= end; i++){
                  var $item = $('<h3></h3>');
                  $item
                    .load('ajax/items.html #item-'+i);
                     .appendTo($('#result'));
                }          }
            });
          },
          error: function(xhr, status, index, anchor) {
            $(anchor.hash).html(
              "Couldn't load this tab. We'll try to fix
                this as soon as possible. " +
              "If this wouldn't be a demo." );
          }
        }
      });
    });
    </script>
  3. Our index.html page is ready and we can create files that are going be loaded in our page via AJAX.

    The first page will be ajax/content1.html. This page will contain a slider with extra functionality, which will be described later.

    <h2>Slider</h2>
    <p> 
      <label for="amount">Displaying items:</label> 
      <input type="text" id="amount" style="border:0; 
    color:#f6931f; font-weight:bold;" value="none" /> 
    </p> 
    <div id="slider"></div>
    <div id="result"></div>
  4. The second page will be ajax/content2.html:

    <p><strong>This tab was loaded using ajax.</strong></p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec turpis justo, et facilisis ligula.</p>

    And the last file in our AJAX folder will be items.html:

    <div id="item-1">Item 1</div>
    <div id="item-2">Item 2</div>
    <div id="item-3">Item 3</div>
    <div id="item-4">Item 4</div>
    <div id="item-5">Item 5</div>
<div id="item-6">Item 6</div>
    <div id="item-7">Item 7</div>
    <div id="item-8">Item 8</div>
    <div id="item-9">Item 9</div>
    <div id="item-10">Item 10</div>
  5. Now, as shown in the following screenshot, we have a multi-functional page with four tabs. Three of them are loaded via Ajax and one of them contains a slider. This slider has an extra functionality and every change loads a selected number of items.

How it works...

From the beginning, we started with a simple tab layout with four tabs, using the jQuery UI library. One of them (#tabs-1) was included directly in the index.html file. The jQuery UI library allows us to define ajaxOptions, so that we can load our content via AJAX. The navigation where we find the required content is preceeded by the href attribute of each hyperlink. If this target does not exist, the error method is triggered.

We wanted to have a functional slider on our second tab (named Books). To make it work, we can't initialize it in the $(document).ready() function, because its HTML content hasn't been created yet. We will add slider initialization only when we need it in the success method.

After each change of slider the load() function is triggered. This function loads the content of the given target via AJAX. In our case, we use a more specific selector with the exact ID of the object, which is displayed in our result box.

There's more...

In this task we were using only the basic function load(), but jQuery offers more AJAX methods, as shown in the following table:

$. ajax

Performs an Ajax request

jQuery.post()

Loads data from the server using HTTP POST request

jQuery.get()

Loads data from the server using HTTP GET request

jQuery.getJSON()

Loads JSON data from the server using HTTP GET request

jQuery.getScript()

Loads and executes a JavaScript file from the server using HTTP GET request

See also

Chapter 3, Useful tools using jQuery

Creating an AJAX shopping cart using MooTools


This task will show us how to use Ajax with MooTools JavaScript framework. We will build a shopping cart with a drag-and-drop functionality. After each UI interpretation to add a new item to the shopping cart, we will send an HTTP POST request to the server.

Getting ready

MooTools is available for download at https://mootools.net/download or in Google's CDN. For communication between the server and client we will create a new file in our ajax folder, for example, addItem.php:

<?php 
if($_POST['type']=='Item'){
	echo 'New Item was added successfuly.';
}
?>

After creating this dummy PHP file, we are ready to proceed to the programming part of this task.

How to do it...

  1. We will begin, as we usually do, with HTML layout to include MooTools library:

    <!doctype html>
    <html>
    <head>
      <title>Ajax Using MooTools</title>
    </head>
    <body>
      <div id="items">
        <div class="item">
        <span>Shirt 1</span>
        </div>
        <div class="item">
        <span>Shirt 2</span>
        </div>
        <div class="item">
        <span>Shirt 3</span>
        </div>
        <div class="item">
        <span>Shirt 4</span>
        </div>
        <div class="item">
        <span>Shirt 5</span>
        </div>
        <div class="item">
        <span>Shirt 6</span>
        </div>
      </div>
      
      <div id="cart">
        <div class="info">Drag Items Here</div>
      </div>
    
      <h3 id="result"></h3>
    
      <script src="js/mootools-core-1.3-full.js"></script> 
      <script src="js/mootools-more-1.3-full.js"></script> 
      <script src="js/mootools-art-0.87.js"></script> 
    </body>
    </html>
  2. In this task we have to provide our own CSS styles:

    <style>
    #items  {
      float: left; border: 1px solid #F9F9F9; width: 525px;
    }
      item {
        background-color: #DDD;
        float: left;
        height: 100px;	
      margin: 10px;
        width: 100px;
        position: relative;
      }
      item span {
        bottom: 0;
        left: 0;
        position: absolute;
        width: 100%;
      }
    #cart {
      border: 1px solid #F9F9F9;
      float: right;
      padding-bottom: 50px;
      width: 195px;
    }
    #cart .info {
        text-align: center;
    }
    #cart .item {
      background-color: green;
        border-width: 1px;
        cursor: default;
      height: 85px;
        margin: 5px;
        width: 85px;
    }
    </style>
  3. When the look of our UI fits our expectations, we can start JavaScript:

    <script>
    window.addEvent('domready', function(){
        $('.item').addEvent('mousedown', function(event){
            event.stop();
            var shirt = this;
            var clone = shirt.clone()
          .setStyles(shirt.getCoordinates())
          .setStyles({
                opacity: 0.6,
                position: 'absolute'
             })
          .inject(document.body);
    
            var drag = new Drag.Move(clone, {
                droppables: $('cart'),
                onDrop: function(dragging, cart){
                    dragging.destroy();
    
            new Request.HTML({
              url: 'ajax/addItem.php',
              onRequest: function(){
              $('result').set('text', 'loading...');
                console.log('loading...');
              },
              onComplete: function(response){
                $('result').empty().adopt(response);
                console.log(response);
              }a
            }).post('type=shirt');
    
                   if (cart != null){
                        shirt.clone().inject(cart);
                        cart.highlight('#7389AE', '#FFF');
                    }
                },
                onCancel: function(dragging){
                    dragging.destroy();
                }
            });
            drag.start(event);
        });
    });
    </script>
  4. Once we save our code, our shopping cart is ready. The result is as follows:

How it works...

The $(document).ready function is performed by binding a domready event to the window object. For each item, we are add a mousedown event, which contains the whole procedure of adding each item in the cart, using the Drag object and clone() function.

To communicate with the server we use the Request.HTML method and send it with the HTTP post method with post variable type. If the variable type is equal to the string shirt, it means a new item was added to the cart and the information box result was updated to 'New Item was added successfully'.

There's more...

Class Request represents the main class, which deals with an XMLHttpRequest:

var myRequest = new Request([options]);

An example of the preceding template is as follows:

var  request = new Request({
  url: 'sample.php', data: { sample: 'sample1'},
    onComplete: function(text, xml){
      $('result').set('text ', text);
}

In the core of the MooTools library, the Request class was extended to Request.HTML and Request.JSON.

Request.HTML is an extended Request class specially made for receiving HTML data:

new Request.HTML({
  url: 'sample.php',
  onRequest: function(){
    console.log('loading...');
  },
  onComplete: function(response){
    $('result').empty().adopt(response);
  }
}).post('id=242');

We can use the post or get method:

new Request.HTML([options]).get({'id': 242});

As the most effective practice of communication between client and server, we can use Request.JSON to receive and transmit JavaScript objects in JSON format.

var jsonRequest = new Request.JSON({
url: 'sample.php', onSuccess: function(author){
  alert(author.firstname);   // "Milan".
  alert(author.lastname);   // "Sedliak"
    alert(author.company);     // "Skype"
}}).get({bookTitle: 'PHP Ajax CookBook', 'bookID': 654});

Building an AJAX login form using prototype.js


The last JavaScript framework in this chapter is prototype.js. In this task, we will make a simple login form with AJAX functionality. We will have a look at the most frequently used practices for prototype.js with AJAX.

Getting ready

We can download prototype.js from http://www.prototypejs.org/download. Then, just save it in the js folder. To finish this task we will need to have the Apache Server running.

How to do it...

  1. First, let's create our dummy .php file, login.php:

    <?php 
    if($_POST['username']==$_POST['password']){
      echo 'proceed';
    }
    ?>

    Then, we can continue with our HTML layout.

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
      <form id="loginForm">
        <label for="username">Username: </label>
        <input type="text" id="username" name="username" />
        <br />
        <label for="password">Password:</label>
        <input type="password" id="password"  name="password"/>
        <br /><br />
        <input type="submit" value="Sign In" id="submit" />
      </form>
    </body>
    </html>
  2. When the HTML is set, we will define our JavaScript:

    <script src="js/prototype.js"></script>
      
    <script>
      
    $('submit').observe('click', login); 
      
    function login(e) {
      Event.stop(e);
      
      var url = "ajax/login.php"; 
      
      new Ajax.Request(url, {
        method: 'post',
        parameters: { 
          username: document.getElementById('username').value,
          password: document.getElementById('password').value 
        },
        onSuccess: process,
        onFailure: function() { 
          alert("There was an error with the connection"); 
        }
      });
    }
      
    function process(transport) {
      var response = transport.responseText;
      if(response == 'proceed'){
        $('loginForm').hide();
        var my_div = document.createElement('div');
        my_div.appendChild(document.createTextNode("You are logged in!"));
        document.body.appendChild(my_div);
      }
      else
        alert("Sorry, your username and password don't match.");  
    }
    </script>

How it works...

As you can see in the source, we observe a new click event on the button element with ID submit, which is the submit button in our login form. The login() function is triggered by the click event. The default behavior of the submit button was replaced by Event.stop(event), and so triggering the HTTP request was disabled. An AJAX request was created instead. Ajax.Request is the basic class for using AJAX in prototype.js. We are using the post method with two parameters (username and password). If the request was successful and the response text from login.php was proceed we were successfully logged in.

There's more...

prototype.js extends the Ajax.Request object to a few more, as discussed:

  • Ajax.Updater:

    Ajax.Updater is an extension of the Ajax.Request object, which performs an AJAX request and updates the container, based on response text:

    <div id="container">Send the request</div>
    
    <script>
    $('submit').observe('click', login);
    function login(){
      new Ajax.Updater(
        'saladContainer', 'login.php', { method: 'post' }
      );
    })
    </script>
    
  • Ajax.PeriodicalUpdater:

    In the case that we need to update our content at regular intervals, we can use periodical updater:

    new Ajax.PeriodicalUpdater('items', '/items', {
      method: 'get', frequency: 3, decay: 2
    });

    Frequency represents the periodicity (in number of seconds) of updating the content. In the preceding code snippet, our content will be updated every 3 seconds.

  • Ajax.Responders:

    Ajax.Responders represents a repository of global listeners that monitor all AJAX activity on the page:

    Ajax.Responders.register(responder)
    Ajax.Responders.unregister(responder)

    With responders we can easily track how many AJAX requests are active on our page.

    Ajax.Responders.register({
      onCreate: function() {
        Ajax.activeRequestCount++;
      },
      onComplete: function() {
        Ajax.activeRequestCount--;
      }
    });
Left arrow icon Right arrow icon

What you will learn

  • Understand Basic form validation and form handling tools Learn Debugging and troubleshooting techniques to make your site perform even quicker Integrate Web 2.0 APIs for Flickr, Picasa, Facebook and Twitter Build chat application using Comet technology Write optimized code using Ajax asynchronous calls to improve website responsiveness Implement best practices to build SEO-friendly websites Become a skilled iPhone app developer using Ajax

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 08, 2011
Length: 340 pages
Edition :
Language : English
ISBN-13 : 9781849513098
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 08, 2011
Length: 340 pages
Edition :
Language : English
ISBN-13 : 9781849513098
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 136.97
PHP jQuery Cookbook
$43.99
Responsive Web Design with HTML5 and CSS3
$43.99
PHP Ajax Cookbook
$48.99
Total $ 136.97 Stars icon
Banner background image

Table of Contents

9 Chapters
AJAX Libraries Chevron down icon Chevron up icon
Basic Utilities Chevron down icon Chevron up icon
Useful Tools Using jQuery Chevron down icon Chevron up icon
Advanced Utilities Chevron down icon Chevron up icon
Debugging and Troubleshooting Chevron down icon Chevron up icon
Optimization Chevron down icon Chevron up icon
Implementing Best Practices to Build Ajax Websites Chevron down icon Chevron up icon
Ajax Mashups Chevron down icon Chevron up icon
iPhone and Ajax Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(5 Ratings)
5 star 60%
4 star 0%
3 star 20%
2 star 20%
1 star 0%
Kindle Customer Apr 09, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently finished reading my first "cookbook" style programming book: PHP Ajax Cookbook: This is my first cookbook review, so I thought I'd start by clarifying what this is and is not. It is not a textbook-style book, similar to "Learn Ajax in 21 days". It is also not a reference book that you can sit on your bookshelf and pull down when you need to look something up. It's a survey of a wide variety of basic techniques that can be implemented with Ajax techniques and how they're done. You should be familiar with both PHP, JavaScript, and CSS before picking this up, or you will get REALLY lost.With that said, I thoroughly enjoyed this book. I recommend going ahead and downloading the source code files (there's a registration, but it's painless). Some examples are fairly lengthy, and you'll want the source code handy. In fact, this book is between 30% and 50% code!The layout of the book is chapter around a main concept. Each chapter has several sections, each devoted to a single example. For every example, several things are provided: an overview of what the goal is, the code to implement a simple example (enough for you to build a real-world product), an explanation of how it works, often nearly line-by-line, and a "There's more..." section that gives you additional resources and ideas.Chapter 1 gives you a quick orientation to JavaScript libraries that will make doing Ajax a lot easier. The practical examples will give you a sense of the style of jQuery, Ext JS, MochiKit, Dojo, YIU, MooTools, and prototype.js. You'll have to learn them on your own, but you will get a sense of how they work, and what they're like. The authors use jQuery for the rest of the book. It's worth using one of these libraries, because raw JavaScript makes doing Ajax calls awkward. The elegance these provide for coding is worth the effort.Chapter 2 goes over basic Ajaxy things. Form validation (really just jQuery form validation), autosuggest (similar to Google's search), creating a multi-step form wizard, file updload, multi-file upload using Ajax + Flash, implementing a 5-star rating system, etc. The purpose of this chapter is to expose you to how easy Ajax effects are to implement. It's generally a simple combination of CSS and small bits of jQuery that have a powerful effect.Chapter 3 looks heavily at the extensions that are available for jQuery. Often there are several options (with links provided) of which one is chosen for demonstration purposes. If you're interested in using jQuery, this chapter will provide you with a wealth of resources to give you ideas for cool things you can do. Examples include an image slider, a Lightbox image loader, a shopping cart, and data sorting/filtering.Chapter 4 pushes this further, showing how to create a chat system and how to decode a simple CAPTCHA using the HTML5 canvas element. These examples are very detailed and will give you a solid idea of the power that is present. One of the key things you will learn is how to do this without using excessive Ajax calls. You can easily kill a server's bandwidth with the "obvious" solution. Thi shows you how to avoid that.Chapter 5 goes in a completely different direction: debugging. It discusses using Firebug and FirePHP, including the details of how to set both up, in Firefox. It discusses the IE developer toolbar. Memory leaks are dealt with in detail, as are how to deal with various timing issues that can crop up. If you've done PHP/HTML/JavaScript debugging, you already know how annoying this can be. I picked up several tricks, and I thought I was Firebug-savvy!Chapter 6 discusses optimization issues, including the use of Yslow. It's very easy to make an Ajax site that works poorly, so these tips will help a lot. It discusses where to place sections of code, caching concerns, etc. Most of these are tips you can find in numerous other sites, but they are nicely consolidated, here.Chapter 7 discusses other best practices, including security concerns and how to address SEO concerns when dealing with dynamic content. Having SEO friendly content means having static content with fixed URL's for each content item. Having Ajaxy content is basically the opposite. This chapter has numerous tips on how to satisfy both requirements, so users can easily find your content.Chapter 8 discusses ways to use various services that have API's, such as Flickr, Twitter, and Google Maps. These are techniques that can make a website "pop", such as getting a list of nearby restaurants with a map, a customized twitter feed, or image search. As usual, you won't learn the full API, but you will learn the basic techniques for leveraging these APIs on your own site.Chapter 9 was the most surprising for me. Building iPhone apps using html, Ajax, and PhoneGap. It can also be used for building Android apps, but the authors focused on the iPhone. PhoneGap is a tool that lets you compile an HTML/Ajax page into a native app for the iPhone, Android, etc. It's a tool I'd never heard of, but offers a huge amount of options for the mobile development market.I enjoyed the book. There's a TON of information here, and the timing was ideal, as I'll be designing a new PHP/Ajax app for my job at work. Topics range from basics of using a framework, to quality layouts, to security concerns. The details will be found elsewhere, but the core ideas are all in here.
Amazon Verified review Amazon
Daedalus Mar 23, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book focuses primarily on the client-side implementations of Ajax tasks common for almost any web 2.0 application. PHP examples are included where necessary for server interaction.Most of the examples use jQuery but the book does touch on some other popular JavaScript frameworks including jQuery, Ext JS, MochiKit, Dojo, and YUI library and compares their strengths and weaknesses in different scenarios. There is an entire chapter devoted to the most useful jQuery and jQuery UI plugins including tab navigation, image animation and effects, lightbox, datepicker.The book begins with fairly trivial examples such as form validation, autosuggest and rating systems but gradually increase in complexity to using canvas for captchas and building two way communication systems using comet. There are also examples of how to implement JavaScript and PHP code to interact with many of the popular webservices online (eg. Google Maps, Facebook, Flickr, IP/Country Lookup, etc.) to create effective mashup sites.Interestingly, they also cover iPhone webapp development from an HTML5 perspective and also using the PhoneGap framework to access mobile phone hardware features from a web development context. I guess this is a sign of the times and the pervasiveness of the iPhone...It includes chapters on tools and techniques for debugging JavaScript and techniques for optimizing your code for faster page load times. For someone getting into JavaScript development, this section will be extremely beneficial. Veterans may already be familiar with most of the debugging tools suggested but I learned several cool tricks here.In most cases, the samples are not watered down with heavy CSS or markup. This allows the code to speak for itself and makes the examples fairly easy to understand if you have a sufficient programming background. This is as a cookbook should be. All in all, it's a great reference of recipes for many of the common features expected in a web 2.0 application. I'm sure I'll be referring back to this for future projects!
Amazon Verified review Amazon
Ivan Ilijasic Mar 03, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've been in PHP development for more than 10 years and this book is really useful material.I could recommend it to beginners and experienced developers. From my point of view, there are three types of developer books - complete byte-to-byte fat books, introduction books and cookbooks. I want my cookbook to have useful and simple to use recipes. This book fullfilled my expectations.Chapter 1 tells about different mainstream JS libraries and framework. You cannot expect from this kind of a book to cover so much information but it's useful to see what is out there. At least you can find useful links or create a list of JS frameworks you should look for.Almost all the rest this book is all about PHP and jQuery. It has lots of recipes that cover typical developer scenarios. How to create form validation, file upload, dynamic containers such as tab navigators or slideshow, pageless pagination but it goes futher. There are some simple examples how to create drag & drop functionality, sorting, filtering. All common functionalities and I like to see them in one book.There are some interesting chapters about debugging PHP / JS applications and about best practices how to secure your Ajax applications. Perhaps it would be useful to see addtional pages about PHP security. I know this is a book about PHP and Ajax, not just about PHP but pages about security can be pure gold. Fortunately, this book offers excellent information about online resources.Mashups chapters talks about usage of common web services. There is one really useful chapter how to create a Google map search in specified radius - how to use PHP, Ajax, Google Map API and MySql. Just like chapter 1 it doesn't go in many details but it gives you enough useful links and library references.Since I recently started developing HTML mobile apps, I was very pleased to see this topic in this cookbook. That's why it's really nice to see last chapter about PhoneGap.Recipes in this cookbook are not offering fancy CSS examples with lot of graphics. They are offering pure ideas and solutions.That's really what every PHP developer should have on his shelf. I would definitely recommend this book. Simple but veeeery useful.
Amazon Verified review Amazon
Alex F Apr 04, 2012
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The sub-title for this book, "Over 60 simple but incredibly effective recipes to Ajaxify PHP websites" is accurate, and if that is what you are looking for, then this book does a good job delivering on it. Many programming training books take you through a single project from start to finish to help the reader gain a deeper understanding of the language or techniques being employed. This is not that style of book. Although the entire volume does flow together for the most part, it seems to work better as a reference to solve a particular problem, or as the title would suggest, a cookbook where you pick the recipe for the task you wish to complete.I feel it is important to note that a book like this is not for novices. Before reading this book, the reader should already be comfortable with PHP and the server end of their application. The reader would hopefully have a basic understanding of JavaScript structure or at least the jQuery JavaScript library which is used for the vast majority of examples in this book. Without this understanding going in, I fear that the reader will be faced with a great deal of confusion and frustration when trying to understand and learn from the examples given. As some newbies may not be aware, it is necessary to employ JavaScript to use AJAX functionality.Chapter 1 uses a variety of JavaScript libraries to complete an assortment of AJAX tasks commonly requested in modern web applications. It helps to show some of the strengths and weaknesses of the different libraries. After chapter 1, the jQuery library will be used for all examples.Chapter 2 shows possible solutions to several common tasks using the jQuery library and AJAX functionality such as form validation, auto-suggest, file uploading, a rating system and pagination. Many of the solutions simply employ the use of a jQuery plug-in to do the heavy lifting. This is fine if your goal is to accomplish the task at hand in an efficient manner. Although each section contains a "How it works..." paragraph, if your goal is to learn and understand WHY it works, this chapter will leave you wanting more.Chapter 3 continues where chapter 2 ended and addresses tasks such as tool tips, auto-complete, tabbed navigation, an image slider, using a lightbox, drag and drop functionality, a simple shopping cart, and some animation. As in chapter 2, you will not really be doing any programming. You will be using jQuery plugins and the jQuery UI (User Interface) library to accomplish these tasks. Again, there is not anything wrong with this approach if you simply want to add some AJAX functionality to your website.Chapter 4 covers some more advanced AJAX utilities that will be used on fewer websites such as using a Comet server for live chat, using Google's API to create charts, a very basic OCR (Optical Character Recognition) with very limited practical use, displaying data.Chapter 5, 6 and 7 seems to take a departure from the previous intended audience. I found these chapters to be filled with useful techniques for debugging and optimizing the JavaScript used for the AJAX functionality. They go over more advanced techniques beyond simply making a plugin work. If the reader does not have an adequate understanding of JavaScript and AJAX by this point, I fear that this chapter would largely be lost on them.Chapter 8 gives a very brief overview of web services and the most popular formats of them in use at this time. It gives examples of one way to access the API (Application Programming Interface) for Flickr, Twitter, and a few of Google's web services. Some of the examples use PHP on the server side (using CURL), and some use a client side JavaScript interface. I feel that it is important to note that the examples shown are not the only ways to interact with these API's. I do have to point out that there is one rather interesting subject covered in this chapter. The book shows an example of how to locate addresses (retrieved from your database) within certain radius of a certain location using Google's map API.Chapter 9 covers some basics to keep in mind when beginning to create a version of your web application targeting mobile devices, specifically the iPhone. It briefly covers a couple mobile JavaScript frameworks that assist with this task. This chapter also covers a service called PhoneGap, which allows conversion of HTML, CSS and JavaScript into a native phone application.In summary, when deciding whether this is a good book for you to purchase, you must really examine what it is that you hope to learn. If you have a solid grasp on the PHP needed for your application, have a basic knowledge of JavaScript and simply want to add some cool effects to your site, then you will probably be very pleased with this book. If you choose to learn more about JavaScript and AJAX from other resources, then the later chapters will also be of use to you. If you are brand new to JavaScript and AJAX, or if you want to build a deep understanding of JavaScript, AJAX or jQuery with the intention of being able to build customized functionality for your website, then this is probably not the best book for you. There are many fine publications that can take you from novice to adept programmer, but that is not the goal of this book. After all, you don't read a cookbook to learn how to cook.Disclosure: I was provided with a free copy of this book in return for reviewing it.
Amazon Verified review Amazon
webdev Nov 23, 2012
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Very disappointed with this book. If you're not already familiar with jQuery, this book will teach you some very poor coding habits, like building placeholder blocks of HTML into your markup rather than generating them dynamically with JS, not to mention the bloated and unnecessary code to do simple things. The PHP in the book is also disappointing, providing almost no server side functionality, and even less in regards to "practical" server side functionality.None of these recipes provide anything of a dynamic nature, relying mostly on static chunks of HTML in place of server side data.Formatting is also a mess. Code is scattered and in some cases, missing.Also, at least 1/3 of the source code is omitted from the publisher's downloadable files. It's sad when books like this pass a publisher's standards.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.