100% found this document useful (4 votes)
35 views

(Ebook) Learning PHP, MySQL & JavaScript by Robin Nixon ISBN 9781491918661, 1491918667 all chapter instant download

Robin

Uploaded by

liyiahlers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
35 views

(Ebook) Learning PHP, MySQL & JavaScript by Robin Nixon ISBN 9781491918661, 1491918667 all chapter instant download

Robin

Uploaded by

liyiahlers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Visit https://ebooknice.

com to download the full version and


explore more ebooks

(Ebook) Learning PHP, MySQL & JavaScript by Robin


Nixon ISBN 9781491918661, 1491918667

_____ Click the link below to download _____


https://ebooknice.com/product/learning-php-mysql-
javascript-4761774

Explore and download more ebooks at ebooknice.com


Here are some recommended products that might interest you.
You can download now and explore!

(Ebook) Learning PHP, MySQL, and JavaScript by Robin Nixon ISBN


9780596157135, 0596157134

https://ebooknice.com/product/learning-php-mysql-and-
javascript-1216936

ebooknice.com

(Ebook) Learning PHP MySQL JavaScript and CSS by Robin Nixon ISBN
9781449319267, 1449319262

https://ebooknice.com/product/learning-php-mysql-javascript-and-
css-2618790

ebooknice.com

(Ebook) Learning PHP, MySQL & JavaScript (Early Release) by Robin


Nixon ISBN 9781492093817, 1492093815

https://ebooknice.com/product/learning-php-mysql-javascript-early-
release-24129590

ebooknice.com

(Ebook) Learning PHP, MySQL & JavaScript - With jQuery, CSS & HTML5 by
Robin Nixon ISBN 9781491978917, 1491978910

https://ebooknice.com/product/learning-php-mysql-javascript-with-
jquery-css-html5-7294746

ebooknice.com
(Ebook) Learning PHP, MySQL & JavaScript, 6th Edition by Robin Nixon
ISBN 9781492093800, 9781492093824, 1492093807, 1492093823

https://ebooknice.com/product/learning-php-mysql-javascript-6th-
edition-23267530

ebooknice.com

(Ebook) Learning PHP, MySQL & JavaScript, 7th Edition by Robin Nixon
ISBN 9781098152352, 9781098152291, 1098152352, 1098152298

https://ebooknice.com/product/learning-php-mysql-javascript-7th-
edition-54117148

ebooknice.com

(Ebook) Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5
(Early Release 5th) by Robin Nixon ISBN 9781491978917, 1491978910

https://ebooknice.com/product/learning-php-mysql-javascript-with-
jquery-css-html5-early-release-5th-6855160

ebooknice.com

(Ebook) Learning PHP, MySQL, JavaScript, CSS & HTML5, Third Edition: A
Step-by-Step Guide to Creating Dynamic Websites by Robin Nixon ISBN
9781491949467, 1491949465

https://ebooknice.com/product/learning-php-mysql-javascript-css-
html5-third-edition-a-step-by-step-guide-to-creating-dynamic-
websites-4724548
ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James


ISBN 9781459699816, 9781743365571, 9781925268492, 1459699815,
1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com
4t
h
wi
Ed jQue
th
Learning PHP, MySQL & JavaScript

iti r y
on
FOURTH EDITION
Build interactive, data-driven websites with the potent combination of
open-source technologies and web standards, even if you have only basic bookisthata great
“This beginner's
introduces 

MySQL & JavaScript


Learning PHP,
HTML knowledge. With this popular hands-on guide, you’ll tackle dynamic
web programming with the help of today’s core technologies: PHP, MySQL, several crucial web
JavaScript, jQuery, CSS, and HTML5. developer languages. 
Explore each technology separately, learn how to use them together, and It's a quick-paced, easy-
pick up valuable web programming practices along the way. At the end of to-read, information-
the book, you’ll put everything together to build a fully functional social packed book that will
networking site, using XAMPP or any development stack you choose.
soon have you creating
Learn PHP in-depth, along with the basics of object-oriented dynamically driven web-

Learning
■■
programming sites, including a basic
■■ Explore MySQL, from database structure to complex queries social networking site. ”

PHP, MySQL
■■ Use the MySQLi Extension, PHP’s improved MySQL interface —Albert Wiersch
developer of CSE HTML Validator
■■ Create dynamic PHP web pages that tailor themselves to
the user
■■ Manage cookies and sessions, and maintain a high level
of security

& JavaScript
■■ Master the JavaScript language—and enhance it with jQuery
■■ Use Ajax calls for background browser/server communication
■■ Acquire CSS2 & CSS3 skills for professionally styling your
web pages
■■ Implement all of the new HTML5 features, including
geolocation, audio, video, and the canvas
WITH JQUERY, CSS & HTML5
Robin Nixon, an IT journalist who has written hundreds of articles and several
books on computing, has developed numerous websites using open source tools,
specializing in the technologies featured in this book. Robin has worked with and
written about computers since the early 1980s.

WEB DEVELOPMENT
Twitter: @oreillymedia Nixon
facebook.com/oreilly
US $49.99 CAN $52.99
ISBN: 978-1-491-91866-1

Robin Nixon
4t
h
wi
Ed jQue
th
Learning PHP, MySQL & JavaScript

iti r y
on
FOURTH EDITION
Build interactive, data-driven websites with the potent combination of
open-source technologies and web standards, even if you have only basic bookisthata great
“This beginner's
introduces 

MySQL & JavaScript


Learning PHP,
HTML knowledge. With this popular hands-on guide, you’ll tackle dynamic
web programming with the help of today’s core technologies: PHP, MySQL, several crucial web
JavaScript, jQuery, CSS, and HTML5. developer languages. 
Explore each technology separately, learn how to use them together, and It's a quick-paced, easy-
pick up valuable web programming practices along the way. At the end of to-read, information-
the book, you’ll put everything together to build a fully functional social packed book that will
networking site, using XAMPP or any development stack you choose.
soon have you creating
Learn PHP in-depth, along with the basics of object-oriented dynamically driven web-

Learning
■■
programming sites, including a basic
■■ Explore MySQL, from database structure to complex queries social networking site. ”

PHP, MySQL
■■ Use the MySQLi Extension, PHP’s improved MySQL interface —Albert Wiersch
developer of CSE HTML Validator
■■ Create dynamic PHP web pages that tailor themselves to
the user
■■ Manage cookies and sessions, and maintain a high level
of security

& JavaScript
■■ Master the JavaScript language—and enhance it with jQuery
■■ Use Ajax calls for background browser/server communication
■■ Acquire CSS2 & CSS3 skills for professionally styling your
web pages
■■ Implement all of the new HTML5 features, including
geolocation, audio, video, and the canvas
WITH JQUERY, CSS & HTML5
Robin Nixon, an IT journalist who has written hundreds of articles and several
books on computing, has developed numerous websites using open source tools,
specializing in the technologies featured in this book. Robin has worked with and
written about computers since the early 1980s.

WEB DEVELOPMENT
Twitter: @oreillymedia Nixon
facebook.com/oreilly
US $49.99 CAN $52.99
ISBN: 978-1-491-91866-1

Robin Nixon
FOURTH EDITION

Learning PHP, MySQL & JavaScript


With jQuery, CSS & HTML5

Robin Nixon
Learning PHP, MySQL & JavaScript
With jQuery, CSS & HTML5
by Robin Nixon
Copyright © 2015 Robin Nixon. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.

Editor: Andy Oram Indexer: Ellen Troutman


Production Editor: Nicole Shelby Interior Designer: David Futato
Copyeditor: Rachel Monaghan Cover Designer: Randy Comer
Proofreader: Sharon Wilkey Illustrator: Rebecca Demarest

December 2014: Fourth Edition

Revision History for the Fourth Edition


2014-11-21: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781491918661 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning PHP, MySQL & JavaScript, the
cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.

978-1-491-91866-1
[LSI]
For Julie
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii

1. Introduction to Dynamic Web Content. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


HTTP and HTML: Berners-Lee’s Basics 2
The Request/Response Procedure 2
The Benefits of PHP, MySQL, JavaScript, CSS, and HTML5 5
Using PHP 6
Using MySQL 7
Using JavaScript 8
Using CSS 9
And Then There’s HTML5 10
The Apache Web Server 11
About Open Source 12
Bringing It All Together 12
Questions 14

2. Setting Up a Development Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15


What Is a WAMP, MAMP, or LAMP? 16
Installing XAMPP on Windows 16
Testing the Installation 24
Installing XAMPP on Mac OS X 27
Accessing the Document Root 27
Installing a LAMP on Linux 28
Working Remotely 28
Logging In 28
Using FTP 29
Using a Program Editor 30
Using an IDE 31

v
Questions 33

3. Introduction to PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Incorporating PHP Within HTML 35
This Book’s Examples 37
The Structure of PHP 38
Using Comments 38
Basic Syntax 39
Variables 40
Operators 45
Variable Assignment 48
Multiple-Line Commands 50
Variable Typing 52
Constants 53
Predefined Constants 54
The Difference Between the echo and print Commands 55
Functions 55
Variable Scope 56
Questions 62

4. Expressions and Control Flow in PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63


Expressions 63
TRUE or FALSE? 63
Literals and Variables 65
Operators 66
Operator Precedence 67
Associativity 69
Relational Operators 70
Conditionals 74
The if Statement 75
The else Statement 76
The elseif Statement 78
The switch Statement 79
The ? Operator 82
Looping 83
while Loops 84
do...while Loops 86
for Loops 86
Breaking Out of a Loop 88
The continue Statement 89
Implicit and Explicit Casting 90
PHP Dynamic Linking 91

vi | Table of Contents
Dynamic Linking in Action 92
Questions 93

5. PHP Functions and Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95


PHP Functions 96
Defining a Function 98
Returning a Value 98
Returning an Array 100
Do Not Pass Arguments by Reference 100
Returning Global Variables 102
Recap of Variable Scope 103
Including and Requiring Files 103
The include Statement 104
Using include_once 104
Using require and require_once 105
PHP Version Compatibility 105
PHP Objects 106
Terminology 106
Declaring a Class 107
Creating an Object 108
Accessing Objects 109
Cloning Objects 110
Constructors 111
PHP 5 Destructors 112
Writing Methods 112
Static Methods in PHP 5 113
Declaring Properties 114
Declaring Constants 115
Property and Method Scope in PHP 5 115
Static Properties and Methods 116
Inheritance 118
Questions 121

6. PHP Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123


Basic Access 123
Numerically Indexed Arrays 123
Associative Arrays 125
Assignment Using the array Keyword 126
The foreach...as Loop 127
Multidimensional Arrays 129
Using Array Functions 132
is_array 132

Table of Contents | vii


count 132
sort 133
shuffle 133
explode 133
extract 134
compact 135
reset 136
end 136
Questions 137

7. Practical PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139


Using printf 139
Precision Setting 140
String Padding 142
Using sprintf 143
Date and Time Functions 143
Date Constants 146
Using checkdate 146
File Handling 147
Checking Whether a File Exists 147
Creating a File 147
Reading from Files 149
Copying Files 150
Moving a File 150
Deleting a File 151
Updating Files 151
Locking Files for Multiple Accesses 152
Reading an Entire File 154
Uploading Files 155
System Calls 160
XHTML or HTML5? 162
Questions 162

8. Introduction to MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165


MySQL Basics 165
Summary of Database Terms 166
Accessing MySQL via the Command Line 166
Starting the Command-Line Interface 167
Using the Command-Line Interface 171
MySQL Commands 172
Data Types 177
Indexes 186

viii | Table of Contents


Creating an Index 186
Querying a MySQL Database 192
Joining Tables Together 202
Using Logical Operators 204
MySQL Functions 204
Accessing MySQL via phpMyAdmin 205
Questions 206

9. Mastering MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209


Database Design 209
Primary Keys: The Keys to Relational Databases 210
Normalization 211
First Normal Form 212
Second Normal Form 214
Third Normal Form 217
When Not to Use Normalization 219
Relationships 219
One-to-One 219
One-to-Many 220
Many-to-Many 221
Databases and Anonymity 222
Transactions 223
Transaction Storage Engines 223
Using BEGIN 224
Using COMMIT 225
Using ROLLBACK 225
Using EXPLAIN 226
Backing Up and Restoring 227
Using mysqldump 227
Creating a Backup File 229
Restoring from a Backup File 231
Dumping Data in CSV Format 231
Planning Your Backups 232
Questions 232

10. Accessing MySQL Using PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233


Querying a MySQL Database with PHP 233
The Process 233
Creating a Login File 234
Connecting to a MySQL Database 235
A Practical Example 240
The $_POST Array 243

Table of Contents | ix
Deleting a Record 244
Displaying the Form 245
Querying the Database 246
Running the Program 247
Practical MySQL 248
Creating a Table 248
Describing a Table 249
Dropping a Table 250
Adding Data 250
Retrieving Data 251
Updating Data 251
Deleting Data 252
Using AUTO_INCREMENT 252
Performing Additional Queries 254
Preventing Hacking Attempts 255
Steps You Can Take 256
Using Placeholders 257
Preventing HTML Injection 259
Using mysqli Procedurally 261
Questions 263

11. Form Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265


Building Forms 265
Retrieving Submitted Data 267
register_globals: An Old Solution Hangs On 268
Default Values 269
Input Types 270
Sanitizing Input 277
An Example Program 279
What’s New in HTML5? 281
The autocomplete Attribute 282
The autofocus Attribute 282
The placeholder Attribute 282
The required Attribute 282
Override Attributes 283
The width and height Attributes 283
Features Awaiting Full Implementation 283
The form Attribute 283
The list Attribute 284
The min and max Attributes 284
The step Attribute 284
The color Input Type 285

