PHP jQuery Cookbook - Vijay Joshi - E-Book

PHP jQuery Cookbook E-Book

Vijay Joshi

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

As web technology evolves, the gap between desktop applications and web applications continues to vanish. And what better way to bridge that gap, for your own website, than using the best two open source technologies in the market: PHP and jQuery. The power-combo of these two is leading the way in revolutionizing the RIA world. Although they are easy to integrate, finding or figuring out how to do what you want to do is rather arduous.The PHP jQuery Cookbook will be your handy guide with walkthroughs of common integration tasks and problems that will help you master the possibilities available using the PHP and jQuery combo. You will learn quick solutions to necessary tasks to integrate the power of two of the best known and most widely used web technologies of today – PHP on the server side and jQuery on the client side. Glide through the basics and move to advanced topics to create dynamic and interactive web applications with this book in hand.This book covers a wide array of technical aspects of creating an interactive website. Apart from basics of PHP and jQuery, you will go through advanced topics like creating plugins, validating controls, and useful utilities that you will be able to use as stand-alone tools. AJAX, the key technique of browser-server communication is covered in detail. You will also learn to use JSON, which is becoming preferred as a mode of data interchange over XML, both in web applications and web services.The book also covers database interaction, which is an important part of any dynamic web application. You will also gain expertise in debugging JavaScript with the help of useful tools that will save you hours of tedious manual debugging.Most importantly, by using jQuery and PHP together, you will be able to develop applications that are compatible with all major browsers, with no need to write code targeted at specific browsers!

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 319

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

