jQuery 1.3 with PHP

By Kae Verens
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Introduction and Overview

About this book

To make PHP applications that respond quickly, avoid unnecessary page reloads, and provide great user interfaces, often requires complex JavaScript techniques and even then, if you get that far, they might not even work across different browsers! With jQuery, you can use one of the most popular JavaScript libraries, forget about cross-browser issues, and simplify the creation of very powerful and responsive interfaces – all with the minimum of code.
This is the first book in the market that will ease the server-side PHP coder into the client-side world of the popular jQuery JavaScript library.

This book will show you how to use jQuery to enhance your PHP applications, with many examples using jQuery's user interface library jQuery UI, and other examples using popular jQuery plugins. It will help you to add exciting user interface features to liven up your PHP applications without having to become a master of client-side JavaScript.

This book will teach you how to use jQuery to create some really stunning effects, but without you needing to have in-depth knowledge of how jQuery works. It provides you with everything you need to build practical user interfaces for everything from graphics manipulation to drag-and-drop to data searching, and much more. The book also provides practical demonstrations of PHP and jQuery and explains those examples, rather than starting from how JavaScript works and how it is different from PHP.

By the end of this book, you should be able to take any PHP application you have written, and transform it into a responsive, user-friendly interface, with capabilities you would not have dreamed of being able to achieve, all in just a few lines of JavaScript.

Publication date:
October 2009


Chapter 1. Introduction and Overview


This book is a general overview of how to take advantage of jQuery's ease-of-use to make your PHP applications more "snappy" on the client side.

The book is aimed at the PHP developers who usually don't write client-side JavaScript, and would like an example-based introduction demonstrating a wide variety of integrations between server-side and client-side code.

For years, JavaScript (the language that jQuery is written in) has been seen as a "toy" language. However, the pervasiveness of Ajax has allowed it to break out of the client side and become an essential tool for all serious web application developers.

Ajax is a tool used by client-side code to contact the server and get or send data without needing to reload the entire page. It's used to update part of the page, or to retrieve data for a JavaScript application, or to send data to the server. Ajax stands for Asynchronous JavaScript And XML. However, the XML part is optional, and is often replaced with plain text or another data format such as JSON (explained later in this chapter).

This book will demonstrate how combining server-side PHP with client-side jQuery can make JavaScript much more useful than just for "form checking".

It is assumed that you are a server-side web application developer who wants to take a step into the client side and learn how to use JavaScript to make your applications more efficient and exciting for the client.

To be very clear about it, this book is not about PHP, and it is not about jQuery—it is about how to work with both PHP and jQuery. This book will teach you how to use jQuery to create some really cool effects, but without you needing to have in-depth knowledge of how jQuery works.

With this book, we are more interested in providing some practical demonstrations of PHP and jQuery with explanations, than in getting right down into the guts of how JavaScript works and how it is different from PHP.

After reading this book, you will have seen and built a wide variety of example applications. This would certainly be enough to immensely change how your current PHP applications work.

Each chapter in this book is dedicated to a specific subject, and will usually involve building a practical example, which you can use in your day-to-day work.


Expected developer skills

To read and work with this book's contents, it is expected that you are already a PHP developer with a basic understanding of JavaScript, and experience of HTML and CSS.

The book will not cover jQuery in depth—there are other books available that are dedicated to it. This book is designed to help a PHP developer write some immediately-useful client-side applications without needing weeks of study.