x | Table of Contents
The number and range Input Types 285
Date and Time Pickers 285
Questions 285

12. Cookies, Sessions, and Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287


Using Cookies in PHP 287
Setting a Cookie 289
Accessing a Cookie 290
Destroying a Cookie 290
HTTP Authentication 290
Storing Usernames and Passwords 294
Salting 294
Using Sessions 298
Starting a Session 299
Ending a Session 302
Setting a Time-Out 303
Session Security 303
Questions 307

13. Exploring JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309


JavaScript and HTML Text 310
Using Scripts Within a Document Head 311
Older and Nonstandard Browsers 311
Including JavaScript Files 312
Debugging JavaScript Errors 313
Using Comments 315
Semicolons 315
Variables 316
String Variables 316
Numeric Variables 317
Arrays 317
Operators 318
Arithmetic Operators 318
Assignment Operators 318
Comparison Operators 319
Logical Operators 319
Variable Incrementing and Decrementing 320
String Concatenation 320
Escaping Characters 320
Variable Typing 321
Functions 322
Global Variables 322

Table of Contents | xi
Local Variables 323
The Document Object Model 324
But It’s Not That Simple 326
Using the DOM 327
About document.write 328
Using console.log 328
Using alert 328
Writing into Elements 329
Using document.write 329
Questions 329

14. Expressions and Control Flow in JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331


Expressions 331
Literals and Variables 332
Operators 333
Operator Precedence 334
Associativity 334
Relational Operators 335
The with Statement 338
Using onerror 339
Using try...catch 340
Conditionals 341
The if Statement 341
The else Statement 341
The switch Statement 342
The ? Operator 344
Looping 344
while Loops 344
do...while Loops 345
for Loops 346
Breaking Out of a Loop 346
The continue Statement 347
Explicit Casting 348
Questions 348

15. JavaScript Functions, Objects, and Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351


JavaScript Functions 351
Defining a Function 351
Returning a Value 353
Returning an Array 355
JavaScript Objects 356
Declaring a Class 356

xii | Table of Contents


Creating an Object 357
Accessing Objects 358
The prototype Keyword 358
JavaScript Arrays 361
Numeric Arrays 361
Associative Arrays 362
Multidimensional Arrays 363
Using Array Methods 364
Questions 369

16. JavaScript and PHP Validation and Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371


Validating User Input with JavaScript 371
The validate.html Document (Part 1) 372
The validate.html Document (Part 2) 374
Regular Expressions 377
Matching Through Metacharacters 378
Fuzzy Character Matching 378
Grouping Through Parentheses 379
Character Classes 380
Indicating a Range 380
Negation 380
Some More-Complicated Examples 381
Summary of Metacharacters 383
General Modifiers 385
Using Regular Expressions in JavaScript 386
Using Regular Expressions in PHP 386
Redisplaying a Form After PHP Validation 387
Questions 393

17. Using Ajax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395


What Is Ajax? 395
Using XMLHttpRequest 396
Your First Ajax Program 398
Using Get Instead of Post 403
Sending XML Requests 406
Using Frameworks for Ajax 411
Questions 411

18. Introduction to CSS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413


Importing a Style Sheet 414
Importing CSS from Within HTML 414
Embedded Style Settings 415

Table of Contents | xiii


Using IDs 415
Using Classes 415
Using Semicolons 416
CSS Rules 416
Multiple Assignments 416
Using Comments 417
Style Types 418
Default Styles 418
User Styles 418
External Style Sheets 419
Internal Styles 419
Inline Styles 420
CSS Selectors 420
The Type Selector 420
The Descendant Selector 420
The Child Selector 421
The ID Selector 422
The Class Selector 423
The Attribute Selector 423
The Universal Selector 424
Selecting by Group 425
The CSS Cascade 425
Style Sheet Creators 426
Style Sheet Methods 426
Style Sheet Selectors 426
Calculating Specificity 427
The Difference Between Div and Span Elements 429
Measurements 431
Fonts and Typography 432
font-family 433
font-style 433
font-size 434
font-weight 434
Managing Text Styles 435
Decoration 435
Spacing 435
Alignment 436
Transformation 436
Indenting 436
CSS Colors 437
Short Color Strings 438
Gradients 438

xiv | Table of Contents


Positioning Elements 439
Absolute Positioning 440
Relative Positioning 440
Fixed Positioning 440
Pseudoclasses 442
Shorthand Rules 444
The Box Model and Layout 445
Setting Margins 445
Applying Borders 447
Adjusting Padding 448
Object Contents 450
Questions 450

19. Advanced CSS with CSS3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451


Attribute Selectors 451
Matching Parts of Strings 452
The box-sizing Property 453
CSS3 Backgrounds 453
The background-clip Property 454
The background-origin Property 456
The background-size Property 456
Using the auto Value 457
Multiple Backgrounds 457
CSS3 Borders 459
The border-color Property 459
The border-radius Property 459
Box Shadows 462
Element Overflow 463
Multicolumn Layout 463
Colors and Opacity 465
HSL Colors 465
HSLA Colors 466
RGB Colors 466
RGBA Colors 467
The opacity Property 467
Text Effects 467
The text-shadow Property 467
The text-overflow Property 468
The word-wrap Property 469
Web Fonts 469
Google Web Fonts 470
Transformations 472

Table of Contents | xv
3D Transformations 473
Transitions 474
Properties to Transition 474
Transition Duration 475
Transition Delay 475
Transition Timing 475
Shorthand Syntax 476
Questions 477

20. Accessing CSS from JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479


Revisiting the getElementById Function 479
The O function 479
The S Function 480
The C Function 481
Including the Functions 482
Accessing CSS Properties from JavaScript 482
Some Common Properties 483
Other Properties 484
Inline JavaScript 486
The this Keyword 486
Attaching Events to Objects in a Script 487
Attaching to Other Events 488
Adding New Elements 489
Removing Elements 490
Alternatives to Adding and Removing Elements 491
Using Interrupts 492
Using setTimeout 492
Cancelling a Time-Out 493
Using setInterval 493
Using Interrupts for Animation 495
Questions 497

21. Introduction to jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499


Why jQuery? 500
Including jQuery 500
Choosing the Right Version 500
Downloading 501
Using a Content Delivery Network 502
Always Using the Latest Version 503
Customizing jQuery 503
jQuery Syntax 503
A Simple Example 504

xvi | Table of Contents


Avoiding Library Conflict 505
Selectors 505
The css Method 506
The Element Selector 506
The ID Selector 507
The Class Selector 507
Combining Selectors 507
Handling Events 508
Waiting Until the Document Is Ready 509
Event Functions and Properties 510
The blur and focus Events 511
The this Keyword 512
The click and dblclick Events 512
The keypress Event 513
Considerate Programming 515
The mousemove Event 515
Other Mouse Events 518
Alternative Mouse Methods 519
The submit Event 520
Special Effects 521
Hiding and Showing 522
The toggle Method 523
Fading In and Out 524
Sliding Elements Up and Down 525
Animations 526
Stopping Animations 529
Manipulating the DOM 530
The Difference Between The text and html Methods 531
The val and attr Methods 531
Adding and Removing Elements 533
Dynamically Applying Classes 535
Modifying Dimensions 535
The width and height Methods 536
The innerWidth and innerHeight Methods 538
The outerWidth and OuterHeight Methods 538
DOM Traversal 539
Parent Elements 539
Child Elements 543
Sibling Elements 543
Selecting the Next and Previous Elements 545
Traversing jQuery Selections 546
The is Method 548

Table of Contents | xvii


Using jQuery Without Selectors 549
The $.each Method 550
The $.map Method 551
Using Ajax 551
Using the Post Method 551
Using the Get Method 552
Plug-Ins 553
The jQuery User Interface 553
Other Plug-Ins 553
jQuery Mobile 554
Questions 555

22. Introduction to HTML5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557


The Canvas 558
Geolocation 559
Audio and Video 561
Forms 562
Local Storage 563
Web Workers 563
Web Applications 563
Microdata 564
Summary 564
Questions 564

23. The HTML5 Canvas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565


Creating and Accessing a Canvas 565
The toDataURL Function 567
Specifying an Image Type 569
The fillRect Method 569
The clearRect Method 569
The strokeRect Method 570
Combining These Commands 570
The createLinearGradient Method 571
The addColorStop Method in Detail 573
The createRadialGradient Method 574
Using Patterns for Fills 576
Writing Text to the Canvas 578
The strokeText Method 578
The textBaseLine Property 579
The font Property 579
The textAlign Property 579
The fillText Method 580

xviii | Table of Contents


The measureText Method 581
Drawing Lines 581
The lineWidth Property 581
The lineCap and lineJoin Properties 581
The miterLimit Property 584
Using Paths 584
The moveTo and LineTo Methods 584
The stroke Method 585
The rect Method 585
Filling Areas 586
The clip Method 587
The isPointInPath Method 590
Working with Curves 591
The arc Method 591
The arcTo Method 594
The quadraticCurveTo Method 595
The bezierCurveTo Method 596
Manipulating Images 597
The drawImage Method 597
Resizing an Image 598
Selecting an Image Area 598
Copying from a Canvas 600
Adding Shadows 600
Editing at the Pixel Level 602
The getImageData Method 602
The data Array 603
The putImageData Method 605
The createImageData Method 605
Advanced Graphical Effects 606
The globalCompositeOperation Property 606
The globalAlpha Property 609
Transformations 609
The scale Method 609
The save and restore Methods 610
The rotate Method 611
The translate Method 612
The transform Method 613
The setTransform Method 615
Summary 615
Questions 616

Table of Contents | xix


24. HTML5 Audio and Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
About Codecs 618
The <audio> Element 619
Supporting Non-HTML5 Browsers 621
The <video> Element 623
The Video Codecs 623
Supporting Older Browsers 627
Summary 629
Questions 629

25. Other HTML5 Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631


Geolocation and the GPS Service 631
Other Location Methods 632
Geolocation and HTML5 632
Local Storage 636
Using Local Storage 637
The localStorage Object 637
Web Workers 639
Offline Web Applications 641
Drag and Drop 643
Cross-Document Messaging 645
Microdata 648
Other HTML5 Tags 651
Summary 652
Questions 652

26. Bringing It All Together. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653


Designing a Social Networking Site 653
On the Website 654
functions.php 654
The Functions 654
header.php 656
setup.php 658
index.php 660
signup.php 661
Checking for Username Availability 661
Logging In 662
checkuser.php 665
login.php 665
profile.php 667
Adding the “About Me” Text 668
Adding a Profile Image 668

xx | Table of Contents
Processing the Image 668
Displaying the Current Profile 669
members.php 672
Viewing a User’s Profile 672
Adding and Dropping Friends 672
Listing All Members 672
friends.php 675
messages.php 678
logout.php 681
styles.css 682
javascript.js 685

A. Solutions to the Chapter Questions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687

B. Online Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707

C. MySQL’s FULLTEXT Stopwords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711

D. MySQL Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715

E. jQuery Selectors, Objects, and Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747

Table of Contents | xxi


Preface

The combination of PHP and MySQL is the most convenient approach to dynamic,
database-driven web design, holding its own in the face of challenges from integrated
frameworks—such as Ruby on Rails—that are harder to learn. Due to its open source
roots (unlike the competing Microsoft .NET Framework), it is free to implement and
is therefore an extremely popular option for web development.
Any would-be developer on a Unix/Linux or even a Windows/Apache platform will
need to master these technologies. And, combined with the partner technologies of
JavaScript, jQuery, CSS, and HTML5, you will be able to create websites of the caliber
of industry standards like Facebook, Twitter, and Gmail.

Audience
This book is for people who wish to learn how to create effective and dynamic web‐
sites. This may include webmasters or graphic designers who are already creating
static websites but wish to take their skills to the next level, as well as high school and
college students, recent graduates, and self-taught individuals.
In fact, anyone ready to learn the fundamentals behind the Web 2.0 technology
known as Ajax will obtain a thorough grounding in all of these core technologies:
PHP, MySQL, JavaScript, CSS, and HTML5, and learn the basics of the jQuery library
too.

Assumptions This Book Makes


This book assumes that you have a basic understanding of HTML and can at least put
together a simple, static website, but does not assume that you have any prior knowl‐
edge of PHP, MySQL, JavaScript, CSS, or HTML5—although if you do, your progress
through the book will be even quicker.

xxiii
Organization of This Book
The chapters in this book are written in a specific order, first introducing all of the
core technologies it covers and then walking you through their installation on a web
development server so that you will be ready to work through the examples.
In the first section, you will gain a grounding in the PHP programming language,
covering the basics of syntax, arrays, functions, and object-oriented programming.
Then, with PHP under your belt, you will move on to an introduction to the MySQL
database system, where you will learn everything from how MySQL databases are
structured to how to generate complex queries.
After that, you will learn how you can combine PHP and MySQL to start creating
your own dynamic web pages by integrating forms and other HTML features. Follow‐
ing that, you will get down to the nitty-gritty practical aspects of PHP and MySQL
development by learning a variety of useful functions and how to manage cookies
and sessions, as well as how to maintain a high level of security.
In the next few chapters, you will gain a thorough grounding in JavaScript, from sim‐
ple functions and event handling to accessing the Document Object Model and in-
browser validation and error handling, plus a comprehensive primer on using the
popular jQuery library for JavaScript.
With an understanding of all three of these core technologies, you will then learn how
to make behind-the-scenes Ajax calls and turn your websites into highly dynamic
environments.
Next, you’ll spend two chapters learning all about using CSS to style and lay out your
web pages, before moving on to the final section on the new features built into
HTML5, including geolocation, audio, video, and the canvas. After this, you’ll put
together everything you’ve learned in a complete set of programs that together consti‐
tute a fully functional social networking website.
Along the way, you’ll find plenty of advice on good programming practices and tips
that could help you find and solve hard-to-detect programming errors. There are also
plenty of links to websites containing further details on the topics covered.