PHP jQuery Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Handling Events with jQuery
Introduction
Executing functions when page has loaded
Getting ready
How to do it...
How it works...
Passing a handler to .ready()
Another method of using .ready()
Multiple .ready() methods
Binding and unbinding elements
Getting ready
How to do it...
How it works...
There's more...
Binding multiple events
Shortcut method for binding
Triggering events
Common event types
Unbinding all events from an element
Adding events to elements that will be created later
How to do it...
How it works...
Removing event handlers with die()
See also
Submitting a form with jQuery
Getting ready
How to do it...
How it works...
There's more...
Controlling form submission
See also
Checking for missing images
Getting ready
How to do it...
How it works...
See also
Creating the select/unselect all checkboxes functionality
Getting ready
How to do it...
How it works...
There's more...
Using selectors
Capturing mouse events
Getting ready
How to do it...
How it works...
Creating keyboard shortcuts
Getting ready
How to do it...
How it works...
There's more...
List of common key codes
See also
Displaying user selected text
Getting ready
How to do it...
How it works...
There's more...
Short method for getting selected text
Dragging elements on a page
Getting ready
How to do it...
How it works...
See also
2. Combining PHP and jQuery
Introduction
Fetching data from PHP using jQuery
Getting ready
How to do it...
How it works...
See also
Creating a query string automatically for all form elements
Getting ready
How to do it...
How it works...
There's more...
serializeArray() method
Not all values are serialized
Name should be provided to elements
See also
Detecting an AJAX request in PHP
Getting ready
How to do it...
How it works...
There's more...
Don't rely on X-Requested-With alone
Sending data to PHP
Getting ready
How to do it...
How it works...
There's more...
Alternative method for $.post()
See also
Aborting AJAX requests
Getting ready
How to do it...
How it works...
See also
Creating an empty page and loading it in parts
Getting ready
How to do it...
How it works...
There's more...
Difference between load and get
See also
Handling errors in AJAX requests
Getting ready
How to do it...
How it works...
There's more...
Parameters passed to error callback
The ajaxError() method
See also
Preventing browser from caching AJAX requests
How to do it...
How it works...
There's more...
Only GET requests are cached
See also
Loading JavaScript on demand to reduce page load time
Getting ready
How to do it...
How it works...
There's more...
Alternative method for getScript
See also
3. Working with XML Documents
Introduction
Loading XML from files and strings using SimpleXML
Getting ready
How to do it...
How it works...
There's more...
Parameters for simplexml_load_file
simplexml_load_string
Using SimpleXMLElement to create an object
More info about SimpleXML and libxml
See also
Accessing elements and attributes using SimpleXML
Getting ready
How to do it...
How it works...
There's more...
Modifying an XML with SimpleXML
Adding elements to an XML
See also
Searching elements using XPath
Getting ready
How to do it...
How it works...
There's more...
More info about XPath
See also
Reading an XML using DOM extension
Getting ready
How to do it...
How it works...
There's more...
Getting child nodes
nodeType, nodeName, and nodeValue
See also
Creating an XML using DOM extension
Getting ready
How to do it…
How it works...
See also
Modifying an XML using DOM extension
Getting ready
How to do it...
How it works...
There's more...
Deleting nodes
See also
Parsing XML with jQuery
Getting ready
How to do it...
How it works...
There's more...
The delegate() method
See also
4. Working with JSON
Introduction
Creating JSON in PHP
Getting ready
How to do it...
How it works...
There's more...
Predefined constants
See also
Reading JSON in PHP
Getting ready
How to do it...
How it works...
See also
Catching JSON parsing errors
Getting ready
How to do it...
How it works...
See also
Accessing data from a JSON in jQuery
Getting ready
How to do it...
How it works...
There's more...
Other AJAX methods for requesting JSON data
Handling errors while requesting JSON
Parsing a JSON
See also
5. Working with Forms
Introduction
Adding input fields dynamically in a form
Getting ready
How to do it...
How it works...
There's more...
Getting values on server side
Searching for user-inputted string in a page
Getting ready
How to do it...
How it works...
There's more...
Search and replace
Checking for empty fields using jQuery
How to do it...
How it works...
There's more...
Validating fields one by one
See also
Validating numbers using jQuery
Getting ready
How to do it...
How it works...
See also
Validating e-mail and website addresses using regular expressions
Getting ready
How to do it...
How it works...
There's more...
References for regular expressions
See also
Displaying errors as user types: Performing live validation
Getting ready
How to do it…
How it works...
See also
Strengthening validation: validating again in PHP
Getting ready
How to do it...
How it works...
There's more...
List of Validate filters
Sanitizing data
See also
Creating a voting system
Getting ready
How to do it...
How it works...
There's more...
Cookie expiration time
See also
Allowing HTML inside text areas and limiting HTML tags that can be used
Getting ready
How to do it...
How it works...
There's more...
PHP tags are stripped too
6. Adding Visual Effects to Forms
Introduction
Creating a Tic-Tac-Toe game with effects
Getting ready
How to do it...
How it works...
There's more...
Exercise—checking for a draw
Informing a user while an AJAX request is in progress
Getting ready
How to do it...
How it works...
There's more...
Using text instead of images
Using overlays to stop a user from interacting with the form
See also
Creating expandable and collapsible boxes (accordion)
Getting ready
How to do it...
How it works...
There's more...
Using different markup for accordion
Fading an element after updating it
Getting ready
How to do it...
How it works...
Floating box on demand
Getting ready
How to do it...
How it works...
There's more...
Important note about animate
Updating items in a shopping cart
Getting ready
How to do it...
How it works...
There's more...
Removing items from the cart
See also
7. Creating Cool Navigation Menus
Introduction
Creating a basic drop-down menu
Getting ready
How to do it...
How it works...
There's more...
Opening menus on click
See also
Creating a menu that changes background on mouse-over
Getting ready
How to do it...
How it works...
See also
Creating an accordion style menu
Getting ready
How to do it...
How it works...
There's more...
jQueryUI Accordion
See also
Creating a floating menu
Getting ready
How to do it...
How it works...
See also
Creating an interface for tabbed navigation
Getting ready
How to do it...
How it works...
Adding more tabs
Getting ready
How to do it...
How it works...
There's more...
Displaying new tab by default
See also
Creating a wizard using tabs
Getting ready
How to do it...
How it works...
See also
8. Data Binding with PHP and jQuery
Introduction
Fetching data from a database and displaying it in a table format
Getting ready
How to do it...
How it works...
There's more...
What is a constructor?
Collecting data from a form and saving to a database
Getting ready
How to do it...
How it works...
There's more...
real_escape_string() function
Return values for mysqli->query()
See also
Filling chained combo boxes that depend upon each other
Getting ready
How to do it...
How it works...
Checking username availability from database
Getting ready
How to do it...
How it works...
There's more...
Alternative methods for implementation
Paginating data for large record sets
Getting ready
How to do it...
How it works...
Adding auto-suggest functionality to a textbox
Getting ready
How to do it...
How it works...
See also
Creating a tag cloud
Getting ready
How to do it...
How it works...
See also
9. Enhancing your Site with PHP and jQuery
Introduction
Sending cross-domain requests using server proxy
Getting ready
How to do it...
How it works...
See also
Making cross-domain requests with jQuery
Getting ready
How to do it...
How it works...
There's more...
About JSONP
See also
Creating an endless scrolling page
Getting ready
How to do it...
How it works...
There's more...
Loading data from other sources
Creating a jQuery plugin
Getting ready
How to do it...
How it works...
Displaying RSS feeds with jQuery and PHP
Getting ready
How to do it...
How it works...
See also
A. Firebug
Introduction
Inspecting elements
How to do it...
How it works...
There's more...
Plugins for firebug
See also
Editing HTML and CSS
How to do it...
There's more...
Changing style for a specific element
Debugging JavaScript
How to do it...
There's more...
Debugging in a nutshell
Inspecting AJAX requests
Web developer toolbar
Index