You need to understand how CSS selectors work. A CSS selector is the part of CSS that goes to the left of the { character. jQuery selects elements by using CSS selectors, and it's an extremely powerful way of choosing the elements that you wish to work on.

HTML is a must-have for every web developer. I think we can safely say that your HTML skills are not lacking, especially because that's the environment that PHP is usually working in.

Your PHP is expected to be good. You don't need to know everything about PHP, but it is beneficial if you have already written a few full PHP projects yourself and are comfortable with reading code and quickly understanding what it does.

You are not expected to be a good JavaScript writer. It will be useful, but the book is written such that beginners should not have a problem understanding how it all fits together. As a PHP developer, you will find that JavaScript is similar to PHP anyway, so you should not have a problem reading the examples and understanding them.


Differences between PHP and JavaScript

Syntactically, JavaScript and PHP are very similar. They're both loosely typed languages, and you can choose whether to write in an object-oriented or functional way.

However, there are some interesting differences, which a PHP developer may not have encountered before.

One example is asynchronous events. In PHP, everything happens linearly—when you call a function, the result is returned before the next line runs. However, in JavaScript, you can call some functions and have them return their results to a "callback" function a few seconds later.

The most obvious example is Ajax: when you request information from the server, it is bad design to have everything freeze while you're waiting for the data to return. Instead, you write your script such that the data is sent, and you carry on with other stuff. When the data returns, you handle it with another function.

This poses some interesting problems, such as race conditions, and how to pass variables through to remind the script what it was supposed to be doing when the Ajax request was fired.

A race condition occurs when one resource is accessed by two separate operations at the same time and one of them changes the value. This is because computers always do things one after the other; the change to the value will happen either before or after the other operation. This uncertainty means that in asynchronous systems, such as networks, care must be taken to make sure that things happen in the right order.

Race conditions are not a language-specific problem. They can happen anytime—say, when you open a file, work on it, and close it, only to find that at the time you were working on it, someone else came in and changed the name of the file. There are many ways of solving these problems depending on the nature of the case. The most common solution is to use a "lock", where if an operation is to write into a value, it will first "lock" it (usually by setting a flag variable or creating a .lock file) before it reads it, and then will "unlock" it (remove the file or unset the flag) after it has completed its work.

When an asynchronous function is called and its return value is sent to a callback function, that callback function must be reminded what the caller function was doing, so that it can carry on with it. This can be done using closures. With closures, the callback function is generated by the caller function, and has a copy of the caller's environment, including what variables were set, among other things. Later in the book, you will see some examples of this.


What is jQuery?

jQuery is a JavaScript library that makes it easy to work with the Document Object Model (DOM) of a website. jQuery is not a replacement for JavaScript. It is a JavaScript library, which gives some extra functionality that is not available natively in JavaScript itself.

jQuery is designed to make it easy to create, manipulate, or destroy elements in the document. Manipulation includes animation, CSS effects such as fades, resizes, and so on.

jQuery also makes it very easy to add behaviors to elements. So, you can do things like drag boxes around, have things happen when you hover a mouse cursor over something, have scripts run when a select box is changed, and so on.

All of this can be accomplished in plain JavaScript if you feel the need to write it yourself, but there is no point in re-inventing the wheel. If there is a tool available that makes things easier for you, then you should not do it the hard way.

Besides, handwritten JavaScript tends to be much more verbose than it could be if you used a library, such as jQuery.

As an example, let's say that you want to get all of the <span> elements in a page that are contained in an element with the testme class, and change their contents to the word hi!. Here is the HTML of the example:

    <h1 class="testme"><span>this will change</span></h1>
    <p>this will not</p>
    <p class="testme">this will also not</p>
    <p class="testme"><span>this will change</span></p>
    <a href="javascript:run_test()">do it</a> 

When displayed in a browser, it will look like the following:

When the do it link is clicked, we want the view to change to this:

For the first test, here is how to do it in plain JavaScript. Place this code in the <head> section of the previous HTML code.

  function run_test(){ 
    var i,j,els,els2; 
    for(i in els){
      if(!/(^| )testme( |$)/.test(els[i].className))continue;
      for(j in els2){ 

It would be difficult to write this more compactly in pure JavaScript, but it's still too complex to be maintainable. Really, if you saw that for the first time, would you know straight away what it was trying to do? And, can you be sure that it will work in all browsers?

With jQuery, you can write a much more readable piece of code. Replace the above JavaScript with this:

<script src="../jquery.min.js"></script> 
  function run_test(){ 
    $('.testme span').html('hi!'); 

I know what you're thinking—where's the rest of it? Well, that's the whole thing. It very concisely strips away the confusion and all that you end up with is a very clear piece of code, which can be understood immediately. The problems of cross-browser compatibility are also solved by using the jQuery library. You can be sure that the new script will work as planned in all major browsers.

The example links to the jQuery library file, jquery.min.js, which you can download from http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js.


Why jQuery?

There are many libraries and frameworks available for JavaScript, including MooTools, Ext, Dojo, and Prototype. So, why use jQuery and not others? Here are some of the reasons:

  • jQuery has a huge number of plugins available for everything you could imagine wanting to do online

  • The information on the jQuery site is extremely well documented, with many examples

  • jQuery does not extend the elements that it works on, which means that JavaScript such as 'for(i in el){...}' will still work

  • jQuery's CSS selector engine, Sizzle, is arguably the most complete and the quickest available

jQuery is available at Google's Ajax Libs CDN (http://code.google.com/apis/ajaxlibs), so probably you already have it in your browser's cache.

There are benefits and detractors to everything. So in the end, it's a matter of taste.

In my case, I was using MooTools before I turned to jQuery, but MooTools' habit of extending every element it touches was interfering with my own code, so I had to replace it.

I chose jQuery because the body of knowledge on it was very large (every second article on JavaScript blogs appears to mention jQuery), it's impressively clean to work with, and there are a massive number of plugins available.

Also, because jQuery is used in so many large projects (a few of which are mentioned in the Projects that use PHP and jQuery section of this chapter). If you have ever worked on any of those projects, you will find that the skills you learned on them are transferable to other projects using jQuery.


How does jQuery fit in with PHP?

Traditional network applications have both server and client side, each of which is a program in its own right.

As a very simple example, consider a networked game, where you are playing against a number of other people. The server holds a database of the present positions of everything, and decides if something is allowed or not. On each player's computer, there is a client, which gets data from the server and displays it in a user-friendly way, such as rendering a 3D world that you can move around in. The client is smart enough that if you try to do something that is obviously not allowed, such as run through a wall, then it won't let you.

It would be silly if a 3D screen was generated on the server and was sent to the client 24 times per second. And it would be awkward if you tried to do something like walk through a wall, and had to wait for the server to decide if it was allowed or not.

However, in a pure PHP environment, that's exactly what has been happening—the server generates absolutely everything that the client displays. If an element needs to be removed from a table, for example, then the server needs to be told, so that it can give the client the new view. If you try to do something illegal, such as submit a blank form where an email address is required, then pure PHP applications will let you do that, wasting time and server resources.

However, using JavaScript, and especially using Ajax, the client side is no longer a "dumb terminal" for the server. We can write applications fully on the client side, if we wish, using the server purely as a database. This book will demonstrate ways to work towards that.

Although Ajax stands for Asynchronous JavaScript And XML, it's a misnomer. This is because in most cases, no XML is involved (either plain HTML or data in JSON format is usually used). Ajax allows a client to open a data channel between itself and the server, allowing JavaScript to load new information from the server without needing to refresh the entire screen.

JSON stands for JavaScript Object Notation. It is a simple data storage format, which can be used to transfer information about strings, numbers, arrays, and associative arrays between various languages. It is much smaller than XML, and is much easier to transform because there is a direct relationship between the text format and the internal data format. It can be used in both PHP and JavaScript. It's based on how JavaScript is actually written, so it can be natively compiled into an object in JavaScript.

In JavaScript, you can create an actual data object from JSON by simply "eval"ing it (or using the new json.decode function in newer browsers). In PHP, you can use the json_decode and json_encode functions to convert from and to JSON.

With Ajax, we can provide a client-side experience, which had only been possible beforehand using external plugins, such as Java or Flash. It could not safely be assumed that these plugins were available on the client. Every major browser now supports Ajax, so there are much fewer reasons to rely on proprietary technology these days.

jQuery simplifies Ajax. With pure Ajax, you need to do low-level stuff like create an XMLHTTPRequest object (taking care of cross-browser incompatibilities), set callbacks, check response values, and so on. With jQuery, all you need to do is use $.get or one of the other jQuery JSON functions. These functions will take care of the low-level stuff for you.


How to work with the examples

In every chapter of this book, I will provide a few code examples. If you wish to try them out, you will need to replicate the test environment I'm using here.

On my test server, my directory layout (within the public_html directory) is like this:

[... others from various chapters ...]
[... other plugins ...]

You can see that there's a common theme—everything has its own subdirectory. The jQuery library is kept in the root directory, ./php_and_jquery/, along with the jQuery UI library (when we use it). We will discuss where to get these from in Chapter 2, Quick Tricks.

Here is the root directory of my own test server. It shows the libraries we will use throughout the book, and two test directories (9-5 and 9-4):

When creating your own test server, it should end up looking like this.

You can start out with the empty directories. Each chapter will explain what new files to download and where to get them from.

Each of the examples has a number of screenshots, so you can verify your own tests against what my tests display.


Projects that use PHP and jQuery

Here is a small list of projects that use jQuery along with PHP. This illustrates the variety of uses that jQuery is put to.


WordPress (http://wordpress.org/) is probably the best-known blogging software on the net. Recently, the admin dashboard area was given a thorough going over, and is now extremely flexible with the areas you can move around or remove, a navigation menu you can hide at the click of a button, and other improvements. jQuery is used to handle autosaves, word counts, and much more.


RoundCube (http://roundcube.net/) allows you to read your emails online using an application designed to look similar to your normal email client. With jQuery, the engine allows emails to be removed, moved around, and so on, without reloading the whole page.


I'm proud to say that this is one of my own projects. KFM (http://kfm.verens.com/) is a file manager, which allows you to upload, sort, and rename (and more) your files online. You can even edit text files or play media files. The project is designed to look like a desktop file manager, complete with file icons, tree directory, and so on. jQuery is used for most of it.


Drupal (http://drupal.org/) is a Content Management System. Since version 5, jQuery has been included as part of the core. It's more prominently used in some of the modules, but some core functionality, such as story creation is enhanced by allowing text boxes to be re-sized, optional sections to be hidden/shown, and so on.

Now, without further ado, let's get on with the fun stuff.



In this chapter, we discussed what jQuery is, why you would want to use it, and why is it useful to combine it with PHP.

We also saw a list of projects illustrating some uses for combining PHP and jQuery.

In the next chapter, we will look at a few examples of how you can use jQuery immediately to give your site a more "live" feel, without needing to know a lot of JavaScript.

About the Author

  • Kae Verens

    Kae Verens is an owner manager of the web-development company Webworks.ie and is currently secretary of the Irish PHP Users Group. He has been writing in JavaScript since the mid 90s, and in PHP since the late 90s. Kae is the creator of the file management system KFM, the CMS WebME (used by Webworks.ie for over 200 separate clients), and the author of the Packt book jQuery 1.3 with PHP.


    Browse publications by this author
jQuery 1.3 with PHP
Unlock this book and the full library FREE for 7 days
Start now