Supporting Books
Once you have learned to develop using PHP, MySQL, JavaScript, CSS, and HTML5,
you will be ready to take your skills to the next level using the following O’Reilly ref‐
erence books. To learn more about any of these titles, simply enter the ISBN shown
next to it into the search box at http://oreilly.com or at any good online book seller’s
website.

xxiv | Preface
• Dynamic HTML: The Definitive Reference (9780596527402) by Danny Goodman
• PHP in a Nutshell (9780596100674) by Paul Hudson
• MySQL in a Nutshell (9780596514334) by Russell Dyer
• JavaScript: The Definitive Guide (9780596805524) by David Flanagan
• CSS: The Definitive Guide (9780596527334) by Eric A. Myer
• HTML5: The Missing Manual (9781449363260) by Matthew MacDonald

Conventions Used in This Book


The following typographical conventions are used in this book:
Plain text
Indicates menu titles, options, and buttons.
Italic
Indicates new terms, URLs, email addresses, filenames, file extensions, pathnames,
directories, and Unix utilities.
Constant width
Indicates command-line options, variables and other code elements, HTML tags,
macros, and the contents of files.
Constant width bold
Shows program output or highlighted sections of code that are discussed in the text.
Constant width italic
Shows text that should be replaced with user-supplied values.

This element signifies a tip, suggestion, or general note.

This element indicates a warning or caution.

Using Code Examples


This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not

Preface | xxv
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples
from O’Reilly books does require permission. Answering a question by citing this
book and quoting example code does not require permission. Incorporating a signifi‐
cant amount of example code from this book into your product’s documentation does
require permission. There is a companion website to this book at http://lpmj.net,
where you can download all the examples from this book in a single zip file.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “Learning PHP, MySQL & JavaScript,
4th Edition by Robin Nixon (O’Reilly). Copyright 2015 Robin Nixon,
978-1-4919-1866-1.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.

Safari® Books Online


Safari Books Online is an on-demand digital library that deliv‐
ers expert content in both book and video form from the
world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.

xxvi | Preface
How to Contact Us
Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/lpmjch_4e.
To comment or ask technical questions about this book, send email to bookques‐
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments
I would like to once again thank my editor, Andy Oram, and everyone who worked
so hard on this book, including Albert Wiersch for his comprehensive technical
review, Nicole Shelby for overseeing production, Rachel Monaghan for her copy edit‐
ing, Sharon Wilkey for proofreading, Robert Romano for his original illustrations,
Rebecca Demarest for her new illustrations, David Futato for interior design, Lucie
Haskins for creating the index, Karen Montgomery for the original sugar glider front
cover design, Randy Comer for the latest book cover, and everyone else too numer‐
ous to name who submitted errata and offered suggestions for this new edition.

Preface | xxvii
CHAPTER 1
Introduction to Dynamic Web Content

The World Wide Web is a constantly evolving network that has already traveled far
beyond its conception in the early 1990s, when it was created to solve a specific prob‐
lem. State-of-the-art experiments at CERN (the European Laboratory for Particle
Physics—now best known as the operator of the Large Hadron Collider) were pro‐
ducing incredible amounts of data—so much that the data was proving unwieldy to
distribute to the participating scientists who were spread out across the world.
At this time, the Internet was already in place, with several hundred thousand com‐
puters connected to it, so Tim Berners-Lee (a CERN fellow) devised a method of nav‐
igating between them using a hyperlinking framework, which came to be known as
Hypertext Transfer Protocol, or HTTP. He also created a markup language called
Hypertext Markup Language, or HTML. To bring these together, he wrote the first
web browser and web server, tools that we now take for granted.
But back then, the concept was revolutionary. The most connectivity so far experi‐
enced by at-home modem users was dialing up and connecting to a bulletin board
that was hosted by a single computer, where you could communicate and swap data
only with other users of that service. Consequently, you needed to be a member of
many bulletin board systems in order to effectively communicate electronically with
your colleagues and friends.
But Berners-Lee changed all that in one fell swoop, and by the mid-1990s, there were
three major graphical web browsers competing for the attention of 5 million users. It
soon became obvious, though, that something was missing. Yes, pages of text and
graphics with hyperlinks to take you to other pages was a brilliant concept, but the
results didn’t reflect the instantaneous potential of computers and the Internet to
meet the particular needs of each user with dynamically changing content. Using the
Web was a very dry and plain experience, even if we did now have scrolling text and
animated GIFs!

1
Shopping carts, search engines, and social networks have clearly altered how we use
the Web. In this chapter, we’ll take a brief look at the various components that make
up the Web, and the software that helps make it a rich and dynamic experience.

It is necessary to start using some acronyms more or less right


away. I have tried to clearly explain them before proceeding. But
don’t worry too much about what they stand for or what these
names mean, because the details will become clear as you read on.

HTTP and HTML: Berners-Lee’s Basics


HTTP is a communication standard governing the requests and responses that take
place between the browser running on the end user’s computer and the web server.
The server’s job is to accept a request from the client and attempt to reply to it in a
meaningful way, usually by serving up a requested web page—that’s why the term
server is used. The natural counterpart to a server is a client, so that term is applied
both to the web browser and the computer on which it’s running.
Between the client and the server there can be several other devices, such as routers,
proxies, gateways, and so on. They serve different roles in ensuring that the requests
and responses are correctly transferred between the client and server. Typically, they
use the Internet to send this information.
A web server can usually handle multiple simultaneous connections and—when not
communicating with a client—spends its time listening for an incoming connection.
When one arrives, the server sends back a response to confirm its receipt.

The Request/Response Procedure


At its most basic level, the request/response process consists of a web browser asking
the web server to send it a web page and the server sending back the page. The
browser then takes care of displaying the page (see Figure 1-1).

2 | Chapter 1: Introduction to Dynamic Web Content


Figure 1-1. The basic client/server request/response sequence

Each step in the request and response sequence is as follows:

1. You enter http://server.com into your browser’s address bar.


2. Your browser looks up the IP address for server.com.
3. Your browser issues a request for the home page at server.com.
4. The request crosses the Internet and arrives at the server.com web server.
5. The web server, having received the request, looks for the web page on its disk.
6. The web page is retrieved by the server and returned to the browser.
7. Your browser displays the web page.

For an average web page, this process takes place once for each object within the
page: a graphic, an embedded video or Flash file, and even a CSS template.
In step 2, notice that the browser looked up the IP address of server.com. Every
machine attached to the Internet has an IP address—your computer included. But we
generally access web servers by name, such as google.com. As you probably know, the
browser consults an additional Internet service called the Domain Name Service

The Request/Response Procedure | 3


(DNS) to find its associated IP address and then uses it to communicate with the
computer.
For dynamic web pages, the procedure is a little more involved, because it may bring
both PHP and MySQL into the mix (see Figure 1-2).

Figure 1-2. A dynamic client/server request/response sequence

1. You enter http://server.com into your browser’s address bar.


2. Your browser looks up the IP address for server.com.
3. Your browser issues a request to that address for the web server’s home page.
4. The request crosses the Internet and arrives at the server.com web server.
5. The web server, having received the request, fetches the home page from its hard
disk.

4 | Chapter 1: Introduction to Dynamic Web Content


6. With the home page now in memory, the web server notices that it is a file incor‐
porating PHP scripting and passes the page to the PHP interpreter.
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements, which the PHP interpreter now
passes to the MySQL database engine.
9. The MySQL database returns the results of the statements to the PHP interpreter.
10. The PHP interpreter returns the results of the executed PHP code, along with the
results from the MySQL database, to the web server.
11. The web server returns the page to the requesting client, which displays it.

Although it’s helpful to be aware of this process so that you know how the three ele‐
ments work together, in practice you don’t really need to concern yourself with these
details, because they all happen automatically.
HTML pages returned to the browser in each example may well contain JavaScript,
which will be interpreted locally by the client, and which could initiate another
request—the same way embedded objects such as images would.

The Benefits of PHP, MySQL, JavaScript, CSS, and HTML5


At the start of this chapter, I introduced the world of Web 1.0, but it wasn’t long
before the rush was on to create Web 1.1, with the development of such browser
enhancements as Java, JavaScript, JScript (Microsoft’s slight variant of JavaScript), and
ActiveX. On the server side, progress was being made on the Common Gateway
Interface (CGI) using scripting languages such as Perl (an alternative to the PHP lan‐
guage) and server-side scripting—inserting the contents of one file (or the output of a
system call) into another one dynamically.
Once the dust had settled, three main technologies stood heads and shoulders above
the others. Although Perl was still a popular scripting language with a strong follow‐
ing, PHP’s simplicity and built-in links to the MySQL database program had earned it
more than double the number of users. And JavaScript, which had become an essen‐
tial part of the equation for dynamically manipulating Cascading Style Sheets (CSS)
and HTML, now took on the even more muscular task of handling the client side of
the Ajax process. Under Ajax, web pages perform data handling and send requests to
web servers in the background—without the web user being aware that this is going
on.
No doubt the symbiotic nature of PHP and MySQL helped propel them both for‐
ward, but what attracted developers to them in the first place? The simple answer has
to be the ease with which you can use them to quickly create dynamic elements on
websites. MySQL is a fast and powerful, yet easy-to-use, database system that offers

The Benefits of PHP, MySQL, JavaScript, CSS, and HTML5 | 5


just about anything a website would need in order to find and serve up data to brows‐
ers. When PHP allies with MySQL to store and retrieve this data, you have the funda‐
mental parts required for the development of social networking sites and the
beginnings of Web 2.0.
And when you bring JavaScript and CSS into the mix too, you have a recipe for build‐
ing highly dynamic and interactive websites.

Using PHP
With PHP, it’s a simple matter to embed dynamic activity in web pages. When you
give pages the .php extension, they have instant access to the scripting language. From
a developer’s point of view, all you have to do is write code such as the following:
<?php
echo " Today is " . date("l") . ". ";
?>

Here's the latest news.

The opening <?php tells the web server to allow the PHP program to interpret all the
following code up to the ?> tag. Outside of this construct, everything is sent to the
client as direct HTML. So the text Here's the latest news. is simply output to the
browser; within the PHP tags, the built-in date function displays the current day of
the week according to the server’s system time.
The final output of the two parts looks like this:
Today is Wednesday. Here's the latest news.
PHP is a flexible language, and some people prefer to place the PHP construct
directly next to PHP code, like this:
Today is <?php echo date("l"); ?>. Here's the latest news.
There are also other ways of formatting and outputting information, which I’ll
explain in the chapters on PHP. The point is that with PHP, web developers have a
scripting language that, although not as fast as compiling your code in C or a similar
language, is incredibly speedy and also integrates seamlessly with HTML markup.

If you intend to enter the PHP examples in this book to work along
with me, you must remember to add <?php in front and ?> after
them to ensure that the PHP interpreter processes them. To facili‐
tate this, you may wish to prepare a file called example.php with
those tags in place.

Using PHP, you have unlimited control over your web server. Whether you need to
modify HTML on the fly, process a credit card, add user details to a database, or fetch

6 | Chapter 1: Introduction to Dynamic Web Content


information from a third-party website, you can do it all from within the same PHP
files in which the HTML itself resides.

Using MySQL
Of course, there’s not a lot of point to being able to change HTML output dynami‐
cally unless you also have a means to track the changes that users make as they use
your website. In the early days of the Web, many sites used “flat” text files to store
data such as usernames and passwords. But this approach could cause problems if the
file wasn’t correctly locked against corruption from multiple simultaneous accesses.
Also, a flat file can get only so big before it becomes unwieldy to manage—not to
mention the difficulty of trying to merge files and perform complex searches in any
kind of reasonable time.
That’s where relational databases with structured querying become essential. And
MySQL, being free to use and installed on vast numbers of Internet web servers, rises
superbly to the occasion. It is a robust and exceptionally fast database management
system that uses English-like commands.
The highest level of MySQL structure is a database, within which you can have one
or more tables that contain your data. For example, let’s suppose you are working on
a table called users, within which you have created columns for surname, firstname,
and email, and you now wish to add another user. One command that you might use
to do this is as follows:
INSERT INTO users VALUES('Smith', 'John', 'jsmith@mysite.com');
Of course, as mentioned earlier, you will have issued other commands to create the
database and table and to set up all the correct fields, but the INSERT command here
shows how simple it can be to add new data to a database. INSERT is an example of
Structured Query Language (SQL), a language designed in the early 1970s and remi‐
niscent of one of the oldest programming languages, COBOL. It is well suited, how‐
ever, to database queries, which is why it is still in use after all this time.
It’s equally easy to look up data. Let’s assume that you have an email address for a user
and need to look up that person’s name. To do this, you could issue a MySQL query
such as the following:
SELECT surname,firstname FROM users WHERE email='jsmith@mysite.com';

MySQL will then return Smith, John and any other pairs of names that may be asso‐
ciated with that email address in the database.
As you’d expect, there’s quite a bit more that you can do with MySQL than just simple
INSERT and SELECT commands. For example, you can join multiple tables according
to various criteria, ask for results in a variety of orders, make partial matches when

The Benefits of PHP, MySQL, JavaScript, CSS, and HTML5 | 7


you know only part of the string that you are searching for, return only the nth result,
and a lot more.
Using PHP, you can make all these calls directly to MySQL without having to run the
MySQL program yourself or use its command-line interface. This means you can save
the results in arrays for processing and perform multiple lookups, each dependent on
the results returned from earlier ones, to drill down to the item of data you need.
For even more power, as you’ll see later, there are additional functions built right into
MySQL that you can call up for common operations and extra speed.