PHP jQuery Cookbook

PHP jQuery Cookbook

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2010

Production Reference: 1081210

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-849512-74-9

www.packtpub.com

Cover Image by Vinayak Chittar ( <[email protected] >)

Credits

Author

Vijay Joshi

Reviewers

Anis Ahmad

Md. Mahmud Ahsan

Joe Wu

Shameemah Kurzawa

Acquisition Editor

Chaitanya Apte

Development Editor

Neha Mallik

Technical Editors

Mohd. Sahil

Hithesh Uchil

Editorial Team Leader

Aanchal Kumar

Project Team Leader

Ashwin Shetty

Project Coordinator

Michelle Quadros

Proofreader

Mario Cecere

Indexer

Hemangini Bari

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

Vijay Joshi is a programmer with over six years of experience on various platforms. He discovered his passion for open source four years ago when he started playing with PHP on a hobby project after completing his Masters in Computer Applications. Vijay is a professional web developer now and prefers writing code ONLY in open source (but that does not always happen, unfortunately!). He switches hats as needed—he is full-time lead programmer at Philogy, independent consultant for a few selected companies where he advises them on a variety of Internet-based initiatives, and still remains an active blogger at http://vijayjoshi.org.

Besides his work, he enjoys reading, trekking, and sometimes getting obsessed with fitness.

Writing a book is a long and complicated task which requires the support and coordination of many people. I am thankful to the entire team at Packt, especially Michelle, Chaitanya, and Neha for being so cooperative and patient with me.

This book is dedicated to all open source developers, contributors, and enthusiasts around the world who have made PHP and jQuery the leading programming tools in their niche. A big thank you to you guys. I am feeling both proud and excited to be able to contribute to the community that gave me so much to learn.

On a personal note, I would like to thank my parents, my brother Ajay, and Sheethal for their support and encouragement.

A special thanks to Ravindra Vikram Singh for helping me get started on this project.

About the Reviewers

Md. Mahmud Ahsan graduated in Computer Science & Engineering from the International Islamic University Chittagong (IIUC) in Bangladesh. He is a Zend Certified Engineer and expert in developing web applications, Facebook applications, Mashup applications, and iPhone-native applications. Besides his full time job, he blogs at http://thinkdiff.net and writes articles on different technologies, especially Facebook applications development. He lives in Bangladesh with his wife Jinat.

Currently, Mahmud works as a Software Engineer (remote developer) in i2we inc. (867 Avalon, Lafayette, CA) where he develops social web applications using PHP, MySQL, JavaScript, Zend Framework, CodeIgniter, jQuery, and Mashup APIs. He also leads various small to medium level projects.

Mahmud is also an Indie iPhone application developer and publishes his own applications at http://ithinkdiff.net.

He was a technical reviewer of the Zend Framework 1.8 Web Application Development book by Packt Publishing.

