Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
PHP jQuery Cookbook
PHP jQuery Cookbook

PHP jQuery Cookbook: jQuery and PHP are the dynamic duo that will allow you to build powerful web applications. This Cookbook is the easy way in with over 60 recipes covering everything from the basics to creating plugins and integrating databases.

Arrow left icon
Profile Icon Joshi
Arrow right icon
NZ$45.99 NZ$51.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6 (5 Ratings)
eBook Dec 2010 332 pages 1st Edition
eBook
NZ$45.99 NZ$51.99
Paperback
NZ$64.99
Subscription
Free Trial
Arrow left icon
Profile Icon Joshi
Arrow right icon
NZ$45.99 NZ$51.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6 (5 Ratings)
eBook Dec 2010 332 pages 1st Edition
eBook
NZ$45.99 NZ$51.99
Paperback
NZ$64.99
Subscription
Free Trial
eBook
NZ$45.99 NZ$51.99
Paperback
NZ$64.99
Subscription
Free Trial

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 jQuery Cookbook

Chapter 2. Combining PHP and jQuery

In this chapter, we will cover:

  • Fetching data from PHP using jQuery

  • Creating a query string automatically for all form elements

  • Detecting an AJAX request in PHP

  • Sending data to PHP

  • Aborting AJAX requests

  • Creating an empty page and loading it in parts

  • Handling errors in AJAX requests

  • Preventing a browser from caching AJAX request

  • Loading JavaScript on demand to reduce page load time

Introduction


You surely know how typical web applications work. You enter a URL in your browser and the browser loads that page for you. If you are required to submit a form, you will fill it and the browser sends the filled data to the server side for processing. During this time you wait for the entire page to load. If you are on a slow connection, the wait is even longer.

Let me describe another typical scenario, a web page has two select boxes. The first select box asks you to select the name of a country. You make your selection and the whole page loads to populate the second select box with the names of the cities in that country. If by mistake you made a wrong selection, fixing your mistake means another page load. Irritating isn't it?

The point I am trying to make here is: why load the complete page every time? Why can't you just select the country name and using some magic in the background be provided with the city list without loading the complete page? Maybe you can fill some other...

Fetching data from PHP using jQuery


This recipe will teach you the usage of jQuery's get method to retrieve data from a PHP script. We will see a simple example where data will be fetched from the server using the get method based on user selection from a form.

Getting ready

Create a directory named chapter2 in your web root. Put the jQuery library file in this directory. Now create another folder inside and name it as Recipe1. As a recipe can have more than one file, it is better to keep them separate.

How to do it...

  1. Create a file index.html in the Recipe1 folder. Write the HTML code in it that will create a combo box with some options.

    <html>
      <head>
        <title>jQuery.get()</title>
        <style type="text/css">
          ul{border:1px solid black; list-style:none;margin:0pt;padding:0pt;float:left;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px;width:300px;}
          li{padding:10px 5px;border-bottom:1px solid black;}
        </style>
      </head&gt...

Creating a query string automatically for all form elements


Getting ready

Create a new folder Recipe2 inside the chapter2 directory. Now create a file index.html in the newly created directory.

How to do it...

  1. Open the index.html file for editing and create a form with some HTML elements, such as textboxes, radio buttons, and check boxes.

    <html>
    <head>
        <title>Serializing form values</title>
        <style type="text/css">
          ul{ border:1px solid black; list-style: none;margin:0pt;padding:0pt;float:left;font-family:Verdana,Arial, Helvetica, sans-serif;font-size:12px;width:400px;}
          li{  padding:10px 5px;border-bottom:1px solid black;}
          label{width:100px;text-align:right;margin-right:10px;float:left;}
        </style>
      </head>
      <body>
        <form>
          <ul>
            <li><label>Email:</label><input type="text" name="email"/></li>
            <li><label>Full Name</label><input type...

Detecting an AJAX request in PHP


After going through this recipe you will be able to distinguish between AJAX requests and simple HTTP requests in your PHP code.

Getting ready