Using JavaScript
The oldest of the three core technologies in this book, JavaScript, was created to
enable scripting access to all the elements of an HTML document. In other words, it
provides a means for dynamic user interaction such as checking email address valid‐
ity in input forms, and displaying prompts such as “Did you really mean that?”
(although it cannot be relied upon for security, which should always be performed on
the web server).
Combined with CSS (see the following section), JavaScript is the power behind
dynamic web pages that change in front of your eyes rather than when a new page is
returned by the server.
However, JavaScript can also be tricky to use, due to some major differences in the
ways different browser designers have chosen to implement it. This mainly came
about when some manufacturers tried to put additional functionality into their
browsers at the expense of compatibility with their rivals.
Thankfully, the developers have mostly now come to their senses and have realized
the need for full compatibility with one another, so they don’t have to write multi-
exception code. But there remain millions of legacy browsers that will be in use for a
good many years to come. Luckily, there are solutions for the incompatibility prob‐
lems, and later in this book we’ll look at libraries and techniques that enable you to
safely ignore these differences.
For now, let’s take a look at how to use basic JavaScript, accepted by all browsers:
<script type="text/javascript">
document.write("Today is " + Date() );
</script>

This code snippet tells the web browser to interpret everything within the script tags
as JavaScript, which the browser then does by writing the text Today is to the current
document, along with the date, by using the JavaScript function Date. The result will
look something like this:
Today is Sun Jan 01 2017 01:23:45

8 | Chapter 1: Introduction to Dynamic Web Content


Unless you need to specify an exact version of JavaScript, you can
normally omit the type="text/javascript" and just use <script>
to start the interpretation of the JavaScript.

As previously mentioned, JavaScript was originally developed to offer dynamic con‐


trol over the various elements within an HTML document, and that is still its main
use. But more and more, JavaScript is being used for Ajax. This is a term for the pro‐
cess of accessing the web server in the background. (It originally meant Asynchronous
JavaScript and XML, but that phrase is already a bit outdated.)
Ajax is the main process behind what is now known as Web 2.0 (a term popularized
by Tim O’Reilly, the founder and CEO of this book’s publishing company), in which
web pages have started to resemble standalone programs, because they don’t have to
be reloaded in their entirety. Instead, a quick Ajax call can pull in and update a single
element on a web page, such as changing your photograph on a social networking site
or replacing a button that you click with the answer to a question. This subject is fully
covered in Chapter 17.
Then, in Chapter 21, we take a good look at the jQuery framework, which you can
use to save reinventing the wheel when you need fast, cross-browser code to manipu‐
late your web pages. Of course, there are other frameworks available too, but jQuery
is by far the most popular and, due to continuous maintenance, is extremely reliable,
and a major tool in the utility kit of many seasoned web developers.

Using CSS
With the emergence of the CSS3 standard in recent years, CSS now offers a level of
dynamic interactivity previously supported only by JavaScript. For example, not only
can you style any HTML element to change its dimensions, colors, borders, spacing,
and so on, but now you can also add animated transitions and transformations to
your web pages, using only a few lines of CSS.
Using CSS can be as simple as inserting a few rules between <style> and </style>
tags in the head of a web page, like this:
<style>
p {
text-align:justify;
font-family:Helvetica;
}
</style>

These rules will change the default text alignment of the <p> tag so that paragraphs
contained in it will be fully justified and will use the Helvetica font.

The Benefits of PHP, MySQL, JavaScript, CSS, and HTML5 | 9


As you’ll learn in Chapter 18, there are many different ways you can lay out CSS rules,
and you can also include them directly within tags or save a set of rules to an external
file to be loaded in separately. This flexibility not only lets you style your HTML pre‐
cisely, but it can also (for example) provide built-in hover functionality to animate
objects as the mouse passes over them. You will also learn how to access all of an ele‐
ment’s CSS properties from JavaScript as well as HTML.

And Then There’s HTML5


As useful as all these additions to the web standards became, they were not enough
for ever more ambitious developers. For example, there was still no simple way to
manipulate graphics in a web browser without resorting to plug-ins such as Flash.
And the same went for inserting audio and video into web pages. Plus, several annoy‐
ing inconsistencies had crept into HTML during its evolution.
So, to clear all this up and take the Internet beyond Web 2.0 and into its next itera‐
tion, a new standard for HTML was created to address all these shortcomings. It was
called HTML5 and it began development as long ago as 2004, when the first draft was
drawn up by the Mozilla Foundation and Opera Software (developers of two popular
web browsers). But it wasn’t until the start of 2013 that the final draft was submitted
to the World Wide Web Consortium (W3C), the international governing body for
web standards.
With nine years for it to develop, you might think that would be the end of the speci‐
fication, but that’s not how things work on the Internet. Although websites come and
go at great speed, the underlying software is developed slowly and carefully, and so
the stable recommendation for HTML5 is expected only after this edition of the book
has been published—in late 2014. And then guess what? Work will move on to ver‐
sions 5.1 and higher, beginning in 2015. It’s a never-ending cycle of development.
However, while HTML5.1 is planned to bring some handy improvements (mainly to
the canvas), basic HTML5 is the new standard web developers now need to work to,
and it will remain in place for many years to come. So learning everything you can
about it now will stand you in very good stead.
There’s actually a great deal of new stuff in HTML (and quite a few things that have
been changed or removed), but in summary, here’s what you get:
Markup
Including new elements such as <nav> and <footer>, and deprecated elements like
<font> and <center>.

New APIs
Such as the <canvas> element for writing and drawing on a graphics canvas, <audio>
and <video> elements, offline web applications, microdata, and local storage.

10 | Chapter 1: Introduction to Dynamic Web Content


Applications
Including two new rendering technologies: MathML (Math Markup Language) for
displaying mathematical formulae and SVG (Scalable Vector Graphics) for creating
graphical elements outside of the new <canvas> element. However, MathML and
SVG are somewhat specialist, and are so feature-packed they would need a book of
their own, so I don’t cover them here.
All these things (and more) are covered in detail starting in Chapter 22.

One of the little things I like about the HTML5 specification is that
XHTML syntax is no longer required for self-closing elements. In
the past, you could display a line break using the <br> element.
Then, to ensure future compatibility with XHTML (the planned
replacement for HTML that never happened), this was changed to
<br />, in which a closing / character was added (since all ele‐
ments were expected to include a closing tag featuring this charac‐
ter). But now things have gone full circle, and you can use either
version of these types of element. So, for the sake of brevity and
fewer keystrokes, in this book I have reverted to the former style of
<br>, <hr>, and so on.

The Apache Web Server


In addition to PHP, MySQL, JavaScript, CSS, and HTML5, there’s a sixth hero in the
dynamic Web: the web server. In the case of this book, that means the Apache web
server. We’ve discussed a little of what a web server does during the HTTP server/
client exchange, but it does much more behind the scenes.
For example, Apache doesn’t serve up just HTML files—it handles a wide range of
files from images and Flash files to MP3 audio files, RSS (Really Simple Syndication)
feeds, and so on. To do this, each element a web client encounters in an HTML page
is also requested from the server, which then serves it up.
But these objects don’t have to be static files such as GIF images. They can all be gen‐
erated by programs such as PHP scripts. That’s right: PHP can even create images and
other files for you, either on the fly or in advance to serve up later.
To do this, you normally have modules either precompiled into Apache or PHP or
called up at runtime. One such module is the GD (Graphics Draw) library, which
PHP uses to create and handle graphics.
Apache also supports a huge range of modules of its own. In addition to the PHP
module, the most important for your purposes as a web programmer are the modules
that handle security. Other examples are the Rewrite module, which enables the web
server to handle a varying range of URL types and rewrite them to its own internal

The Apache Web Server | 11


requirements, and the Proxy module, which you can use to serve up often-requested
pages from a cache to ease the load on the server.
Later in the book, you’ll see how to use some of these modules to enhance the fea‐
tures provided by the three core technologies.

About Open Source


Whether or not being open source is the reason these technologies are so popular has
often been debated, but PHP, MySQL, and Apache are the three most commonly used
tools in their categories. What can be said definitively, though, is that their being
open source means that they have been developed in the community by teams of pro‐
grammers writing the features they themselves want and need, with the original code
available for all to see and change. Bugs can be found and security breaches can be
prevented before they happen.
There’s another benefit: all these programs are free to use. There’s no worrying about
having to purchase additional licenses if you have to scale up your website and add
more servers. And you don’t need to check the budget before deciding whether to
upgrade to the latest versions of these products.

Bringing It All Together


The real beauty of PHP, MySQL, JavaScript (sometimes aided by jQuery or other
frameworks), CSS, and HTML5 is the wonderful way in which they all work together
to produce dynamic web content: PHP handles all the main work on the web server,
MySQL manages all the data, and the combination of CSS and JavaScript looks after
web page presentation. JavaScript can also talk with your PHP code on the web server
whenever it needs to update something (either on the server or on the web page).
And with the powerful new features in HTML5, such as the canvas, audio and video,
and geolocation, you can make your web pages highly dynamic, interactive, and
multimedia-packed.
Without using program code, let’s summarize the contents of this chapter by looking
at the process of combining some of these technologies into an everyday Ajax feature
that many websites use: checking whether a desired username already exists on the
site when a user is signing up for a new account. A good example of this can be seen
with Gmail (see Figure 1-3).

12 | Chapter 1: Introduction to Dynamic Web Content


Figure 1-3. Gmail uses Ajax to check the availability of usernames

The steps involved in this Ajax process would be similar to the following:

1. The server outputs the HTML to create the web form, which asks for the neces‐
sary details, such as username, first name, last name, and email address.
2. At the same time, the server attaches some JavaScript to the HTML to monitor
the username input box and check for two things: (a) whether some text has been
typed into it, and (b) whether the input has been deselected because the user has
clicked on another input box.
3. Once the text has been entered and the field deselected, in the background the
JavaScript code passes the username that was entered back to a PHP script on the
web server and awaits a response.
4. The web server looks up the username and replies back to the JavaScript regard‐
ing whether that name has already been taken.
5. The JavaScript then places an indication next to the username input box to show
whether the name is one available to the user—perhaps a green checkmark or a
red cross graphic, along with some text.
6. If the username is not available and the user still submits the form, the JavaScript
interrupts the submission and reemphasizes (perhaps with a larger graphic
and/or an alert box) that the user needs to choose another username.
7. Optionally, an improved version of this process could even look at the username
requested by the user and suggest an alternative that is currently available.

Bringing It All Together | 13


All of this takes place quietly in the background and makes for a comfortable and
seamless user experience. Without Ajax, the entire form would have to be submitted
to the server, which would then send back HTML, highlighting any mistakes. It
would be a workable solution, but nowhere near as tidy or pleasurable as on-the-fly
form-field processing.
Ajax can be used for a lot more than simple input verification and processing,
though; we’ll explore many additional things that you can do with it in the Ajax chap‐
ters later in this book.
In this chapter, you have read a good introduction to the core technologies of PHP,
MySQL, JavaScript, CSS, and HTML5 (as well as Apache), and have learned how they
work together. In Chapter 2, we’ll look at how you can install your own web develop‐
ment server on which to practice everything that you will be learning.

Questions
1. What four components (at the minimum) are needed to create a fully dynamic
web page?
2. What does HTML stand for?
3. Why does the name MySQL contain the letters SQL?
4. PHP and JavaScript are both programming languages that generate dynamic
results for web pages. What is their main difference, and why would you use both
of them?
5. What does CSS stand for?
6. List three major new elements introduced in HTML5.
7. If you encounter a bug (which is rare) in one of the open source tools, how do
you think you could get it fixed?
See Chapter 1 Answers in Appendix A for the answers to these questions.

14 | Chapter 1: Introduction to Dynamic Web Content


CHAPTER 2
Setting Up a Development Server

If you wish to develop Internet applications but don’t have your own development
server, you will have to upload every modification you make to a server somewhere
else on the Web before you can test it.
Even on a fast broadband connection, this can still represent a significant slowdown
in development time. On a local computer, however, testing can be as easy as saving
an update (usually just a matter of clicking once on an icon) and then hitting the
Refresh button in your browser.
Another advantage of a development server is that you don’t have to worry about
embarrassing errors or security problems while you’re writing and testing, whereas
you need to be aware of what people may see or do with your application when it’s on
a public website. It’s best to iron everything out while you’re still on a home or small
office system, presumably protected by firewalls and other safeguards.
Once you have your own development server, you’ll wonder how you ever managed
without one, and it’s easy to set one up. Just follow the steps in the following sections,
using the appropriate instructions for a PC, a Mac, or a Linux system.
In this chapter, we cover just the server side of the web experience, as described in
Chapter 1. But to test the results of your work—particularly when we start using Java‐
Script, CSS, and HTML5 later in this book—you should also have an instance of
every major web browser running on some system convenient to you. Whenever pos‐
sible, the list of browsers should include at least Internet Explorer, Mozilla Firefox,
Opera, Safari, and Google Chrome. If you plan to ensure that your sites look good on
mobile devices too, you should try to arrange access to a wide range of Apple iOS and
Google Android phones and tablets.

15
What Is a WAMP, MAMP, or LAMP?
WAMP, MAMP, and LAMP are abbreviations for “Windows, Apache, MySQL, and
PHP,” “Mac, Apache, MySQL, and PHP,” and “Linux, Apache, MySQL, and PHP.”
These abbreviations describe a fully functioning setup used for developing dynamic
Internet web pages.
WAMPs, MAMPs, and LAMPs come in the form of a package that binds the bundled
programs together so that you don’t have to install and set them up separately. This
means you can simply download and install a single program, and follow a few easy
prompts, to get your web development server up and running in the quickest time
with a minimum hassle.
During installation, several default settings are created for you. The security configu‐
rations of such an installation will not be as tight as on a production web server,
because it is optimized for local use. For these reasons, you should never install such a
setup as a production server.
But for developing and testing websites and applications, one of these installations
should be entirely sufficient.