I’m very grateful to my father who bought a computer for me in 2001. Since then, I have loved programming and working with various technologies.

Joe Wu is a full-time Senior PHP Web Developer, and has been in the industry since 2005. He has worked on various projects of all sizes and is familiar with most of the open source technologies surrounding PHP web development.

Joe is always enthusiastic about new and upcoming technologies and is keen to learn and pick up new skill-sets wherever possible and utilize them in his current or future projects. He is also keen to learn about new opportunities and innovative ideas out there, and believes that the market is always wide open for new and upcoming innovations to improve our way of living.

Aside from all the technological computer work, Joe is a professional badminton player and manages to somehow fit a near full-time training schedule together with his full-time job. Joe's best ranking of 59th in the world in singles and the attendance of the Commonwealth Games Delhi 2010 means that he has equally as much experience in badminton and web developing.

Aside from all the endeavors, Joe also works for his own company (with his business partner) to put his skills and experience to good use and to help anyone who needs assistance with web development.

Wackyinnovation (www.wackyinnovation.com) promotes the concept of always moving forward and coming up with and utilizing new technologies and ideas. Their always enthusiastic and can-do attitude ensures jobs are done to perfection with an innovative edge on their competitors.

Shameemah Kurzawa has been programming since she was at high school. Being motivated to be a Systems Analyst, she pursued both undergraduate and postgraduate studies in Business Information System and Software Engineering, respectively.

She has been working as a Web Developer/Analyst for the past five years, for a renowned company SBS (Special Broadcasting Service) in Australia. Besides work, she enjoys spending her time with her family (she is the mum of a little two year old baby boy) and enjoys travelling as well as investigating new technologies.

I would like to thank my husband, my son, and the Packt Publishing team for their support and understanding in reviewing this book.

www.PacktPub.com

Support files, eBooks, discount offers, and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can access, read and search across Packt’s entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy & paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Nowadays, web applications are behaving more and more like desktop applications with lesser page loads and more user interaction and effects. The Web has become faster and applications such as Gmail and Facebook have given a new meaning to web applications.

PHP on the server side and jQuery on the client side (browser) are a killer combination for developing interactive web applications. PHP is the leading language of choice among web developers and jQuery is now used on more than one-third of the top 1000 sites on the internet and is the most widely-used library.

One thing that PHP and jQuery have in common is that they are easy to learn. Once you know the basics, you can promote yourself to the next level easily.

And this is what the book will do for you. It is like a toolbox having a myriad of tools inside. It will allow you to write faster web applications, which feel like desktop applications, with the help of PHP and jQuery. Whether you want to learn live validations, create plugins, drag elements, create a menu, watch videos using YouTube API, or interact with the database, just jump to the respective recipe for the solution. AJAX, a key feature of rich internet applications, is also covered in detail.

You are not required to read this book from the beginning to the end. Each recipe is independent and is like a "how to" or a mini application in itself. You can directly look for a solution to a specific problem.

I hope you will find this book useful and that it will help you to take your skills to a higher level.

What this book covers

Chapter 1, Handling Events with jQuery, helps you understand jQuery's cross-browser event handling methods. You will learn to work with keyboard and mouse events. Advanceevent handling topics, such as dragging and keyboard shortcuts are also discussed.

Chapter 2, Combining PHP and jQuery, lists several ways of sending AJAX requests using jQuery and also describes how PHP responds to such requests. This chapter also contains recipes that deal with caching of AJAX requests and error handling during AJAX requests.

Chapter 3, Working with XML Documents, explains working with XML files in PHP as well as jQuery. Recipes will describe how to read, write, and modify XMLs using DOM and SimpleXML extensions of PHP. Parsing XML with jQuery is also discussed.

Chapter 4, Working with JSON, discusses JSON in detail. You will be shown how to read and write JSON data in PHP, and also explore jQuery's inbuilt capabilities of parsing JSON.

Chapter 5, Working with Forms, deals with forms and form validations. You will learn how to validate forms for different types of data with jQuery. This will cover validating empty fields, numbers, e-mail addresses, web addresses, and much more. Server-side validation methods will also be discussed to make validations more powerful.

