
PHP jQuery Cookbook
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
- Debug and execute jQuery code on a live site
- Design interactive forms and menus
- Another title in the Packt Cookbook range, which will help you get to grips with PHP as well as jQuery
Book DescriptionAs 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!What you will learn - Start from the basics and learn pro-level tricks by the end of the book
- Create interactive and dynamic hierarchical menus
- Apply eye-catching effects on form elements
- Integrate a database along with PHP and jQuery
- Use AJAX to enhance user experience and page interaction
- Learn how to work with JSON and XML for efficient data exchange
- Create tools and utilities for your web applications
- Master form validation on client side as well as server side
Who this book is forIf you want to use PHP and jQuery together to create web applications this book is for you. It provides a large number of examples in each chapter that will take you from a basic developer to a pro by giving step-by-step instructions for each task in developing web applications using PHP and jQUery. All you need are JavaScript basics and you are on your way to building power web applications, with this book in hand.
All prices
More details
Other editions
Additional editions

Person
Vijay Joshi is a full stack web developer having more than a decade of experience in working with PHP and JavaScript.
Content
- Intro
- PHP jQuery Cookbook
- 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
Creating a Tic-Tac-Toe game with effects
Web forms should be as user-friendly as possible to ease the life of users. Users should be clear as to which part they are interacting with.
In this recipe we will create a game of Tic-Tac-Toe. You may have already played this game as a kid. This will present a good example of how different sections of a page can be highlighted for a user to let him or her know where he or she is interacting on the page.
Ours will be a two-player game where we will present the user with a grid of 3*3 or 5*5 depending on his selection. Hovering over a box in the grid will highlight that box and clicking on a box will put either a cross or a circle depending on the player's turn. With every mark made on the grid, we will switch user turns and check if a user has won or not.
Getting ready
Create a folder named Recipe1 inside the Chapter6 directory. For this recipe we will need two more images: one for a cross and one for a circle as the game demands. Using paint or any other simple image editing programs we can create these two images. I have used the following images in this recipe:
How to do it...
- First create a CSS file
main.cssin theRecipe1folder. This file will contain the following CSS styles for our game: body{color:#FA6766;font-family:Trebuchet MS,arial,verdana;margin:20px;padding:0pt;} h3{margin:0pt:padding:0pt;} div{float:left;} #table{ width:100%; } .row {width:100%;} .col {width:75px;float:left;height:75px;cursor:pointer;} .hr{ border-right:2px solid #FA6766;} .vr{ border-bottom:2px solid #FA6766;} .cross{background-image:url(cross.png);} .round{background-image:url(round.png);} #log{clear:both;margin:0pt;padding:0pt;} .reset{cursor:pointer;display:none;text-decoration:underline;} - After defining styles, create another file in the same folder and name it as
index.html. This file includes themain.cssfile. Then create a combo box from where the user will select a grid size (3*3 or 5*5). Then create twoh2elements. The first element will be used to display the player's turns and the second element will be used to reset the game when it ends. Lastly, create a DIV with IDcontainerthat will hold the grid for a game. It will be created using jQuery. - In the end add the reference to the jQuery library. Since the jQuery code will be a bit lengthy, we will keep it in a separate file that we will call
tictactoe.js. Add a reference to this file also. <html> <head> <title>Tic-Tac-Toe</title> <link rel="stylesheet" href="main.css" /> </head> <body> <div> <strong>Grid Size:</strong><select id="size"> <option value="3">3 * 3</option> <option value="5">5 * 5</option> </select> </div>
<h2 id="log">Waiting for Player 1</h2> <h2 class="reset">Reset</h2>
<div id="container"></div> <script type="text/javascript" src="../jquery.js"></script> <script type="text/javascript" src="tictactoe.js"></script> </body> </html> - Now create the
tictactoe.jsfile in theRecipe1directory. This code will define a separate namespacegamein which we will keep all our variables and functions. The code in this file has a functioncreateGrid(), which will create a grid according to selected size and other functions. Then it will add event handlers for clicking on the grid. $(document).ready(function() { function game() {}; game.init = function(size) { if(parseInt(size,10) <=0) return; this.gridSize = size; this.player = 0; // 0 - player 1; 1- player 2 this.marker; //create grid this.createGrid(); $('.col').hover(function(){$(this).css('background-color', '#FBF9EA');},function(){$(this).css('background-color', '#FFF');}); $('.col').click(function() { //check if already clicked if($(this).hasClass('cross') || $(this).hasClass('round')) { return; }// cant var who = (game.player ==0 ) ? "Player 1" : "Player 2"; game.marker = (game.player == 0 ) ? 'cross' : 'round'; $(this).addClass(game.marker); var won = game.checkForWin(this); if(!won) { //change players turn game.player = (game.player == 0) ? 1 : 0; var player = (game.player ==0 ) ? "Player 1" : "Player 2"; $('#log').html('Waiting for '+ player); } else { $('.col').unbind('click'); $('#log').html(who + ' Wins!!!'); $('h2:last').show('slow'); } }); } - Another function
checkForWin()is defined that will check if a player has won a game after clicking on a box in the grid. Finally, there are event handlers for bothh2elements. In the last line of code we start the game by calling theinitfunction. game.checkForWin = function(current) { var size = this.gridSize; var row = $(current).attr('i'); var col = $(current).attr('j'); //check horizontal and vertical rows var hDone = true, vDone = true; for(var i=0; i< size; i++) { if($('#'+(row + i)).hasClass(this.marker) != true) hDone = false; if($('#'+(i + col)).hasClass(this.marker) != true) vDone = false; } if(hDone == true || vDone == true) return true; //check diagonals if(row == col || ((parseInt(row) + parseInt(col)) == (this.gridSize)-1)) { var ldDone = true, rdDone = true; for(var i = 0, j = size-1; i< size; i++, j--) { if($('#'+i+i).hasClass(this.marker) != true) ldDone = false; if($('#'+i+j).hasClass(this.marker) != true) rdDone = false; } if(ldDone == true || rdDone == true) return true; } return false; } game.createGrid = function() { var size = this.gridSize; var str = '<div id="table">'; for(var i=0; i<size; i++) { str+= '<div class="row">'; for(var j=0; j<size; j++) { var cssClass='col'; if(j< size-1) cssClass+= " hr"; if(i< size-1) cssClass+= " vr"; str+= '<div id="'+i+j+'" class="' + cssClass +'" i="'+i+'"j="'+j+'"></div>'; } str+= '</div>'; } $('#container').html(str); } $('#size').change(function() { game.init($(this).val()); $('#log').html('Waiting for Player 1'); }); $('h2:last').click(function() { game.init($('#size').val()); $('#log').html('Waiting for Player 1'); $(this).hide('slow'); }); game.init(3); }); - Our game is complete and is ready to be played now. Run the file
index.htmlin your browser and you will see a nice 3*3 tic-tac-toe grid. - Start playing the game now. Taking the mouse pointer over a box will make it yellow. Clicking in any box will place cross and circle symbols alternatively. After a player wins the game, the screen will look similar to the following screenshot:
How it works...
First, define a global object game. This will be our namespace under which we will keep all variables and functions for our game.
We start with the init function where we pass a number. This number is the size of the grid that we will create. There is another variable, player, whose value will be 0 if it's Player 1's turn and 1 if it's Player 2's turn. The variable marker will decide which icon to place (cross or circle) depending on the player's turn. In the case of Player 1 it will be a cross and a circle if it is Player 2's turn.
Next comes createGrid() that creates the actual game grid. This function creates a DIV with rows and columns and assigns CSS classes to them that define the look and feel of the grid. If the grid size is 3, it will create a 3*3 grid. After creating the HTML for the grid, it inserts it into the container DIV. Each column in the grid has also been assigned two custom attributes i and j whose value is the index value of the matrix. The following figure will explain this:
Before proceeding, make note of two important CSS classes: cross and round. cross will add a background image of a cross to a column and round will add the background image of a circle.
Our UI is ready and now we need to add event listeners. There are two important event handlers. First is when a user hovers the mouse pointer over a box in the grid. For this we use the jQuery .hover listener that changes the color to yellow while the mouse pointer is over a box and back to white if the mouse pointer goes out of the boundaries of a box.
The most important event is the click event on a box on the grid. On clicking a box or column, we first check if it has the cross or round class. If it has, we simply return from the function as we can place icons or markers on already empty columns.
As mentioned above, the variable who defines which player is playing and marker defines the CSS class to be applied. We then apply the suitable class after checking which player is playing.
After placing the CSS...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: PDF
Copy-Protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (only limited: Kindle).
The file format PDF always displays a book page identically on any hardware. This makes PDF suitable for complex layouts such as those used in textbooks and reference books (images, tables, columns, footnotes). Unfortunately, on the small screens of e-readers or smartphones, PDFs are rather annoying, requiring too much scrolling.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our eBook Help page.