If you choose not to go the WAMP/MAMP/LAMP route for build‐


ing your own development system, you should know that down‐
loading and integrating the various parts yourself can be very time-
consuming and may require a lot of research in order to configure
everything fully. But if you already have all the components
installed and integrated with one another, they should work with
the examples in this book.

Installing XAMPP on Windows


There are several available WAMP servers, each offering slightly different configura‐
tions, but out of the various open source and free options, the best is probably
XAMPP. You can download it at http://apachefriends.org, as shown in Figure 2-1.

16 | Chapter 2: Setting Up a Development Server


Figure 2-1. The XAMPP website

I recommend that you always download the latest stable release (in this instance, it’s
1.8.3), and there is a direct download link for Windows, OS X, and Linux on the main
page.

During the lifetime of this edition, some of the screens and options
shown in the following walk-through may change. If so, just use
your common sense to proceed in as similar a manner as possible
to the sequence of actions described.

Once you’ve downloaded the installer, run it to bring up the window shown in
Figure 2-2. Before arriving at that window, though, if you use an anti-virus program
or have User Account Control activated on Windows, you may first be shown one or
more advisory notices, and will have to click Yes and/or OK to continue installation.

Installing XAMPP on Windows | 17


Figure 2-2. The initial installation window of the installer

Click Next and then uncheck any of the components shown in Figure 2-3 that you
don’t need. For example, at the minimum for this book you will want to keep Apache,
MySQL, PHP, and PHPMyAdmin checked. The other features are not covered in this
book, but you can get more details on all of these, plus the core XAMPP technologies,
at http://apachefriends.org/faq_windows.html.
Clicking Next brings up the screen in Figure 2-4, in which you should choose a folder
for the installation. You are recommended to accept the default provided unless you
have a good reason to choose a different one. In this book, the default location is
assumed. If the folder you choose exists and is not empty, you will be unable to use it.

18 | Chapter 2: Setting Up a Development Server


Figure 2-3. Select the components to install

Figure 2-4. Choose a folder for the installation

Clicking Next brings up the screen in Figure 2-5 with a checkbox already checked
(which you can uncheck) for supplying information on adding free installers for
related products in a new web browser window or tab. After you choose whether or
not to receive this information, click the Next button.

Installing XAMPP on Windows | 19


Figure 2-5. Information on related free products is available

Having supplied the basic information required by the installer, you will arrive at the
screen in Figure 2-6. Setup is ready to start, so click the Next button.

Figure 2-6. Accept the default values offered for the ports

20 | Chapter 2: Setting Up a Development Server