Chapter 6, Adding Visual Effects to Forms, extends the previous chapter and provides recipes for adding visual effects to forms. Recipes in this chapter allow you to create user-friendly forms by adding effects, such as highlighting, fading, expandable boxes, and various others.

Chapter 7, Creating Cool Navigation Menus, describes the creation of different types of menus, such as animated menus, accordions, and tabbed menus. Advanced techniques for creating tabs are also covered that will guide you in adding and removing tabs on the fly.

Chapter 8, Data Binding with PHP and jQuery, explains, in detail, how a database can be used along with PHP and jQuery. Examples included in this chapter will explain how to fetch data from the database and use it in web forms.

Chapter 9, Enhancing your Site with PHP and jQuery, teaches you some advanced techniques of PHP and jQuery. It will show how to overcome browser restrictions like cross-domain requests. You will learn to create a jQuery plugin for custom use and an endless scrolling page among other things.

Appendix, Firebug, explains the use of Firebug for debugging HTML and JavaScript in web pages. You will learn how to edit HTML and change the appearance of pages on the browser itself without switching to actual code files. You will be able to execute JavaScript directly from Firebug and further understand debugging JavaScript using this add-on.

What you need for this book

You should have Apache (or another web server), PHP (version 5.0 or above), and MySQL installed on your system to be able to run the examples in this book. You can install them all at once using software such as WampServer or you can install them separately. jQuery (version 1.3.2 or higher) will also be required.

In terms of technical proficiency, this book assumes that you have working knowledge of PHP, jQuery, HTML, and CSS. You need to know only the basics of these, leave the rest to this book.

Who this book is for

This book is for PHP and jQuery developers who just know the basics of these two and want to use PHP and jQuery together to create rich internet applications. It provides a large number of examples in each chapter that will take you from being a basic developer to a pro by giving step-by-step instructions for each task in developing web applications using PHP and jQuery.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "The input button has also been attached to a click event."

A block of code is set as follows:

$('input:text').bind( { focus: function() { $(this).val(''); }, blur: function() { $(this).val('Enter some text'); } });

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Now click on the Create New Element button a few times to create some DIV elements".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Tip

Downloading the example code for this book

You can download the example code files 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 files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Handling Events with jQuery

In this chapter, we will cover:

Executing functions when a page has loadedBinding and unbinding elementsAdding events to elements that will be created laterSubmitting a form using jQueryChecking for missing imagesCreating a select/unselect all checkbox functionalityCapturing mouse movementsCreating keyboard shortcutsDisplaying user-selected textDragging elements on a page

Introduction

Events are actions that execute some JavaScript code for producing the desired result. They can be either some sort of manipulation of a document or some internal calculations.

Since different browsers handle events differently, it takes a lot of effort to write JavaScript code that is compatible with all browsers. This chapter will help you understand event handling and explore related methods of jQuery that can make scripts compatible on different browsers. You will learn to work with the keyboard and mouse events. Advanced event handling topics like dragging and keyboard shortcuts are also discussed.

Executing functions when page has loaded

AJAX applications make extensive use of JavaScript to manipulate the content and the look and feel of web pages. Web pages should have the DOM loaded before any JavaScript code tries to perform any such modification on it.

This recipe will explain how to execute the JavaScript after the content has been loaded and the DOM is ready.

Getting ready

Get a copy of the latest version of the jQuery library.

How to do it...