Create a new directory named Recipe3 in the chapter2 directory. Inside it create an HTML file named index.html and another PHP file check.php.

How to do it...

  1. Open the index.html file and create a button that will load a string from a PHP file using the $.get() method.

    <html>
      <head>
        <title>Detecting AJAX Requests</title>
      </head>
      <body>
        <form>
          <p>
            <input type="button" value="Load Some data"/>
          </p>
        </form>
      </body>
    </html>
  2. Next, include jQuery and write the code for a click event of the button. Clicking on the button will simply send an AJAX request to check.php, which will return a string. The response string will be appended to the page after the input button.

    <script type="text/javascript" src="../jquery...

Sending data to PHP


GET and POST are the two most frequently used methods for accessing pages. In the first recipe you learned to make requests using GET method.

This recipe will make use of jQuery's $.post() method to retrieve data from a PHP script. We will see a simple example where we will fill some data in a form and the data will be sent to PHP using the POST method. Sent data will be processed by PHP and then displayed in the browser.

Getting ready

Create a new directory named Recipe4 under the chapter2 directory.

How to do it...

  1. Create a file named index.html in the newly created Recipe4 directory. In this recipe, we will use the same form that we created in the second recipe (Creating query string automatically for all form elements) of this chapter. So write the HTML that will create a form with multiple controls.

    <html>
      <head>
        <title>Sending data through post</title>
        <style type="text/css">
          ul{ border:1px solid black; list-style:none;margin...

Aborting AJAX requests


Consider a case where a user is allowed to select a date on a page and an AJAX request is made to the server to fetch some data against that date. If the request is under processing and in the meantime the user selects another date and a new request is sent, the server now has two requests pending.

Imagine what will happen to an application if there are multiple users repeating the same behavior. Desirable behavior in this case will be to cancel the pending request and allow only the current one.

This recipe will explain how to cancel any pending requests.

Getting ready

Create a new folder in chapter2 directory and name it as Recipe5.

How to do it...

  1. We will use the same markup that we created in the first recipe of this chapter. So create a new file index.html and write the code to create an HTML page with a combo box and two options. Also create a paragraph element on the page that will display the received response.

    <html>
      <head>
        <title>Aborting...

Creating an empty page and loading it in parts


The larger a web page the more time a browser will take to download it. This may degrade the user experience in case of slow connections or larger pages.

One approach that can be followed is to load only what is absolutely necessary for the user and load the rest of the content when required. There are some sections on a page which are rarely accessed. It will make page loads faster and user experience will improve.

In this recipe we will demonstrate this case with a simple example. We will create a single HTML page and will allow the user to load its one section when required.

Getting ready

Create a folder named Recipe6 in chapter2 directory.

How to do it...

  1. Create a new file and save it as index.html. This page will have three sections: head, content, and footer. HTML for the footer will not be created; instead we will load it dynamically. We have also applied some CSS in the head section to customize the appearance of the page.

    <html>
      &lt...

Handling errors in AJAX requests


Errors are inevitable. Period. Sometimes things are not in your control—like server failures—and in this case you must have an error handling mechanism in place, which can catch the errors and show them to the users. Throughout the recipes in this chapter we have implemented callback functions that execute when a request is successful. It may happen (and I promise you it will happen) that you typed a filename incorrectly or the server encounters an error and you get an error rather than a successful response.

This recipe will explain how to deal with such situations in AJAX requests.

Getting ready

Create a folder Recipe7 inside the chapter2 folder.

How to do it...

  1. Create a file named index.html in the Recipe7 folder. Define some CSS styles in it and create an input box that will ask for a filename to load and a button. Also create a paragraph where contents loaded in a file will be displayed.

    <html>
      <head>
        <title>Error handling</title...

Preventing browser from caching AJAX requests


In case of GET requests, browsers cache these requests and when the request is invoked again they do not send the request to the server and instead serve it from the cache.

This recipe will explain how to force browsers to send the request to a server instead of serving it from the cache.

How to do it...

  1. While sending an AJAX request use the cache option to force no caching by the browser. Setting the cache option to false does not let the browser cache any AJAX requests and the data is loaded from the server each time the request is made.

    $.ajax({
      url : 'someurl.php',
      cache: false,
      success: function(data)
      {
        //do something with received data
      }
    });

How it works...

On an AJAX request, the browser checks if a request to that URL is already in the browser cache or not. If it is found in the cache, no request to the server is sent and response from the cache is served.

jQuery provides a cache option that can be used to override this browser...

Loading JavaScript on demand to reduce page load time


Think of a rich Internet application that makes heavy use of JavaScript to interact with the user. Such a page typically consists of more than one JavaScript files, such as a file for calendar control, another file for special effects, yet another plugin for your cool accordion, and so on.

This results in the increase of the page load time as browsers cannot download all of these files simultaneously. The best solution for this is to load only absolutely necessary files at the time of loading the page and load the other files when required.

This recipe will explain how JavaScript files can be loaded on demand.

Getting ready

Create a directory named Recipe9 in the chapter2 folder.

How to do it...

  1. Create a file index.html in the chapter2 folder. Write the HTML to create a page that will have a paragraph element and four buttons. The first button will be used to load another JavaScript file and rest of the buttons will manipulate the paragraph...

Left arrow icon Right arrow icon

Key benefits

  • Create rich and interactive web applications with PHP and jQuery
  • 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

Description

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!

Who is this book for?

If 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.

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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 14, 2010
Length: 332 pages
Edition : 1st
Language : English
ISBN-13 : 9781849512756
Languages :
Tools :

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 14, 2010
Length: 332 pages
Edition : 1st
Language : English
ISBN-13 : 9781849512756
Languages :
Tools :

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 NZ$7 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 NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 201.97
PHP Ajax Cookbook
NZ$71.99
Responsive Web Design with HTML5 and CSS3
NZ$64.99
PHP jQuery Cookbook
NZ$64.99
Total NZ$ 201.97 Stars icon

Table of Contents

9 Chapters
Handling Events with jQuery Chevron down icon Chevron up icon
Combining PHP and jQuery Chevron down icon Chevron up icon
Working with XML Documents Chevron down icon Chevron up icon
Working with JSON Chevron down icon Chevron up icon
Working with Forms Chevron down icon Chevron up icon
Adding Visual Effects to Forms Chevron down icon Chevron up icon
Creating Cool Navigation Menus Chevron down icon Chevron up icon
Data Binding with PHP and jQuery Chevron down icon Chevron up icon
Enhancing your Site with PHP and jQuery Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(5 Ratings)
5 star 80%
4 star 0%
3 star 20%
2 star 0%
1 star 0%
Amazon Customer Sep 12, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Kann das Buch nur empfehlen um die Zusammenarbeit zwischen jQuery und PHP zu bekommen. Allerdings würde ich mir manche Kaptiel etwas ausführlicher wünschen
Amazon Verified review Amazon
Julian A. Rozzell Sr. Apr 23, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Love the information provided in this book in developing html, php and javascript codes: effectively, efficiently, producitvely and accurately. A must for developers who seek professionalism and quality codemanship.
Amazon Verified review Amazon
Cristian Astudillo B Mar 26, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very didactic and practical book; the examples work fine.
Amazon Verified review Amazon
Anders S. Nielsen Jul 27, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book was very valuable to my project, which involved writing a jQuery Mobile app that fetches and sends data through a PHP back-end. I found few useful examples online, and since I was brand new to the world of jQuery, this book was a godsend, covering most of the scenarios relevant to my app.Of course, this book isn't specific to jQuery Mobile, so I used another book to learn proper front-end coding of JQM.
Amazon Verified review Amazon
K. Robinson Sr. Mar 15, 2012
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
You can find all the material that's in this book on the web. With a little research skills and filtering through many website, you can find just about any tutorials on jQuery. Although this books give you some the modest, coolest things about jQuery, you can implement the code into your site quickly and be up and running with jQuery on your site. I gave three stars because everything is on the web all ready.
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.