Exploring the Variety of Random
Documents with Different Content
[49] Cong. Globe, p. 3, 1st Sess. 35th Cong., p. 2,977.
[50] “The American Irish,” pp. 70-1-3.
[51] Cong. Globe, Appendix, 1st Sess., 35th Cong., p. 430.
[52] “Father Curley tells me that John C. Calhoun used to come
to the College to talk philosophy with old Father Dzierozynsky.”
Extract from a letter of the late Father J. S. Sumner, of
Georgetown College, to the author.
CHAPTER VIII.
ELECTED SHERIFF—MASTERS DUTIES OF OFFICE—RE-ELECTED—
NOMINATED FOR MAYOR AGAINST A. OAKEY HALL—CAUSES OF
HIS WITHDRAWAL—GOES TO EUROPE—VISITS HOLY LAND—
INNER LIFE—HIS CHARITIES—RELATIONS WITH S. J. TILDEN—
LEADER OF TAMMANY—SECOND MARRIAGE—COMPTROLLER OF
NEW YORK—SPEECH AT LOTOS CLUB, ETC.
On Christmas Day, 1858, having been elected Sheriff of the City
and County of New York, November 2d of that year, Mr. Kelly
resigned his seat in the Thirty-fifth Congress. He remained in
Washington at his post until it was necessary to go to New York to
enter upon his new office; but in refreshing contrast to those
Representatives in a subsequent Congress, the Forty-second, who
voted themselves back-pay, he declined, after his election as Sheriff,
to draw any salary at all for his service as a member of Congress.
The total number of votes cast at the election for Sheriff was
69,088, of which John Kelly received 39,090, and William H.
Albertson received 29,837, scattering 161. Kelly was the regular
nominee of the Democratic party of the city. His majority was 9,092.
He entered with characteristic energy upon the duties of Sheriff,
that most ancient of county officers known to the common law, Vice-
comes to the Earl, as Blackstone calls him. The difficulties and
responsibilities of this office in New York are peculiarly great. The
reported cases upon Sheriff’s law in that city indicate the immense
number of statutes applicable to the office, and the subtleties,
refinements, and nice legal distinctions, together with the liabilities,
which constantly press upon the Sheriff in the discharge of his
duties. As laymen nearly always have been elected to the office, it
was the rule, before Kelly’s term, for incumbents to rely for guidance
upon legal advisers and prompters behind the scenes, whose special
knowledge of business was supplemented by professional knowledge
of law, and by training and experience in the office. But John Kelly
set resolutely to work with his law books, for it is one of the leading
traits of his character to perform conscientiously whatever duties are
imposed upon him, and he was determined to delegate to no one
else a labor which the people had elected him to do himself. While
he was in the office the Under-Sheriff ceased to be the High-Sheriff.
After reading one or two good elementary books, he next applied
himself to the Code of Procedure, the Revised Statutes, and
Reported Cases, and wrote out a syllabus, or private digest for
himself, of opinions delivered in the lower Courts and the Court of
Appeals in relation to Sheriff’s law. To master such questions he
worked with unflagging zeal, not only by day but far into the night,
during the greater part of his term. In the meantime he acquired
familiarity with the routine and usages of the office. Thus equipped,
he was perhaps the first Sheriff who thoroughly understood the
duties of the office, and discharged them in person. He became a
favorite among the members of the bar, and was an authority,
theoretically and practically, upon disputed questions of Sheriff’s law.
In the Sheriff’s Court Mr. Kelly himself presided over the intelligent
juries there empanelled. He heard arguments of counsel, passed
upon authorities cited, was conversant in the law applicable to
cases, and in the opinion of leading members of the profession he
displayed a judicial mind of high order.
The best body of jurors in the United States is undoubtedly the
Sheriff’s Jury in New York city. The members of this jury are chosen
annually by an eminent Commission of judicial and other high
officers, and are selected from among the foremost citizens in the
community, whose wealth, intelligence, and established character
afford a guarantee of their freedom from improper influences. Large
fines for absence are imposed, and cheerfully paid. An annual
banquet, known of all men, ubique gentium, as the Sheriff’s Jury’s
Dinner, is provided for with the ample sum thus accumulated.
Delmonico’s choicest menu is laid under requisition, and a
distinguished and brilliant company is always brought together.
That accomplished and discerning gentleman, Mr. Rosewell G.
Rolston, President of the Farmers’ Loan and Trust Company of New
York, was one of the members of the Sheriff’s Jury during Mr. Kelly’s
term. He once expressed to the writer of these pages his high
respect for the Sheriff, and descanted upon his sturdy qualities,
saying, that while he was a stern and austere man to look at, he
was, nevertheless, brimful of kindly human nature. After mentioning
some occurrences which had come under his own observation, he
said, with no little earnestness, “John Kelly is a love of a man, a
grand fellow undoubtedly.”
Under-Sheriffs had presided at the trial of Sheriff’s cases before
Mr. Kelly’s entry into the office. The Jury was surprised now to see
the usual rule broken, and the new Sheriff going upon the bench
himself. The more experienced members gave each other a smile of
astonishment and a knowing wink, for they suspected that Kelly was
led away by zeal, and by ignorance of the mysteries of the law, into
whose knotty labyrinths he would be plunged presently by wrangling
lawyers. But Mr. Rolston and his fellow-jurors quickly discovered that
the imperturbable Sheriff behaved like a veteran under legal fire,
and the lawyers themselves were surprised to find him not only
familiar with questions at issue, both of traverse and demurrer, but
practically master of the situation. He had broken the precedent, and
what had been before a fiction was now a fact, a Sheriff of New York
who knew more about his office than any of his subordinates. John
Kelly made a reputation for honesty and capacity as Sheriff, which in
the whole history of the office has never been excelled by any man
who has occupied it. The best evidence of this is found in the fact
that at the earliest moment when he was eligible under the
Constitution of the State, namely, at the expiration of the term of
Sheriff Lynch, his immediate successor, John Kelly was renominated
and re-elected Sheriff of New York. He is the only man since the
foundation of the Government who has been elected twice to this
important office. In the early day, before the Hamiltonian or
monarchical features of the State Constitution had been abolished,
and the Jeffersonian or elective principle had been substituted for
them by constitutional amendment, the Governor and Council held
the appointment, not only of judicial and other great officers, a most
fruitful source of corruption and centralization, but they were
likewise clothed with the power to appoint Sheriffs and County
Clerks in the several counties of the State. But twice only, in the
early history of the State, did the Council of Appointment at Albany
select the same men to fill a second term as Sheriff of the city and
county of New York. Marinus Willett was appointed Sheriff of New
York in 1784, and served until 1787. He was re-appointed in 1791,
and held until 1795. Benjamin Ferris also held the office by
appointment from 1808 to 1810, and again from 1811 to 1813. On
the 6th of November, 1864, John Kelly, who had filled the office so
faithfully from 1859 to 1861, was re-elected Sheriff of New York, an
unprecedented honor, as well as endorsement of his official integrity,
now bestowed for the first time in the history of the city, by the
people themselves, upon any individual.
At this election there were three candidates in the field, two
Democrats and a Republican, but after an exciting canvass John
Kelly led the poll by a plurality of nearly 6,000, his Republican
competitor coming next. The whole number of votes for Sheriff was
106,707, of which Kelly received 42,022, John W. Farmer 36,477, and
Michael Connolly, commonly called the “Big Judge,” 28,099. The
number of scattering votes was 109. Mr. Kelly’s second term expired
December 31, 1867. That it was a repetition of the first one in his
fidelity to the important interests and duties confided to his charge,
was universally declared at the time, without one whisper of dissent.
In the fierce conflicts of party fifteen years after his first term as
Sheriff, and seven years after the second, when his talents and
commanding position in the community had made him a formidable
antagonist, John Kelly’s official integrity as Sheriff was called in
question for the first time by certain political opponents, whose
misconduct he had exposed, and whose arbitrary acts he had
resisted. These tardy shafts of malice fell harmless at his feet.
In the year 1868, eleven months after he had ceased to be Sheriff
a second time, a still handsomer testimonial to the stainlessness of
his character was tendered to him than that implied in his re-election
as Sheriff; an emphatic endorsement of his qualifications for the
highest civic preferment was received by him when the Democratic
Union of New York nominated him for Mayor of the city against A.
Oakey Hall, the candidate of the Tweed Ring. In a laudable and
patriotic attempt to drive the Ring from power at the Charter
election of November, 1868, New York’s best citizens,—merchants,
bankers, tradesmen, mechanics, and members of the various
professions, turned to John Kelly to lead them, to the man whose
admirable administration of the trusts he had previously held as
Alderman, Congressman, and Sheriff, afforded satisfactory proof of
his fitness to grapple with the Ring, and if elected, to crush it, and
restore honesty and economy in the various municipal offices.
Among those who looked to Mr. Kelly at this interesting and critical
hour in the history of New York, as a safe leader against the
notorious triumvirate of Tweed, Sweeny and Connolly, were Samuel
J. Tilden, Andrew H. Green, Augustus Schell, and still another—tell it
not in Gath! mention it not in the streets of Ascalon! for it is
surprising to relate—Nelson J. Waterbury himself. Yes, in the very
next year after John Kelly had ceased to be Sheriff, this gentleman,
who has since lavished so much savage abuse upon him for mythical
misdeeds as Sheriff, the self-same Nelson J. Waterbury was an
enthusiastic supporter of John Kelly for Mayor of New York.
The support which Mr. Tilden was disposed to bestow upon Mr.
Kelly was a more important incident of that eventful campaign. For a
long time they had been intimate acquaintances, and Tilden not only
looked upon Kelly as a man of invincible honesty, but recognized in
him a born leader of men. It was a most unfortunate thing that Mr.
Kelly’s health, at this particular juncture, was so much impaired that
it was not possible for him to stand the strain of such a contest, or,
indeed, of any contest at all. The blackest chapter in the history of
New York was about to be written. He felt the magnitude of the
occasion, and rose from a sick bed to go meet the people half way,
when they called him to lead them in the fight. No personal sacrifice
could be too great, not even life itself, when the stakes were the
reformation of the public service, and the rescue of a million people
from the corrupt domination of such a Ring. “You will never live to
reach the army,” said Voltaire to the feeble and emaciated Mareschal
de Saxe, as the leader was setting out for Fontenoy. “The object
now,” replied the fiery commander, “is not to live, but to go.” But Mr.
Kelly, however willing to act his part, soon found that nature’s
barriers are not to be overcome. The hand which had rejoiced in its
strength was relaxed and powerless under wasting illness, and like
that of Old Priam, telumque imbelle, no longer could strike an
effectual blow. He was, indeed, destined to smite the Tweed Ring a
death-blow, but not now, nor until four years had come and gone,
when, with health restored, and energies all on fire, he drove them
from Tammany Hall, and inscribed his name among the benefactors
of New York. He lived, like Saxe, to fight and win his Fontenoy.
From early life Mr. Kelly had suffered from bronchial troubles,
which always were increased by public speaking. His mind is
intensely active. “I must be occupied in some way,” he once said to a
friend, “and I can’t sit still five minutes without doing something. I
cannot be an idler.”[53] Whatever he undertook to do, his faculties
became concentrated upon the task until it was accomplished. His
occupations for a long time had been engrossing and laborious, and
his health had suffered under the strain. “For twenty years,” to
repeat the remark of the editor of the Utica Observer, quoted in a
preceding chapter of this volume, “he had devoted several hours of
every day to the pursuit of literature and science,” and at length his
constitution was seriously impaired. Domestic afflictions also came
upon him about this period, and his physical maladies were
increased fourfold.
John Kelly had entered into wedlock when a very young man, and
for twenty years his circle of domesticity was unclouded by a single
shadow. His wife, nèe McIlhargy, was the daughter of an Irish
adopted citizen of New York, and an interesting family, a son and
two daughters, grew up to the verge of manhood and womanhood
about him. Mrs. Kelly, whom the present writer knew well, and
greatly respected for the excellent but unostentatious qualities of her
character, was a good wife, a devoted mother and a pious Christian
woman. In the year 1866 she fell a victim to consumption. Her son
Hugh, a bright and winning young man, just as he had turned his
twenty-first year, succumbed to the same disease, and followed his
mother to the grave. Symptoms of consumption also appeared in the
daughters, and it was evident that death had marked them both for
its early victims. To a man of John Kelly’s strongly affectionate
nature, wrapped up in his home and family, these visitations falling
upon him like unmerciful disasters, one after another in quick
succession, proved well nigh irreparable. His health already
impaired, gave way entirely, and his friends were seriously
apprehensive of his own early demise.
It was in the midst of these afflictions that he was nominated for
Mayor against A. Oakey Hall. He was placed in nomination by the
Democratic Union, which held its convention at Masonic Hall,
November 18, 1868, and he received on the first ballot 240 votes, to
51 for John W. Chanler, and 1 each for John McKeon and Fernando
Wood. On the second ballot John Kelly received every vote in the
convention, and was declared the unanimous nominee for Mayor. A
committee was appointed by the chair, Mr. Roswell D. Hatch, to
notify Mr. Kelly of his nomination, and to invite him before the
convention. The chairman of this committee was Mr. Nelson J.
Waterbury. After some time Mr. Kelly entered the hall escorted by Mr.
Waterbury, by whom he was presented to the convention in
appropriate terms, as the reform candidate for Mayor.
He was warmly received, and made a brief speech, vigorously
denouncing the Tweed and Sweeny Ring, which had usurped control
of Tammany Hall. He referred in terms of praise to those honest
Democrats, many of whom he saw before him, who formerly like
himself had been identified with the Wigwam, but who had retired
from it in disgust, as he himself had done when the Ring obtained
control. “I see many gentlemen in this convention,” said Mr. Kelly,
“who formerly were associated with me in Tammany Hall, and who
felt the same grievances there which I myself have experienced. I
have no desire for this nomination, but while I have not sought it, I
will only say this, I shall stand by those who have so generously
nominated me for Mayor, and if elected, I will discharge the duties of
the office honestly and faithfully. In accepting your nomination I fully
realize that both yourselves and myself will have to work strenuously
against the corrupt men opposing us, if we expect to secure victory.
But by working together in good faith we can succeed, for the
people of New York feel the importance of the contest, and the
necessity of putting down the bad men who have obtained control of
the city government. I accept your nomination, and if elected will do
the best in my power to realize all your legitimate expectations.”[54]
Abram R. Lawrence was nominated for Corporation Counsel. The
candidacy of Mr. Kelly greatly alarmed the Ring leaders and their
Republican allies. The latter sought to control the Republican
convention which was held the next day, and force through a
straight Republican ticket for Mayor and Corporation Counsel, as the
most effective way to secure the election of A. Oakey Hall. But
fortunately there was a reform element among the Republicans, as
well as among the Democrats, and the opponents of the Ring were
in a majority in the Republican city convention. That excellent
citizen, Mr. Sinclair Tousey, was President of this convention. The
main struggle was between those who favored the endorsement of
John Kelly for Mayor, and, therefore, wished the convention to
adjourn over, and those who advocated the prompt nomination of a
straight Republican ticket. The latter class was led by Charles S.
Spencer, who vehemently demanded immediate action. But the
opponents of Spencer prevailed, and secured an adjournment to the
following Monday. “It was understood,” remarked the Herald of
November 20th, “that the party of compromise was engaged in
fixing up quite a neat little arrangement, by which the Republicans
would endorse the nomination of John Kelly for Mayor, in
consideration of having Mr. Shaw substituted for Mr. Lawrence as
candidate for Corporation Counsel. The compromisers gave out that
Spencer and the party of action were simply acting in the interest of
Tammany Hall in endeavoring to have the Republican convention
make regular nominations.”
In this campaign the Herald opposed John Kelly, and championed
A. Oakey Hall for Mayor. This was not evidence of any complicity on
the part of that paper in the misconduct of the Ring, for in 1868
there was no positive proof in possession of the public of the
criminality of the Ring, and hence the Herald or any other journal
was not justly obnoxious to unfavorable criticism at that early day in
the history of the plunderers for advocating the election of Hall. “The
Ring,” says Mr. Tilden in his history of its overthrow, “became
completely organized and matured on the 1st of January, 1869,
when Mr. A. Oakey Hall became Mayor. Its duration was through
1869, 1870 and 1871.”[55]
The morning after Mr. Kelly’s nomination the Herald declared for A.
Oakey Hall and against Kelly, in one of those plausible leading
articles by which it has so long and so remarkably influenced public
opinion for or against men and measures. The reference to Mr. Kelly
as a nabob was an adroit campaign stroke, and although he was
living quite unostentatiously in a modest three-story brick house at
the corner of 38th Street and Lexington Avenue, an impression was
created that he was surrounded by princely opulence, in the
fashionable quarter among the millionaires. The Herald editorial was
as follows:
“John Kelly is a good citizen and a respectable man; but he has
already been elected by the Tammany Democracy, to which he owes
all his past political favors, to the offices of Councilman, Alderman,
member of Congress, and twice to the valuable position of Sheriff of
New York, being the only man, we believe, who has held that
lucrative office a second term. John Kelly was brought up a lad in
the Herald office, when he first came to New York, and was well
brought up; but he went into politics in spite of his early training. We
supported him for office while he was poor and lived in the locality
of the Fourteenth Ward. Now that he has made himself a millionaire,
and lives like a nabob in the high locality of one of the most
fashionable avenues of uppertendom, we think he should be
satisfied, and give place to others who have not enjoyed such good
fortune.”
“If the Democrats nominate A. Oakey Hall, as it is said they will,
as their candidate for Mayor, he will no doubt be elected by a large
majority. He will suit those who take a pride in the dignity of the city,
because he is a man of superior ability, a profound thinker, an
eloquent talker, and understands thoroughly the details of the
municipal government.”[56]
The Ring men got thoroughly frightened after the adjournment of
the Republican City Convention without a nomination, for it was
becoming quite clear that independent citizens, both outside and
inside of the respective political parties, meant to support Mr. Kelly
for Mayor against the Ring candidate. This state of things caused the
Herald to discard special pleading respecting the “nabobs of
uppertendom,” and to redouble its attacks on Kelly. He was now
denounced as a deserter for having retired from Tammany Hall, and
joined the opponents of William M. Tweed. “The fight,” said the
Herald, “is to be made against the Democratic organization with the
object of breaking down Tammany, and thus giving the death-blow
to the regular Democracy in its stronghold. The Tribune, Times and
World are co-laborers in this work—the two former openly, and the
latter in an underhanded but not less vindictive manner. They are
preparing to unite on John Kelly, who has deserted the Democratic
organization for the purpose of leading the Republican forces in the
battle. District Attorney A. Oakey Hall will be the Democratic
nominee, and will no doubt be elected; but it will be one of the
greatest fights we have ever had over a Charter election, as the
breaking down of the Democratic organization at this end of the
State would be the death-blow of the party, and is therefore a stake
worth playing for by the Republicans, who feel the loss of power in
New York very severely.”[57]
Against this pretended but sham regularity, not only Mr. Kelly, but
Mr. Tilden also revolted. “Weighty pressure,” says Tilden, “was
brought on me from powerful men all over the State to ‘save the
party.’ I denied that the system of organization then in use in the city
had any moral right to be considered regular, or to bind the
Democratic masses. I told the State Convention that I felt it to be
my duty to oppose any man who would not go for making the
government of this city what it ought to be, at whatever cost, at
whatever sacrifice. If they did not deem that ‘regular,’ I would resign
as chairman of the State Committee.”[58]
The exertion made by Mr. Kelly in leaving a sick bed to go before
the Democratic Union City Convention to accept its nomination for
Mayor, increased the illness from which he suffered. His physician
called eminent doctors into consultation, and it was the opinion of
them all that his continuance in active political movements would
have a fatal result. This professional decision was communicated to
Mr. Kelly by that eminent physician, the late Dr. Marion Sims. Thus
admonished that the excitement of the campaign would kill him, Mr.
Kelly, on the 27th of November, reluctantly sent in his withdrawal
from the Mayoralty contest to the Executive Committee of the
Democratic Union, and the vacancy was filled by the nomination of
Mr. Frederick A. Conkling.
Mr. Kelly, who was a sufferer from insomnia, soon after sailed with
his two daughters for Europe. He made an extended tour in Europe,
Asia and Africa, visiting, among other places, the Holy Land. He first
went to Ireland as a pilgrim would return to the home of his fathers,
spending some time in the beautiful Island of Saints, where
Christianity made its only bloodless conquest in the world. During
fourteen hundred years, while other Christian nations have rushed
back into infidelity and again become Christian, Ireland has never
lapsed into infidelity, nor into a scoffing, Godless philosophy, the
invariable accompaniment of unbelief and paganism. After visiting
the various capitals of Europe,—London, Paris, Vienna, Berlin,
Madrid, St. Petersburg, and other places, he repaired to Rome, the
city of the soul, the Niobe of nations, shrine of saints and martyrs, of
doctors and confessors, where he spent a considerable period in rest
and retirement, and in viewing its wonderful ruins, monuments, and
churches. Repairing to Holy Land, Mr. Kelly remained for some time
at Jerusalem, the cradle of Christianity; which Titus, in fulfilment of
prophecy, left not a stone upon a stone of; where Christ had walked
about among the people, and where He died upon Calvary.
In contemplating scenes associated with the earthly life and death
of the Redeemer, the traveler no doubt derived comfort in his own
bereavements, dignified by such a fellowship of suffering as was
there. What a lesson of humility the ignominious Cross must have
preached to his reflective mind. He was leading a contemplative life,
and his letters at this period dwell much upon the Mount of Olives,
the Way of the Cross, and the Holy Sepulchre. He had read
somewhere in allegory of the contest in which the trees of the forest
are represented as debating among themselves who should be their
king. Had the contest occurred in the days of the Redeemer, small
chance the ignoble tree of the Cross would have had to win the
crown. Mr. Kelly had read Cardinal Wiseman’s beautiful thoughts on
the subject. “Apply the allegory,” said he once in a circle of his
friends, “and let us enter some forest of Judea filled with stately
trees, lofty, tapering pine, and royal cedar, and hear the proud
possessor give orders as to how their worth should be realized into
wealth. He says to the forester: ‘See that elegant and towering tree
which has reached the maturity of its growth, how nobly will it rise
above the splendid galley and bear itself in the fell fury of the wind,
without breaking or bending, and carry the riches of the earth from
one flourishing port to another. Cut it down and destine it for this
noble work. And this magnificent cedar, overcasting all around it with
the solemnity of its shade, worthy to have been built by Solomon
into the temple of God, such that David might have sung its praises
on his inspired lyre; let it be carefully and brilliantly polished, and
embarked to send to the imperial city, there to adorn those
magnificent halls, in which all the splendor of Rome is gathered; and
there, richly gilded and adorned, it shall be an object of admiration
for ages to come.’ ‘It is well, my lord,’ replies his servant, ‘but this
strange, this worthless tree, which seems presumptuously to spring
up, beneath the shadow of those splendid shafts, what shall we do
with it? it is fitted for no great, no noble work.’ ‘Cut it down, and, if
of no other use, why, it will make a cross for the first malefactor!’”
Strange counsels of men! The soaring pine dashed the freight that
it bore against the rocks, and rolled a wreck upon the beach. The
noble cedar witnessed the revels of imperial Rome, and fell by the
earthquake, or in the fire kindled by the barbarians, charred into
ashes. But that ignoble tree, spurned by proud man and put to the
most ignominious of uses, bore the price of the world’s redemption
upon Calvary, its every fragment has been gathered up, and
treasured and enshrined, and in every age it has been considered
worth all that the world dotes on, and sets its heart on. An Empress
crossed the seas and searched among the tombs of the dead for
that material wood of the Cross of Christ. For that holy rood was
built a magnificent church on Mount Sion. For it the Emperor
Heraclius made war on the King of Persia; and when he had
recovered it, bore it as his Master had borne it before, barefoot and
in humble garb to Calvary. For that tree Constantine the Great built a
noble church, yet standing among the ruins of the palaces of Rome,
and brought the very earth from the Savior’s own land, as though
none were worthy to be there save that upon which had first fallen
the precious blood of redemption. For eighteen hundred years this
relic has been the most priceless treasure of Christians. Its smallest
fragment has been enshrined and vestured in gold and precious
stones, and housed and sheltered in magnificent temples piled up
with the richest materials and noblest productions of art. The
ignoble tree which the world despised has conquered the world
itself.
Mr. Kelly’s correspondence at this time made it apparent that he
had ceased to feel interest in the busy trifles of politicians, and that
his thoughts were directed to problems of the moral world, to
reveries upon the mysteries of redemption, like that outlined in the
preceding allegory upon the Cross, and to the works of mercy, both
spiritual and corporal. He brought back from Palestine souvenirs and
patristic relics of much interest. He had familiarized himself with the
topography of the hallowed scenes of Holy Land, and those who
have heard him describe them and relate the history and traditions
connected with them, have been struck with his reverence as a
narrator, as well as with his closeness as an observer of manners,
customs and places. While he was abroad unfounded rumors
reached New York that John Kelly had withdrawn from the world, in
order to spend the remainder of his days in monastic retirement.
Perhaps this story originated from the circumstance that he travelled
much in the company of clergymen in Europe. Vicar-General Quinn
of New York was his companion on the Continent. The late Bishop
McGill of Richmond, Virginia, a man of ascetic tastes and profound
learning, often shared Mr. Kelly’s carriage in the latter’s drives about
Rome. Another thing which may have given color to the rumor was
the fact that Mr. Kelly had educated, and was still educating, many
young men for the ecclesiastical state, not only American youths, but
those of Irish and German and Swiss nationalities. While he was in
Switzerland his attention was directed by his daughters to a pious
little boy, the son of a poor gardener, who with another boy of
wealthy parentage, served at the altar every morning. The wealthy
man’s son soon departed for the University, when Mr. Kelly sent for
the son of the gardener, and finding that he wished to become a
religious, told him that he would afford him the means to carry out
his purpose, and amid the grateful tears and prayers of the boy’s
parents, he sent him to a renowned German University, and defrayed
all his expenses until he was graduated. That boy has since become
a learned scholar and minister at the altar. While Mr. Kelly was in
Rome he became warmly interested in the American College, a noble
seat of learning in that city for the training of young ecclesiastics for
the American Missions, and he generously established a bursary in
the College. He gave to its President, Dr. Chatard, who since has
been raised to the Episcopate, five thousand dollars for the
maintenance of this charitable Kelly foundation. It reflected no credit
upon the managers of the New York Cooper Institute meeting, held
in 1884, to denounce the spoliation of the Propaganda, of which the
American College at Rome is a part, to have omitted one of its
benefactors, and so prominent a representative man as John Kelly,
from the list of the officers and speakers of that meeting. Those
managers were then burning incense to Monsignor Capel, a clerical
gentleman of know—ledge, not knowledge, who thinks American
Catholics are too illiterate yet awhile to aspire to a University.
The beautiful pictures in stained glass, which adorn the windows
of St. Patrick’s Cathedral in New York, are, with the exception of the
examples in the French Cathedral in Chartres, perhaps unsurpassed
in modern times, as figured scenes from the Scriptures and lives of
the saints. In this pictorial religious epic is a beautiful window placed
there by John Kelly in memory of his lost ones, or more correctly of
those members of his family who have been called to the better life.
“Before quitting the Sanctuary,” says the writer of a pamphlet
descriptive of the exterior and interior of the Cathedral, “we will
bend our steps towards the Lady Chapel. The window in the first bay
represents the Presentation of the Blessed Virgin in the Temple. The
high priest, in gorgeous vesture, advances to receive the child, while
St. Joachim and St. Anne modestly remain standing behind. The
friends of the family are assembled to witness the ceremony. This
bears the inscription, ‘John Kelly—in memoriam.’”[59]
Some years before the completion of the new Cathedral, and while
Mr. Kelly was in Rome, he gave an order to a celebrated artist in that
city of art treasures to execute for him four great oil paintings
representing the Baptism of our Lord, the Marriage feast of Cana,
the Return of the Prodigal Son, and St. Patrick preaching at Tara. He
afterwards embraced two additional scenes from sacred history in
his scheme, the Ascension of Our Lord, and the Assumption of the
Blessed Virgin. The artist, Galliardi, produced a noble work after the
best masters. These six magnificent paintings were sent from Rome
to America as a present from Mr. Kelly to St. Patrick’s Cathedral, and
are the only paintings in canvas upon the walls of that grand church.
When he was in England he visited a region inhabited almost
entirely by miners—English, Irish and Welsh. Those people were, to
a great extent, ignorant of the truths of Christianity, and there were
no facilities in the wild mountain region they inhabited to improve
their moral condition. Working in the mines day and night, and
constantly exposed to death in the midst of their subterranean toil,
these poor people appealed to friends at a distance to send them a
clergyman to minister to their spiritual wants. The appeal was
answered, and the Reverend Mr. Dealy arrived there to open a
mission a short time before Mr. Kelly visited that part of England.
The clergyman found himself destitute of every worldly appliance for
a proper ministration of the functions of his spiritual office, no
church, no school-house, no charitable home or asylum for the sick
and helpless, all things, in a word, wanting, and no adequate means
to provide them. He was an excellent and zealous man, and he
stated his situation, and the necessities of the people to Mr. Kelly. He
told him that if he had the money to build a church and school-
house, incalculable good might be done. He poured his story into
sympathetic ears. Help was promised, and faithfully was the promise
kept. Mr. Dealy some time after, upon Mr. Kelly’s invitation, set sail
for America, and took up his residence in the latter’s house. When
Mr. Kelly reached home he organized a movement among those of
his immediate friends, whose opulence and charity admitted of the
appeal, and in the course of a few months Mr. Dealy, as he informed
the writer of these pages, was the fortunate possessor of a purse of
over twelve thousand dollars, inclusive of Mr. Kelly’s own handsome
donation. Those poor miners in England soon had their church, and
a school for their children, and their pastor had reason to bless the
day when he first made the acquaintance of the subject of this
memoir.
After John Kelly had re-entered the field of politics, and even
when immersed in public affairs, his charity and philanthropy
continued to be the controlling principles of his conduct. During the
past five or six years he has been a frequent lecturer in various cities
of the Union. His lectures, respectively upon the Sisters of Charity,
the Early Jesuit Missionaries in North America, and upon the Irish
Settlers in North and South America, were replete with historical
information and sound practical instruction, and wherever he
appeared on the platform as a lecturer he always drew crowded
houses. Mr. Kelly realized from his lectures, which he delivered
repeatedly in the North, South and West, over fifty thousand dollars,
and this immense sum he gave in charity to educate and clothe the
poor, to build schools, or to lift the burden of debt from charitable
institutions. His heart was in his work. He would not allow one penny
of the proceeds of his lectures to be diverted from the sweet uses of
charity for his traveling expenses, but in every instance, wherever he
went to lecture, he insisted on paying his railroad fare, and hotel
bills, out of his own pocket.
Bagenal, the London traducer of the American Irish, with
unblushing mendacity, classes John Kelly as a leader of “shoulder-
hitters and ballot-stuffers,” and ignorantly accuses him of being an
enemy of Irish colonization in the West. The simple truth is that Kelly
is one of the originators and prime leaders in the movement to get
poor emigrants out of the overcrowded Eastern cities, and has
contributed thousands of dollars to make their colonization in the
West a success.
Dr. Ireland, Bishop of St. Paul, Minnesota, one of the great
pioneers in this benign scheme, while speaking kindly of Mr. Bagenal
in a letter to the present writer, still shows how erroneous he is in
his strictures upon Mr. Kelly. The Bishop’s comment upon Bagenal, is
as follows: “He is mistaken, of course, in his remarks about Mr. John
Kelly. But I do not think he will be sorry to be set right. He mixes up
Mr. Kelly with the average politicians of New York—not knowing, as I
know, Mr. Kelly’s exceptional qualities, his sterling honesty, his true
love for his fellow-Irishmen, and his general nobility of character.”[60]
When he retired from politics in 1868, Mr. Kelly had resolved to
enter upon that field no more. Chastened by domestic affliction, and
loss of health, the plan of his life was changed. Public station had
lost its charm for him. To feed the hungry, clothe the naked, and
open the doors of colleges, or advanced schools, to those whose
talents were good, but who were too poor to gain admittance, these
things afforded to him his greatest pleasure. He sought out the
companionship of holy men, and of holy books. Thomas à Kempis
became his vade mecum. He took more delight in the pages of the
Following of Christ than he had ever known in the conflicts of
politics, either in the halls of Congress or the city of New York. It
was not altogether surprising, therefore, that people’s conjectures
should consign him to the prospective seclusion of a monastery, and
that rumors to that effect should have gained circulation. The New
York Times, on one occasion, shortly after Mr. Kelly’s second
marriage, made editorial reference to these rumors, and spoke of
him as that remarkable individual who had escaped being a monk at
Rome, in order to become the nephew of a Cardinal in America.
These revelations of the inner life of John Kelly are not laid before
the public without a great deal of reluctance. Some may think it
were better to keep them back until after his death, and the writer
knows perfectly well that no one else would prohibit their publication
at any time, or under any conceivable circumstances more sternly
than John Kelly himself. But these pages have been written without
consultation with any human being in the world, and recollecting the
unparalleled and shameful abuse which this man has been subjected
to for doing his duty as God has given him to see it, the writer is
resolved to tell the truth about him, and let the unprejudiced reader
know something of his real character. Indeed hardly a tithe of those
charities and good works of John Kelly which are within the personal
knowledge of the present writer, have been mentioned in these
pages. During the war for the Union, especially, were the kindly
impulses of his nature displayed. He went about among the hospitals
visiting and cheering the sick and despondent, supplying articles for
their relief and money for their wants, and doing what he could for
the wounded. He did not confine these ministrations to the hospitals
in New York, but went to Washington and got a pass from Edwin M.
Stanton, Secretary of War, whom he had known well in former years,
to visit the Army of the Potomac, and particularly the camp
hospitals. Thither he repaired, and extended his aid not only to New
York soldiers but to those of other States, with characteristic zeal
and liberality. A letter was published in the New York World,
November 1st, 1875, from Mr. James Murphy, in which reference is
made to one of Mr. Kelly’s visits to the army in Virginia.
“I well recollect,” said the writer, “that thirteen years ago, when I
was a soldier in the Second Army Corps of the Army of the Potomac,
and stationed at Stafford Heights, Virginia, opposite Fredericksburg,
I had the pleasure of meeting Mr. John Kelly. His mission was one of
the noblest that man ever followed. He was going round from
hospital to hospital, and from tent to tent, visiting the sick and
wounded of the poor and neglected soldiers of the New York
regiments, to see to their wants, and alleviate their sufferings as
much as lay within his power, and questioning them as to their
treatment as compared with the treatment of the soldiers of other
States.” Many persons in the border States, as those adjoining the
scene of military operations were called, who were guilty of no
disloyal acts, were nevertheless made victims of spies and
detectives, and they and their families suffered great hardships. One
of these was Mr. John Henry Waring, a prominent and wealthy
citizen of Prince George’s County, Maryland, whose property was
confiscated, whose large family, mostly ladies, were banished, and
who was himself imprisoned for the war in Fort Delaware. This was
the work of Baker, the notorious detective, and a more cruel
persecution hardly occurred during the war. Mr. Kelly was appealed
to on behalf of Mr. Waring, and after he was satisfied that injustice
had been done to that excellent citizen, he went to Washington and
saw Mr. Lincoln, and Secretaries Stanton and Montgomery Blair, on
behalf of the Waring family and estate. But Baker had poisoned the
mind of Stanton against the Warings, and, notwithstanding the
Secretary’s regard for Mr. Kelly, he refused the clemency that was
asked. Mr. Kelly returned to New York, and enlisted in Mr. Waring’s
favor the powerful co-operation of Governor Morgan, Archbishop
Hughes, Thurlow Weed, James T. Brady, and about fifty other
leading men, and, thus strengthened, he renewed the appeal for
justice and executive clemency. Postmaster General Blair had
become warmly interested in the case, and to him Mr. Kelly confided
the petition of the citizens of New York named above, and Mr. Blair
in conjunction with Mr. Kelly ceased not to press the case until Mr.
Waring was liberated, his family were recalled from banishment, and
his beautiful home and plantation on the Patuxent river were
restored to him.
Mr. Kelly returned from Europe in the fall of 1871, much improved
in health, but not yet restored to his old vigor. The present writer
gave to Mr. J. E. Mallet, of Washington, D. C., who was going to
Europe, a letter of introduction to Mr. Kelly, while the latter was
abroad. Although they were near each other several times in Europe,
Mr. Mallet did not become acquainted with Mr. Kelly until they
accidentally met on the same steamship, the Republic, in returning
to America. In a letter published in the Baltimore Catholic Mirror, Mr.
Mallet gave an interesting account of this voyage, and of the
amusements improvised on shipboard. “One evening,” said he, “we
organized a musical and literary entertainment. The chairman made
a speech, a lady played a fine musical composition, a gentleman
gave a recitation, a young bride sang a beautiful ballad, Hon. John
Kelly, of New York, sang in excellent style an amusing Irish song,
then a duet was sung by two ladies, some one sang a French song,
Father Sheehy sang an Irish ballad on St. Patrick, and the
entertainment concluded, and the assemblage dispersed during the
reading by the Rev. Dr. Arnot, of one of his old sermons.”
“A valued friend had given me a letter of introduction to Mr. Kelly,
to present in France or Switzerland, but I met that gentleman only
on the wharf at Liverpool, and then almost accidentally. Mr. Kelly has
travelled throughout Europe and the Holy Land, and is one of the
most interesting travelling companions whom I have ever met. I was
particularly pleased with his manner of presenting the true history
of, and reasons for certain religious and national practices in Ireland
and Italy, in opposition to the theories and suppositions of certain of
our fellow-voyagers, who ignorantly calumniated the one, and
ridiculed the other.”
During the three years of Mr. Kelly’s absence in Europe, New York
had been given over to every form of official rascality and plunder.
No sooner had he reached the city than he was besieged by leading
citizens, such as Mr. Tilden, Mr. Schell, Mr. Hewitt, Mr. Belmont, Mr.
Chanler, Mr. Clark, Mr. Green and others, all of whom urged him to
take the lead in a movement for the overthrow of the Tweed Ring.
To each one of these gentlemen he said that it was not in accord
with the plan of life which he had marked out for himself for the
future, to re-enter the field of active politics. But his friends
redoubled their importunities. They told him there was no other man
in New York, scarcely one in the United States, so well fitted as
himself to head such a movement, and that in the lifetime of but
very few persons did so grand an opportunity offer itself to serve the
people as that which now awaited him. His friends finally prevailed,
his private plans were changed, and his memorable reappearance in
New York politics occurred in the year 1872. “My health remains
about the same as when I saw you,” said Mr. Kelly, in 1872, in a
letter to the present writer. “I was compelled to take part, for the
reason that my old associates would not take No for answer. My
active participation has not helped me much in point of health, nor
does it seem possible for me to live in New York without being more
or less mixed up in politics.” In an interview published in the New
York World, October 18, 1875, Mr. Kelly explained more fully how he
was induced to return to politics. Details omitted, the salient points
of that interview were as follows: “When I returned from Europe in
the fall of 1871, it was my intention to have nothing to do with
politics at all. I had been sorely afflicted by the loss of my family,
and I wanted to spend the rest of my life as a private business man.
I was met by a number of leading men, who told me that during my
absence the Democratic party in the city had become utterly
demoralized, and that the Grant Republicans, taking advantage of
this state of affairs, had come into full possession in this great
Democratic city, and they begged me to assume an active part. I
had hundreds of the leading men in the city here at my house,
asking me to take hold and help them up. After much importunity, I
consented, and threw my whole heart into the work. I suppose I
have some foresight. I think I generally see things pretty clearly, and
this is probably why they trust to my judgment. Whenever I fail to
win their confidence it will be an easy matter for them to dispense
with me. I am not commissioned as a leader by any constituted
authority. But as what power and influence I have depend entirely
upon the good will and confidence of the people who choose to
recognize me as a leader, and listen to my advice, I am wholly in
their hands, and they can keep me or reject me any day.”
Mr. Kelly’s part in public affairs prior to 1872 had been creditable
and marked by ability, but there were other public men who, in like
circumstances, had attained equal or greater distinction. In the year
1872 he was called upon to prove whether he was endowed with
that highest of all the gifts of Heaven, the capacity to lead men in a
supreme emergency, and it is not the language of eulogy to say that
he displayed consummate ability as such a leader; and that his
courage, coolness and good judgment enabled him to achieve
results which no other citizen of New York, with similar resources at
command, and similar obstacles in his way, could have
accomplished.
yours truly
John Kelly
(AT THE AGE OF 50 YEARS.)