Create a file and name it as domReady.html.To run any JavaScript code only after the DOM has completely loaded, write it between the curly braces of .ready() method:
<script type="text/javascript"> $(document).ready(function () { // code written here will run only after the DOM has loaded }); </script>

How it works...

jQuery ensures that code written inside .ready() gets executed only after the DOM is fully loaded. This includes the complete document tree containing the HTML, stylesheets, and other scripts. You can, therefore, manipulate the page, attach events, and do other stuff. Note that .ready() does not wait for images to load. Images can be checked using the .load() method, which is explained in a separate recipe in this chapter.

If .ready() is not used, the jQuery code does not wait for the whole document to load. Instead it will execute as it is loaded in the browser. This can throw errors if the written code tries to manipulate any HTML or CSS that has not been loaded yet.

Passing a handler to .ready()

In the previous example code we used an anonymous function with .ready(). You can also pass a handler instead of the anonymous function. It can be done as follows:

<script type="text/javascript"> $(document).ready(doSomething); function doSomething() { // write code here } </script>

Another method of using .ready()

Instead of writing the code in the above mentioned format, we can also use one of the below described variations for finding out when the DOM is ready:

$(function () { });

Or

$(doSomething); function doSomething() { // DOM is ready now }

Multiple .ready() methods

If there are multiple script files in your application, you can have a .ready() for each of them. jQuery will run all of these after DOM loads. An example scenario may be when you are using some plugins on a page and each one of them has a separate .js file.

Binding and unbinding elements

This recipe will demonstrate how you can attach events to DOM elements using the .bind() method and how to remove them using the .unbind() method.

Getting ready

Get a latest copy of the jQuery library to use with this recipe.

How to do it...

Create a new file, in a directory named chapter1, and name it as binding.html.Write the HTML markup to create some HTML elements. Create an unordered list with the names of some countries. After that, create a select box containing names of continents as options. Finally, create a button that will be used to remove the event handler from the select box.
<html> <head> <title>Binding Elements</title> <style type="text/css"> ul { background-color:#DCDCDC; list-style:none; margin:0pt; padding:0pt; width:250px;} li { cursor:pointer; margin:10px 0px;} </style> </head> <body> <ul> <li>India</li> <li>USA</li> <li>UK</li> <li>France</li> </ul> <select> <option value="Africa">Africa</option> <option value="Antarctica">Antarctica</option> <option value="Asia">Asia</option> <option value="Australia">Australia</option> <option value="Europe">Europe</option> <option value="North America">North America</option> <option value="South America">South America</option> </select> <input type="button" value="Unbind select box"/> </body> </html>
It's time to add some jQuery magic. Attach a click event handler to list items using the .bind() method, which will set the background color of the clicked item to red. Attach the change event handler to the select box, which will display the value of the selected item. Finally, add a click handler to the button. Clicking on the button will remove the event handler from the select box.
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('input:text').bind( { focus: function() { $(this).val(''); }, blur: function() { $(this).val('Enter some text'); } }); $('li').bind('click', function() { $(this).css('background-color', 'red'); }); $('select').bind('change', function() { alert('You selected: '+ $(this).val()); }); $('input:button').bind('click', function() { $('select').unbind('change'); }); }); </script>
Run the binding.html file in your browser and click on some items in the list. The background color of each item clicked upon will change to red. Now select some value from the select box and you will see an alert box that displays the selected value as shown in the following screenshot:

Clicking on the Unbindselectbox button will remove the change event handler here and the selection of a value from the combo box will now do nothing.

How it works...

jQuery uses the .bind() method to attach standard JavaScript events to elements. .bind() takes two parameters. The first parameter is the event type to attach. It is passed in string format, and event types such as click, change, keyup, keydown, focus, blur, and so on can be passed to it. The second parameter is the callback function, which will be executed when the event fires.

In the previous code, we used .bind() for the list items to attach a click handler. In the callback function, $(this) refers to the element that fired the event. We then use the .css() method to change the background color of the element that is clicked upon.

Similarly, we attached the change event to the select box using the .bind() method. The callback function will be called each time the value of the select box is changed.

The input button has also been attached to a click event. Clicking on the button calls the .unbind() method. This method accepts an event type name and removes that event from the element. Our example code will remove the change event from the select box. Therefore, changing the value of the select box will not display any further alerts.

There's more...

Binding multiple events

Multiple events can also be attached using the .bind() method. The following code attaches two events focus and blur to a textbox. Focusing on a textbox will empty it, whereas taking the focus away from it will put some text in it.

$('input:text').bind( { focus: function() { $(this).val(''); }, blur: function() { $(this).val('Enter some text'); } });

Tip

Note that this functionality was added in Version 1.4 of jQuery. So, make sure that you have the correct version before running this code.

Shortcut method for binding

Instead of using .bind(), events can be attached directly by using shortcut event names to elements. For example, $(element).click(function() { }); can be written instead of using $(element).bind('click', function() { });.

Other events can be attached similarly.

Triggering events

Events can also be triggered from the code. For this we have to pass the event name without any parameter.

$(element1).click(function() { $(element2).keydown(); });

The above code will execute the keydown event of element2 when element1 is clicked.

Common event types

Here is a list of some common events that can be passed to the bind() and unbind() methods.

blur

focus

load

unload

scroll

click

dblclick

mousedown

mouseup

mousemove

mouseover

mouseout

change

select

submit

keydown

keypress

keyup

Unbinding all events from an element

If no parameter is passed to the .unbind() method, it will remove all event handlers associated with the specified element.

$(element).unbind();

Adding events to elements that will be created later

The .bind() method attaches events to only those elements that exist on a page. If any new elements are created that match the criteria for the .bind() method, they will not have any event handlers.

How to do it...

Create a new file in the chapter1 directory and name it as live.html.Write the HTML, which creates a button and a DIV on the page and styles them a bit.
<html> <head> <title>Attaching events elements </title> <style type="text/css"> div { border: 1px solid black;cursor:pointer;width:200px;margin:10px; } </style> </head> <body> <input type="button" id="button" value="Create New Element"/> <div class="future">Already on page</div> </body> </html>
Time to spice things up with jQuery. Attach a click event to the button. This button will create the new DIV elements and will insert them into the page. Now attach a click event handler to the DIV using the live() method. Clicking on the DIV will change its CSS and HTML.
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#button').click(function() { $('body').append('<div class="future">I am a new div</div>'); }); $('div').live('click', function() { $(this).css({'color':'red','font-weight':'bold'}).html('You clicked me'); }); }); </script>
Run the live.html file and click on the DIV. You will see that its HTML and CSS has changed. Now click on the CreateNewElement button a few times to create some DIV elements. Clicking on any of these DIV elements will change their appearances. A typical screenshot after a few clicks will look similar to the following:

How it works...

The input button creates the new DIV elements and appends them to the body of a document. The secret lies in the next function. We have used jQuery's live() method to attach an event on click of a DIV element. live() behaves exactly like bind() for attaching events with only one major difference. Where bind() can add events to only existing elements on a page, live() remembers the attached event for that selector and applies it to matching elements even if they are created later and then inserted into a page.

Therefore, all new DIV elements that are created as a result of clicking on the Create NewElement button also respond to the click event handler.

Removing event handlers with die()

The die() method is similar to the unbind() method. It is used to remove event handlers that were attached using the live() method. Similar to unbind(), die() also has two variations.

If it is called with no parameters, all event handlers will be removed. Another variation accepts an event type name that will remove that particular event:

$(element).die();

The following is the code for other variations that will remove only the specified event handler.

$(element).die('click');

If an element has more than one event handler attached to it, the above code will remove only the click event handler and will leave the others intact.

See also

Binding and unbinding elements provides basic information about adding and removing events from elements.

Submitting a form with jQuery

We know that submit buttons are used in HTML forms to submit data to a server. Apart from submit buttons, JavaScript also provides a submit method that can be used to submit forms.

In this recipe, you will learn how to submit forms the jQuery way and will also learn how the form submission can be controlled using the submit button.

Getting ready

Get the jQuery library to use with this recipe.

How to do it...

Create a new file, name it as formSubmit.html and save it in the chapter1 directory.Write the following code, which creates a form with an input button (not submit button). Add some jQuery code that will be triggered on clicking the button and will submit the form.
<html> <head> <title>Submitting forms</title> </head> <body> <form id="myForm"> <input type="button" value="Submit Form" /> </form> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('input:button').click(function() { $('#myForm').submit(); }); }); </script> </body> </html>
Run the formSubmit.html file and click on the input button. It will submit the form.

How it works...

In this example we attached the click event handler to the input button. The event handler function will execute when the button is clicked. On clicking the button, jQuery's submit() method is called on the form, which submits the form. All browsers have a native submit method to submit the form programmatically. jQuery has wrapped this functionality into its own submit() method.