In a city of a million inhabitants, where a Government had


prevailed for years, such as disgraced Rome in the days of Caligula,
when the tyrant made his horse a Roman Consul; or in the epoch
from Tiberius to Nero, when folly, crime and profligacy ran riot in all
departments of the Empire, such as Tacitus describes so vividly in
the Annals, and in the immortal Life of Agricola; in such a state of
affairs it was an enormous task for John Kelly to head a successful
movement against a Ring intrenched in office, with millions of stolen
money at command, and backed up by a purchased Legislature. This
task he undertook and accomplished, and history will record the fact
on its imperishable page that the gallant attack upon the Ring in the
Courts and Legislature, by Charles O’Conor and Samuel J. Tilden,
was not crowned with final success until John Kelly carried the war
into Tammany Hall, and drove the Ring politicians from its portals.
O’Conor and Tilden scotched the snake in 1871, and John Kelly killed
it in 1872. Tammany Hall, the cradle of American Democracy, whose
patriotic Sachems in the year 1819 were addressed in a speech by
Andrew Jackson,[61] and in long friendly letters at the same period
by Thomas Jefferson, the elder Adams, and James Madison,[62] was
rescued from disgrace and placed again in control of honest men in
1872 by John Kelly. Not only the political organization, but the
Tammany Society was wrested from the control of the Ring. No
political contest in the history of the city of New York was more
stubbornly fought on both sides, or has been followed by happier
results to the people at large. If great public service entitles a man
to rank among the worthies of the Republic, John Kelly won that title
when he succeeded in expelling the Ring men from Tammany Hall.
His victory marked an epoch. The Board of Sachems of the
Tammany Society for 1871, and the Board for 1872 tell the story of
this great revolution:
1871. 1872.
—— ——
Grand Sachem: Grand Sachem:
William M. Tweed. Augustus Schell.
—— ——
Sachems: Sachems:
Richard B. Connolly, Charles O’Conor,
Peter B. Sweeny, Samuel J. Tilden,
A. Oakey Hall, John Kelly,
Joseph Dowling, Horatio Seymour,
Samuel B. Garvin, Sanford E. Church,
etc. August Belmont,
Abram S. Hewitt,
etc.

On the retirement of Mr. Belmont from the Chairmanship of the


National Democratic Committee, in 1872, that distinguished position
was tendered to Mr. Kelly at the meeting of the National Convention
in Baltimore. But domestic affliction had again visited him about that
time, in the death in New York of his only surviving daughter, his
elder daughter having died some time before in a city in Spain,
where her father had taken her in a vain pursuit of health. Cast
down by these afflictions, Mr. Kelly declined the Chairmanship of the
National Committee of his party, but suggested his old friend Mr.
Schell, who was elected Chairman. “Who is John Kelly?” asked some
of the younger delegates at Baltimore, when they heard his name
mentioned as their first choice by the New York delegation. They
were informed by Mr. Schell that Mr. Kelly was detained at home in
the house of mourning, but that he was a great leader in New York
politics, and a true patriot in public life; and that he had sat in
Congress before many of those young men were well out of the
nursery.
It was about this time that the Committee of Seventy set out to
reform the city government, but those worthy old gentlemen soon
became engaged in an amusing scramble for office, and beyond
putting their chairman, General Dix, in the Governor’s chair, and
another of their number, Mr. Havemeyer, in that of Mayor, they did
not set the river on fire, nor perform any of the twelve labors of
Hercules. As soon as the Committee of Seventy became known as
office-seekers, their usefulness was at an end. John Kelly sought no
office, for he had to fight a battle with office-holders, then a
synonym for corruptionists, and he appreciated the magnitude of the
struggle more correctly than to leave it in anybody’s power to say
that the Ring men and the Reform element, the latter marshalled by
Tilden and himself, were fighting over the offices. A mere scramble
for office between the Ins and Outs is always a vulgar thing. When
they became place-hunters, the Committee of Seventy ceased to be
reformers. Kelly, with better statesmanship, sought no office, and
would accept none. When every other event in his life has been
forgotten, his memorable battle in the County Convention of 1872
will still be remembered. A fiercer one was never fought in American
politics. To employ the words of Mr. Tilden, in his history of the
overthrow of the Tammany Ring, Kelly had to confront on that
occasion, “an organization which held the influence growing out of
the employment of twelve thousand persons, and the disbursement
of thirty millions a year; which had possession of all the machinery
of local government, dominated the judiciary and police, and swayed
the officers of election.”[63]
Harry Genet was leader of the Ring men in the Convention. Prize-
fighters and heelers swarmed upon the floor; and when Samuel B.
Garvin was again placed in nomination for District-Attorney, the
fighters and heelers roared themselves hoarse with applause. Mr.
Kelly took the floor to oppose Garvin, when he was interrupted by
Genet. He replied to the latter in scathing language, arraigned him
and Garvin with the utmost severity, and although hissed by the
hirelings of the Ring, and interrupted by volleys of oaths, John Kelly
kept the mob in sufficient restraint until he caught the eye of the
chairman, and moved an adjournment to 3 o’clock the next day. Mr.
Schell, who was in the chair, put the motion to adjourn, and it was
carried, in spite of the protests of the mob.
The next day the same emissaries of the Ring were there to
overwhelm the Convention again, but this time Kelly was prepared
for them. He had a force stationed at the doors of Tammany Hall,
and no man, not a delegate to the Convention, and not provided
with a delegate’s ticket, was allowed to enter the building. The police
and city authorities were on the side of the desperadoes, but no
policeman was allowed inside the premises. This bold stand of Mr.
Kelly had the desired effect. By his personal intrepidity, and
readiness to resist attack, he cowed the rowdies, and no others but
delegates got into the Convention. Garvin was defeated, and Charles
Donohue was nominated for District-Attorney. Abram R. Lawrence
was nominated for Mayor. It was in that day’s struggle that the
backbone of the Ring was broken, and it ceased to be a compact
organization, and melted away after that day’s defeat. Havemeyer of
the Committee of Seventy was elected Mayor, with Lawrence a close
second, and O’Brien a bad third. Phelps beat Donohue for District-
Attorney. But Reformed Tammany, in spite of predictions to the
contrary, polled a surprisingly large vote, and although it did not
elect, it was a vote of confidence in John Kelly, and discerning men
saw that the future belonged to the old organization. Mr. Havemeyer,
who had been an excellent Mayor in early life, now proved a failure.
His defiance of the Supreme Court in the case of Police
Commissioners Charlick and Gardner raised a storm of indignation
about his head, and led to his reprimand by Governor Dix, who
threatened his removal from office. Charlick and Gardner had been
indicted for a violation of the election laws, and Mr. Kelly was very
active in bringing on their trial. They were convicted by the Jury, and
sentenced by Judge Brady to pay a fine of $250 each, but conviction
carried with it a still severer penalty, forfeiture of their offices and
disability to fill them by reappointment. The Mayor’s attempt to
reappoint them was an act of surprising folly, but when the
Governor’s reprimand reached him, with the statement that his age,
and near completion of his term of office, alone saved him from
removal for contumacy, Mayor Havemeyer’s rage vented itself in an
extravagantly abusive attack on John Kelly. He held Mr. Kelly
responsible for the trial of Charlick and Gardner, and after
astounding the community by defying the Supreme Court with a vain
attempt to re-instate the guilty officials, he brought the matter to an
impotent conclusion by pouring out a torrent of abuse upon John
Kelly, and assailing his record for honesty when he was Sheriff of
New York. During all the long years which had elapsed since Mr.
Kelly had held that office, not one syllable had ever been uttered
derogatory to his exalted character for honesty as Sheriff, until
Mayor Havemeyer made his reckless charges. Smarting under a
sense of humiliation after the Gardner-Charlick fiasco, the Mayor
allowed bad temper to get the mastery of his judgment, and the
explosion of wrath against Mr. Kelly followed. The animus of the
attack was perfectly apparent on its face, and the good sense of the
people was not imposed upon by the revengeful ebullitions of the
angry old gentleman. Mr. Kelly promptly instituted a suit for
damages, but on the very day the trial began, by a remarkable
coincidence Mayor Havemeyer, stricken by apoplexy, fell dead in his
office. The passionate events of the moment were forgotten, and a
sense of sorrow pervaded the community. Mr. Havemeyer’s long and
honorable career was remembered, and the unfortunate passage in
his last days was generally, and justly imputed to the misguided
counsels of his friends.
The Tammany Democrats were completely victorious at the
election of 1873. Those able lawyers, Charles Donohue and Abram
R. Lawrence, were elected to the Supreme Court. The late William
Walsh and the late Wm. C. Connor, both excellent men, were elected
County Clerk and Sheriff. Again, in 1874, victory perched on the
standards of Mr. Kelly. This time its dimensions were larger. In
addition to a Mayor (Mr. Wickham), and other city officers, a
Governor (Mr. Tilden), and other State officers, were chosen by
overwhelming Democratic majorities.
Mr. Kelly had been the first man to suggest Mr. Tilden’s nomination
for Governor. His splendid services in the war on the Ring pointed
him out as the fit candidate of his party. Tired out, after his long
labors, Mr. Tilden, in 1874, went to Europe to enjoy the first holiday
he had allowed himself for years. But such was his confidence in the
judgment of Mr. Kelly, that a cable message from that friend was
sufficient to cause him to cancel his engagements in Europe, give up
his tour, and take passage in the first steamer for New York. The
Canal Ring was in motion against Tilden’s nomination, and Kelly, who
had found this out, thought there was no time for delay. Tilden at
first expressed disinclination for the office, but the Tammany Chief
had set his heart on his nomination, and the author of these pages
has heard Mr. Tilden say that Mr. Kelly’s persistency finally controlled
his decision, and won his acquiescence. One of the leading delegates
to the Convention of 1874 was Mr. William Purcell, editor of the
Rochester Union. “To John Kelly,” said Purcell editorially, shortly after
the election, “more than any other man does Governor Tilden owe
his nomination and his majority at the election. Governor Tilden was
personally present at the nominating convention, in close counsel
with Mr. Kelly, than whom he lauded no man higher for his personal
honesty, his political integrity, and his purity of purpose.”
Mr. Tilden was a constant visitor at Mr. Kelly’s house during this
period, and no two men could have evinced more respect and
friendship for each other. The last time Mr. Tilden attended a
meeting in Tammany Hall was at the election of Sachems on the
third Monday of April, 1874. The late Matthew T. Brennan and others
ran an opposition or anti-Kelly ticket, and so anxious was Mr. Tilden
for the defeat of this movement that he came down to the Wigwam,
and took an active part in favor of the regular ticket. He sat with Mr.
Kelly, and when the result was announced warmly congratulated him
upon the victory.
In the latter part of January, 1875, a few weeks after Mr. Tilden’s
inauguration as Governor, the author spent a morning at his
residence in Gramercy Park, and there met ex-Governor Seymour
and Mr. Kelly, in company with Governor Tilden. The conversation of
these three distinguished men, in the abandon of social intercourse
around the hearthstone of Gramercy Park, was very agreeable and
entertaining. The author was an attentive listener and observer, and
afterwards, on the same day, wrote out in his diary his impressions
of these three celebrated New Yorkers. Although ten years have
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like