75% found this document useful (4 votes)
864 views

Learning PHP MySQL JavaScript Early Release 6th Edition Robin Nixon all chapter instant download

Release

Uploaded by

goinessibe
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
75% found this document useful (4 votes)
864 views

Learning PHP MySQL JavaScript Early Release 6th Edition Robin Nixon all chapter instant download

Release

Uploaded by

goinessibe
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/ 52

Download the full version of the textbook now at textbookfull.

com

Learning PHP MySQL JavaScript Early Release


6th Edition Robin Nixon

https://textbookfull.com/product/learning-php-
mysql-javascript-early-release-6th-edition-robin-
nixon/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Learning PHP, MySQL & JavaScript, 6th Edition Robin Nixon

https://textbookfull.com/product/learning-php-mysql-javascript-6th-
edition-robin-nixon/

textbookfull.com

Learning PHP MySQL JavaScript With jQuery CSS HTML5 5th


Edition Robin Nixon

https://textbookfull.com/product/learning-php-mysql-javascript-with-
jquery-css-html5-5th-edition-robin-nixon/

textbookfull.com

Learn PHP 8: Using MySQL, JavaScript, CSS3, and HTML5


Second Edition Steve Prettyman

https://textbookfull.com/product/learn-php-8-using-mysql-javascript-
css3-and-html5-second-edition-steve-prettyman/

textbookfull.com

Racial Disproportionality and Disparities in the Child


Welfare System Alan J. Dettlaff

https://textbookfull.com/product/racial-disproportionality-and-
disparities-in-the-child-welfare-system-alan-j-dettlaff/

textbookfull.com
Faith and Heritage A Christian Nationalist Anthology Faith
And Heritage

https://textbookfull.com/product/faith-and-heritage-a-christian-
nationalist-anthology-faith-and-heritage/

textbookfull.com

The Oxford Handbook Of Plato Gail Fine

https://textbookfull.com/product/the-oxford-handbook-of-plato-gail-
fine/

textbookfull.com

The ESC Textbook of Vascular Biology 1st Edition Rob Krams

https://textbookfull.com/product/the-esc-textbook-of-vascular-
biology-1st-edition-rob-krams/

textbookfull.com

A Clinician s Guide to Pemphigus Vulgaris 1st Edition


Pooya Khan Mohammad Beigi (Auth.)

https://textbookfull.com/product/a-clinician-s-guide-to-pemphigus-
vulgaris-1st-edition-pooya-khan-mohammad-beigi-auth/

textbookfull.com

Advances in Visual Informatics 5th International Visual


Informatics Conference IVIC 2017 Bangi Malaysia November
28 30 2017 Proceedings 1st Edition Halimah Badioze Zaman
Et Al. (Eds.)
https://textbookfull.com/product/advances-in-visual-informatics-5th-
international-visual-informatics-conference-ivic-2017-bangi-malaysia-
november-28-30-2017-proceedings-1st-edition-halimah-badioze-zaman-et-
al-eds/
textbookfull.com
Behavior Management: From Theoretical Implications to
Practical Applications 3rd Edition John W. Maag

https://textbookfull.com/product/behavior-management-from-theoretical-
implications-to-practical-applications-3rd-edition-john-w-maag/

textbookfull.com
Learning PHP, MySQL &
JavaScript
SIXTH EDITION

With Early Release ebooks, you get books in their earliest form—the
author’s raw and unedited content as they write—so you can take
advantage of these technologies long before the official release of these
titles.

With PHP 8, MySQL 8, PDO, CSS, HTML5, jQuery


& React

Robin Nixon
Learning PHP, MySQL & JavaScript
by Robin Nixon
Copyright © 2021 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://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com.

Editor: Rachel Roumeliotis

Production Editor: Caitlin Ghegan

Copyeditor: TK

Proofreader: TK

Indexer: TK

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Catherine Dullea

July 2009: First Edition


August 2012: Second Edition
June 2014: Third Edition
December 2014: Fourth Edition
May 2018: Fifth Edition
November 2021

Revision History for the Early Release


2021-02-04: First release

See http://oreilly.com/catalog/errata.csp?isbn=9781492093817 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-492-09381-7
[LSI]
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, React, 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 websites. 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 responsive web
design will obtain a thorough grounding in the core technologies of PHP,
MySQL, JavaScript, CSS, and HTML5, and you’ll learn the basics of the
React library and React Native Framework, 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 knowledge of PHP, MySQL, JavaScript, CSS, or HTML5—
although if you do, your progress through the book will be even quicker.

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. You will then 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 simple functions and event handling to accessing the Document
Object Model, in-browser validation, and error handling. You’ll also get a
comprehensive primer on using the popular React 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 discovering how the React libraries can
make your development job a great deal easier. You’ll then move on to the
final section on the interactive 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
constitute a fully functional social networking website.
Along the way, you’ll find plenty of advice on good programming practices
and tips that can 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 reference books:

Dynamic HTML: The Definitive Reference by Danny Goodman


PHP in a Nutshell by Paul Hudson
MySQL in a Nutshell by Russell Dyer
JavaScript: The Definitive Guide by David Flanagan
CSS: The Definitive Guide by Eric A. Meyer and Estelle Weyl
HTML5: The Missing Manual 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. Also used for database, table,
and column names.

Constant width

Indicates commands and command-line options, variables and other


code elements, HTML tags, and the contents of files.

Constant width bold


Shows program output and is used to highlight sections of code that are
discussed in the text.

Constant width italic


Shows text that should be replaced with user-supplied values.

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

WARNING
This element indicates a warning or caution.

Using Code Examples


Supplemental material (code examples, exercises, etc.) is available for
download at github.com/RobinNixon/lpmj6.
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 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 set 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
significant amount of example code from this book into your product’s
documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually
includes the title, author, publisher, and ISBN. For example: “Learning
PHP, MySQL & JavaScript 6th Edition by Robin Nixon (O’Reilly).
Copyright 2021 Robin Nixon, [[[ISBN NUMBER GOES HERE]]].”
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.

O’Reilly Online Learning

NOTE
For more than 40 years, O’Reilly Media has provided technology and business training,
knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their knowledge and
expertise through books, articles, and our online learning platform.
O’Reilly’s online learning platform gives you on-demand access to live
training courses, in-depth learning paths, interactive coding environments,
and a vast collection of text and video from O’Reilly and 200+ other
publishers. For more information, visit http://oreilly.com.
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 [[[ERRATA URL GOES
HERE]]].
To comment or ask technical questions about this book, send email to
bookquestions@oreilly.com.
For news and more information about our books and courses, see our
website 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 thank Senior Content Acquisitions Editor, Amanda Quinn,
Content Development Editor, Melissa Potter, and everyone who worked so
hard on this book, including ???, ??? & ??? for their comprehensive
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
technical reviews, ??? for overseeing production, ??? for copy editing, ???
for proofreading, ??? for creating the index, Karen Montgomery for the
original sugar glider front cover design, ??? for the latest book cover, my
original editor, Andy Oram, for overseeing the first five editions, and
everyone else too numerous to name who submitted errata and offered
suggestions for this new edition.
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 problem. 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 producing 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, connecting several hundred
thousand computers, so Tim Berners-Lee (a CERN fellow) devised a
method of navigating 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.
Today we take these tools for granted, but back then, the concept was
revolutionary. The most connectivity so far experienced 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!
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 using it
a rich and dynamic experience.

NOTE
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 are sent 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. Some of
these in-between devices can also help speed up the internet by storing
pages or information locally in what is called a cache, and then serving this
content up to clients directly from the cache rather than fetching it all the
way from the source server.
A web server can usually handle multiple simultaneous connections, and
when not communicating with a client, it 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).
Figure 1-1. The basic client/server request/response sequence

The steps in the request and response sequence are as follows:


1. You enter http://server.com into your browser’s address bar.
2. Your browser looks up the Internet Protocol (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 server retrieves the page and returns it to the browser.
7. Your browser displays the web page.
For an average web page, this process also 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 looks 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 (DNS) to find the server’s
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. For instance, you may click
on a picture of a raincoat. Then PHP will put together a request using the
standard database language, SQL—many of whose commands you will
learn in this book—and send the request to the MySQL server. The MySQL
server will return information about the raincoat you selected, and the PHP
code will wrap it all up in some HTML, which the server will send to your
browser (see Figure 1-2).
Figure 1-2. A dynamic client/server request/response sequence

The steps are 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 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.
6. With the home page now in memory, the web server notices that it
is a file incorporating PHP scripting and passes the page to the
PHP interpreter.
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains SQL 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 elements work together, in practice you don’t really need to concern
yourself with these details, because they all happen automatically.
The 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 language) and server-side scripting
—inserting the contents of one file (or the output of running a local
program) into another one dynamically.
Once the dust had settled, three main technologies stood head and shoulders
above the others. Although Perl was still a popular scripting language with
a strong following, 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 essential 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
asynchronous communication (exchanging data between a client and server
after a web page has loaded). Using asynchronous communication, 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 forward, 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 just about anything a website would
need in order to find and serve up data to browsers. When PHP allies with
MySQL to store and retrieve this data, you have the fundamental parts
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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 building highly dynamic and interactive websites—especially as there is
now a wide range of sophisticated frameworks of JavaScript functions you
can call on to really speed up web development, such as the well-known
jQuery, which until very recently was one of the most common way
programmers access asynchronous communication features, and the more
recent React JavaScript library which has been growing quickly in
popularity, and is now one of the most widely downloaded and
implemented frameworks, so much so that since 2020 the Indeed job site
lists more than twice as many positions for React developers than for
jQuery.

MariaDB: The MySQL Clone


After Oracle purchased Sun Microsystems (the owners of MySQL), the
community became wary that MySQL might not remain fully open source,
so MariaDB was forked from it to keep it free under the GNU GPL.
Development of MariaDB is led by some of the original developers of
MySQL and it retains exceedingly close compatibility with MySQL.
Therefore, you may well encounter MariaDB on some servers in place of
MySQL—but not to worry, everything in this book works equally well on
both MySQL and MariaDB, which is based on the same code base as
MySQL Server 5.5. To all intents and purposes you can swap one with the
other and notice no difference.
Anyway, as it turns out, many of the initial fears appear to have been
allayed as MySQL remains open source, with Oracle simply charging for
support and for editions that provide additional features such as geo-
replication and automatic scaling. However, unlike MariaDB, MySQL is no
longer community driven, so knowing that MariaDB will always be there if
ever needed will keep many developers sleeping at night, and probably
ensures that MySQL itself will remain open source.
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 even more 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.
NOTE
If you intend to enter the PHP examples in this book into a program editor 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 facilitate 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 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
dynamically unless you also have a means to track the information users
provide to your website as they use it. 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');

You will previously have issued other commands to create the database and
table and to set up all the correct fields, but the SQL INSERT command
here shows how simple it can be to add new data to a database. SQL is a
language designed in the early 1970s that is reminiscent of one of the oldest
programming languages, COBOL. It is well suited, however, 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 associated 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
combine related data sets to bring related pieces of information together,
ask for results in a variety of orders, make partial matches when 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 directly access the MySQL command-line interface yourself. 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 to efficiently run common operations
within MySQL, rather than creating them out of multiple PHP calls to
MySQL.
Using JavaScript
The oldest of the three core technologies discussed 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 validity 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 it is less
necessary these days to have to optimize your code for different browsers.
However, there remain millions of users using legacy browsers, and this
will likely be the case for a good many years to come. Luckily, there are
solutions for the incompatibility problems, 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 does by writing the text
Random documents with unrelated
content Scribd suggests to you:
his patron, by whom he was employed to manage an affair requiring
great delicacy as well as firmness in handling it. This was nothing
less than to make his way through the heart of the French armies,
and to open a communication first with Murat, and afterwards with
the Austrian Government. It was while so employed that Mr Graham
became acquainted with Sir Charles, then Captain Napier, of the
Euryalus frigate, of whom he conceived a very high opinion, and with
whom, in due course of time, he quarrelled violently.
Mr Graham, after accompanying Lord William Bentinck through
his campaign in Italy, returned to England, and began, early in 1815,
to feel his way towards a seat in the House of Commons. It was a
season, as a few of our readers may possibly recollect, of great
suffering among the people, and anxiety to the Government. The
renewal of the war with France added upwards of one hundred
millions to the national debt; and peace, when it was purchased by
the battle of Waterloo, seemed to bring only poverty in its train. A
spirit of general disaffection pervaded the masses, and recourse was
had to stringent measures in order to preserve the public peace.
Drawn away by old associations, Mr Graham joined the ranks of the
ultra-Liberals. Lord Archibald Hamilton was his kinsman, and Lord
Folkstone, Sir Francis Burdett, and Lord Althorpe, won his political
affections. His father, on the other hand, continued to profess the
Tory principles in which he had grown old; so that, but for the
sympathy of Lady Catherine, the young man might have found
himself ill at ease as an inmate of Netherby Hall. Accordingly, he
spent but little of his time there in the interval between his return
from abroad and the general election of 1818; when, being assured of
the support of Lord Milton, and obtaining through his mother letters
of recommendation to Mr Wilberforce, he entered the lists as a
candidate for Hull, and fought a hard battle to a successful issue.
We confess not to hold the name of William Wilberforce quite in
the same degree of veneration in which it is held by his sons. We
believe that there was no slight sprinkling of what is vulgarly called
humbug in the good man’s character; and we find some
corroboration of this suspicion in the fact that, though well aware of
Mr Graham’s ultra-Liberal opinions, he nevertheless, because of the
affection with which he regarded Lady Catherine, recommended her
son to the constituency of Hull. A like charge may, we think, be
brought against Dean Milner, subject, of course, to extenuating
circumstances. Dean Milner conscientiously believed that the
admission of Roman Catholics to political power would be
tantamount to the establishment of idolatry in Great Britain: yet he,
too, because Lady Catherine sat at his feet, gave a testimonial to her
son, whom he knew to be an advocate of Catholic emancipation. By
these means, and through the active agency of two Roman Catholic
gentlemen and one clergyman of the Church of England, Mr Graham
conducted his canvass with such spirit, that on the day of nomination
an immense majority of hands was held up in his favour; and at the
end of the second day’s polling he was thirty-three ahead of the
gentleman whom he had determined to oust, and whom he
succeeded in ousting. Those, however, were times when polling went
on for fifteen consecutive days, during which electors and their
friends lived at free quarters, candidates paying the piper. When,
therefore, the returning-officer declared that Mr Graham had beaten
Mr Stamford by thirty-eight votes, and when Mr Stamford’s
committee thereupon demanded a scrutiny, Mr Graham’s heart sank
within him. His father had with difficulty been prevailed upon to
sanction his entering into the contest at all. The funds at his disposal
were quite exhausted, and here was the battle to be fought over
again. But who, having committed himself to such a struggle, ever
willingly withdrew from it? Mr Graham did not; and at the end of a
month he was pronounced member for Hull, with a debt of £6000
hanging like a millstone upon his back.
The lesson thus taught him at the outset of his career Mr Graham
never afterwards forgot. He was fortunate enough to raise the money
at interest, without calling upon his father for a shilling; but he
registered a vow to rush no more blindfold into scrapes of the kind;
and he kept it, in spite of many a strong inducement in after-times to
the contrary.
Mr Graham took his seat on the third Opposition bench, behind
his relative Lord Archibald Hamilton. Near him sat Mr E. Ellice (the
Bear), Sir Robert Wilson, and Mr F. E. Kennedy; below him, Sir
Francis Burdett, Mr Hume, and Lord Althorpe. It was a goodly
association, and it produced its legitimate results. The war of parties
soon began; and in March 1819, scarcely a month after he had taken
his seat, the young member delivered his maiden speech. It proved a
signal failure. Abounding in platitudes, and spoken with the air and
in the tone of an exquisite, it scarcely commanded the attention of
the House for a moment, and was brought to a close amid that buzz
of general conversation which, more surely than any violent outcry of
dissent, marks the disinclination of the Commons of England to be
instructed. Mr Graham felt that his shot had missed, yet he by no
means lost heart. He believed that the causes of the failure might be
equally shared between himself and the House, and he determined to
try again and again till he should compel the attention which was
now denied him. Meanwhile, he sought comfort under the
disappointment in a connection which proved to be the source, to
him, of the purest happiness through life. On the 8th of July 1819 he
married Fanny Callander, one of the loveliest women whom England,
fertile in beauty, had ever produced. She was the daughter of Colonel
Sir James Callander, afterwards Campbell of Arkinglas, and the aunt,
as we need hardly stop to observe, of the still beautiful and highly-
gifted Mrs Norton.
Mr Graham’s next effort was made during that eventful autumn
session when Parliament met in consequence of the Peterloo affair,
and the Government demanded powers beyond those of the
constitution, to deal with the dangers which threatened the country.
One of the bills which Ministers proposed, with a view to stop the
organised agitation which Radical delegates kept up, prohibited all
persons, not resident in a town, or being freeholders, from taking any
part in the proceedings of a town meeting. Here was an opportunity
which the ambitious member for Hull could not possibly allow to
escape. He rose to demand whether the member for a borough, being
neither the inhabitant of such borough nor a freeman, would come
within the meaning of the Act; and when, to his great indignation,
nobody seemed inclined to reply, he had the imprudence to argue the
case, and to state it as peculiarly his own. Just at that moment a
sound of suppressed laughter was heard in the House, whereupon
the member for Hull lost his head, and, after rambling on for a few
minutes without a single cheer to sustain him, sat down, retaining no
recollection either of what he had said, or of what he meant to say.
“There’s an end of Graham,” exclaimed Mr Henry Lascelles,
jeeringly; “we shall hear no more of him.” But Mr Lascelles was
mistaken.
Nothing daunted by this discomfiture, the baffled senator stood up
again when the bill went into committee. This time he had carefully
prepared his speech, and the House listened to it, without, however,
evincing any signs that it approved. He was still on the losing side in
politics; and though his friends saw that there was good stuff in him,
even they scarcely ventured to hope that he would ever prove more
than a useful second-rate orator, and a good man of business
whenever matters of detail came to be considered.
The death of George III. in February 1820 warned the House of
Commons that its days were numbered. The Government was
desirous of precipitating the dissolution; and the Opposition took, in
consequence, an early opportunity to hamper them, as far as might
be, by a small reform bill. Lord John Russell proposed that the writs
for Grampound, Penrhyn, Barnstaple, and Camelford, should be
suspended, in order to afford the new Parliament an opportunity of
inquiring into the corruption with which these boroughs were
charged. But Lord John’s motion, which Mr Graham supported,
though successful in the Lower House, was thrown out in the Upper,
and the members dispersed, each to look after his own interest as he
best might.
It would have been idle in Mr Graham to offer himself again to the
constituency of Hull. He had done nothing in Parliament to secure a
re-election, except at the cost of a second contest, and that he could
not afford. The interest of the debt incurred by the first election
pressed heavily upon his small income, and he at once made up his
mind to look for a seat elsewhere. Now the Lowther influence,
powerful as it had heretofore been, was beginning to give way in the
north of England. Both the county of Cumberland and the city of
Carlisle were growing restive, and the Whigs declared their intention
of fighting for both seats in the city, and for one at least in the
county. It was proposed to Mr Graham that he should stand in the
Liberal interest for Carlisle; while Mr Curwen, up to that time the
city member, contested the county against Sir John Lowther.
Anxious as he was to return to the House of Commons, Mr Graham
had the good taste to decline this proposal. He could not fight under
a Whig banner so close to Netherby without greatly distressing his
father; and, vaulting as his ambition was, it did not blind him to the
impropriety of such a course. He contented himself, therefore, with
throwing the weight of his influence into Mr Curwen’s scale as
candidate for the county. Mr Curwen succeeded, so did Mr John Cam
Hobhouse in Westminster, advocating household suffrage, triennal
Parliaments, and counting among the busiest of his canvassers the
late member for Hull. Mr Graham’s activity on that occasion fixed
upon him the attention of certain gentlemen connected by property
with the little borough of St Ives. They took him up, he canvassed the
constituency, and on the day of election was brought in at the head of
the poll. And well and zealously he redeemed the pledges which he
had given to his Liberal supporters. He voted with Mr Hume against
a proposed increase to the civil-list of George IV., and for inquiry
into the expenses of the Regency during the five preceding years. He
took part with Mr Brougham in his attack on the droits of the Crown
and of the Admiralty, and joined Lord John Russell in demanding
that the report on the civil-list should be deferred till the estimates
for the year had been fully examined. Every proposal, in short, which
had for its object the weakening of the influence of the Crown and
the overthrow of existing usages, received his cordial support. He
was, with Mr Curwen and Mr Brougham, a decided enemy to the
Corn Laws as they then existed. He went into the gallery with Lord
John Russell for the disfranchisement of Grampound, and the
transfer of its members to Leeds. In a like spirit, he stood by Lord
Archibald Hamilton when denouncing the Scottish system of
election, and requiring that the number of Barons of the Exchequer
should be reduced. Finally, in the disputes which arose about Queen
Caroline, he ranged himself under her Majesty’s banner. This was
pretty well within the brief interval of less than a year, as indicating
the course which he had determined to follow. But a check came. The
electors of St Ives were not at all satisfied with their new member.
They presented a petition early in 1821 against Mr Graham’s return,
and Mr Graham, rather than incur the certain expense and hazard of
a scrutiny, resigned his seat.
Mortified as he was at finding himself thus excluded from public
life, Mr Graham possessed too good a digestion to let the
circumstance prey upon his spirits. His home was then, as it
continued to be to the last, the chief scene of his happiness; and the
birth of his first-born son, on the 7th of April 1820, shed additional
light over the domestic circle. It suited neither his means nor his
tastes to reside in London as an idler; he therefore retired into
Cumberland, and, settling down at Crofthead, the unpretending
house to which he had carried his beautiful bride, he threw himself
with all his energies into country pursuits. It was high time that he
should. His father, an easy-going and generous man, had never
looked after his affairs as became him. He put himself entirely into
the hands of an agent, from whom he exacted no accounts, and who
did with the rents of the large estate of Netherby pretty much as he
pleased. The consequence was that farms and farm-buildings went to
ruin. Payments on account were all that the landlord received, and
tenants got into arrear so far that recovery was impossible. With
some difficulty Mr Graham prevailed upon his father to transfer the
management of the property to him, and the work of practical reform
began. But the extent of the difficulties with which he had to grapple
may be guessed at, when we say that encumbrances to the amount of
not less than £120,000 lay like a dead weight upon Netherby.
Mr Graham had accomplished a good deal. Money was raised on
more favourable terms; roads were made, marshes drained, farm-
buildings rendered habitable, and a better system of tillage
introduced, when, in 1824, his father died, and he succeeded to the
title and to the estate. An additional burden was of course laid upon
the latter in the shape of dower to Lady Catherine, but for the sisters
of the new proprietor scarcely any provision had been made. Sir
James, like a good brother as he was, supplied the deficiency out of
his own funds. But this done, there remained so little on which to
reckon, more especially with his views of extensive improvement,
that he thought seriously of selling Netherby, and of embarking, with
whatever might remain to him after paying off the mortgages, in
trade. He even went so far as to open a negotiation with a London
banking-house which happened at that moment to desire an
extension of its business, and waited only the judgment of Mr James
Evan Bailey of Bristol, to whom, through a friend, he referred the
question. “Tell him,” said that experienced banker, “to hold fast by
Netherby, and keep clear of banking.” By Netherby Sir James
accordingly held fast, and within twelve months the names of Messrs
Pole, Thornton, Down, & Co. appeared in the ‘Gazette.’
It had been Sir James’s dream that, as a banker or as a thriving
merchant, he would find readier access to the political career on
which he desired to enter, than as the owner of a large and
encumbered estate. The fate of Messrs Pole and Thornton awoke him
from that dream, and he bent all his energies to diminish, if he could
not entirely remove, the debt upon Netherby. His own habits were
prudent and economical. He chose for his associates practical
agriculturists, studied every work that came out on the subject of
agriculture, and put in practice such suggestions as appeared to be
wise. He read, likewise, with a view to prepare himself at some future
time for public life, and read to excellent purpose. The consequence
was, that every year saw the burden diminish which at the outset
seemed to be intolerable; and that, in 1826, his circumstances, if not
easy, were at all events much less harassing than at one moment he
had expected them ever to be.
It was at this time that he first came before the public as an author.
His pamphlet on corn and currency made a great sensation, taking
men of all parties by surprise. Its argument went far beyond the age
in which it appeared. Upon the Bank Restriction Act of 1797 he laid
the blame of all the evils under which the country then laboured, and
censured Mr Peel for returning too hastily to cash payments in 1819.
The sliding-scale, as a protection to corn-growers, he entirely
condemned, and reasoned in favour of free trade, with a small but
fixed duty on foreign corn as some compensation for the peculiar
burdens which the land was called upon to bear. We who read the
pamphlet now, remembering all that the country has gone through,
and looking to the present state both of its manufacturing and
agricultural interests, cannot sufficiently admire the audacity of the
country gentleman who, in 1826, could thus express himself. But his
audacity told. Though all the leaders of party, from Lord Liverpool to
Cobbet, denounced and censured, there were multitudes in the ranks
who approved the Cumberland baronet’s reasoning, and no great
while elapsed ere they gave tangible proof of their sympathy with his
views.
At the dissolution of Parliament in 1826, Mr James, who for some
time had represented Carlisle, retired. A requisition was immediately
sent in to Sir James Graham, who replied to it favourably, and came
forward as the Liberal candidate. We do not use the stronger term
Radical, because, to do him justice, Sir James never voted for
universal suffrage and annual Parliaments; but of everything on the
sinking-scale short of these two points he was then the advocate. He
declared himself in favour of the immediate abolition of slavery, the
total removal of religious disabilities, retrenchment in the public
expenditure, and the reduction within moderate limits of the import-
duty on corn. The struggle was fierce both in Carlisle and elsewhere,
for the Catholic Question was approaching a crisis; and Sir James,
supported by all the operatives of the city, came in at the head of the
poll. His first vote in the House was against the Government, on a
question of an increased grant out of the Consolidated Fund to the
Duke and Duchess of Clarence; his next, for an inquiry into the
abuses in the Court of Chancery. On both occasions he went into the
lobby, one of a small minority. But already prospects began to open
for him, on which he had no reason to count in returning to public
life. Lord Liverpool was struck down by paralysis in 1827, and that
scramble for a successor at the Treasury began, of which, by the way,
Mr Torrens gives a very inaccurate account. Following implicitly the
story told by Mr Stapleton, he endeavours to show that Canning was
no intriguer; that George IV. hated and would have set Canning
aside, had he seen his way to any other arrangement; and that the
Conyngham influence had nothing in the world to say in deciding the
King’s policy. We know better; and we know likewise that not the
Tories only, but the most consistent and stanchest of the Whigs
never trusted Canning. Sir James Graham, on the other hand, ranged
himself among the Canningites, and soon became the friend and
favourite pupil of Huskisson. He sat on the ministerial side of the
Speaker’s chair while Canning led the House, and he retained his
place during the administration which succeeded on Canning’s
demise. But Lord Goderich’s reign was short; and on the assumption
of office by the Duke of Wellington, Sir James withdrew with his
Whig allies to the Opposition benches. His opposition, however,
appears to have been a good deal modified by the esteem in which he
held Mr Huskisson. The Corn Bill which that gentleman introduced,
still being a minister, Sir James Graham supported, though it was
framed on a principle at variance with that which he had advocated
in his pamphlet; and many years elapsed ere he could bring himself
to contemplate without alarm the disturbance of the compromise
into which, as he believed, contending parties had entered by its
adoption.
In 1827 a vacancy occurred in the representation of Cumberland,
and Sir James was easily persuaded to resign his seat for Carlisle and
to set up for the county. His return was not opposed, and he entered
the House after a brief absence as a county member. Though still
ineffective in debate, the House began to consider him a man of
promise. He was an excellent member of committees, assiduous in
his attendance, and remarkably skilful in sifting evidence. He spoke
likewise with effect in moving for an inquiry into the fitness of
limiting the circulation of Scotch notes to Scotland itself; and his
speech, though overladen, as most of his speeches were, with
quotations, was referred to by almost all who followed him, whether
advocating or opposing the view which he took of the matter. But his
great start was taken, when the Duke, by passing his Catholic Relief
Bill, gave the first decided shock to the Tory party. Sir James of
course approved the measure, of which, as well as of the repeal of the
Test and Corporation Acts, he had always been the consistent
supporter. And he did more. He took an opportunity of commending
Sir Robert Peel, in his absence, for the sacrifice to duty which he had
made of his seat for the University of Oxford, and paved the way
thereby for the close intimacy which in due time arose between him
and that great though not always straightforward or very consistent
statesman.
Whatever the Duke’s conduct and views at that critical moment
may have been, those of his subordinates strike us now as not only
impolitic, but dishonest. Sir George Murray went out of his way to
assure the Whigs that he intended to manage the affairs of the
colonies on the principles which they advocated. Sir Henry Hardinge
became a frequent visitor at Spenser House, and professed opinions
there which led Lord Althorpe to reckon upon him as a willing
member of a new coalition. Meanwhile three members of Brookes’s,
Lords Rosselyn and Jersey and Sir James Scarlett, held office under
a Tory chief, and Earl Grey was approached with a view to
conciliation by creating his son-in-law, Mr Lambton, Earl of
Durham. All this gave sure evidence of weakness on the part of the
Government, and encouraged the discontented among its old
supporters to aim at its overthrow. On the other hand, Sir James
Graham, as if looking rather to a fusion than to the break-up of
parties, declared that he saw little difference, except on the question
of the currency, between the opinions entertained by the Opposition
on the one side, and the friends of the Administration on the other.
And, as if to test the House, he moved, on going into Committee of
Supply, that since Peel’s bill of 1819 was accepted as a final
settlement of the currency question, the salaries of all public servants
should be cut down by 20 per cent. Though listened to attentively, he
received small support, either from his own friends or the friends of
the Government; but he added, by the vigour of his appeal, to the
reputation which he had already acquired, and was by common
consent assigned a place with Lord Althorpe, Lord John Russell, and
Mr Brougham, as one of the leaders of the Opposition in the House
of Commons.
Early in May 1830 the Parliamentary campaign opened in earnest,
by a notice of motion by Sir James Graham for a return of all the
pensions, salaries, and emoluments then receivable by members of
the Privy Council. His speech was, in its own way, a telling one; and
the motion was met by a proposal from the Chancellor of the
Exchequer to supply the honourable member with a comprehensive
enumeration of all civil and military offices and salaries under the
Crown. Sir James either felt or affected great indignation, and, in
rejecting Mr Goulbourne’s counter-proposal, made use of the
expression, “That he was not disposed to stoop to ignoble game while
flights of voracious birds of prey were floating in the upper regions of
the air.” This was one of the clap-traps in which Sir James on all
convenient occasions indulged, and it had its effect. Not fewer than
147 members in a House of 382 voted with him—a remarkable sign
of the times, a sure proof that men’s passions had overclouded their
reason on many matters, and that Government by party, as it had
once existed, was for a season at least at an end.
Encouraged by the plaudits which were heaped upon him, Sir
James, after remaining quiet for a few weeks, moved to reduce the
grant for special diplomatic missions from £28,000 to £18,000 a
year. He was again opposed with all the strength which the
Government could muster, and again failed. But failure on this
occasion was accepted on both sides as a triumph. In a House of 217
members, the motion was rejected by a majority of 19 only. It was a
blow to the Ministers scarcely less severe than that which they
received the same evening, when Sir James Mackintosh carried his
clause in the Forgery Bill against them—abolishing the punishment
of death in all cases except where wills were concerned.
The death of George IV., on the 20th of June 1830, was soon
followed by the dissolution of Parliament. Sir James went back to his
constituents with a reputation largely enhanced; and while his
canvass was at its height, tidings of the revolution in Paris arrived.
They set the whole country in a blaze, and two Liberal members
immediately started for Cumberland. A fierce contest ensued, of the
temper of which some idea may be formed when we transcribe one of
the toasts which was proposed and accepted amid a tempest of
applause at a public dinner given to Sir James Graham at
Whitehaven—“May the heads of Don Miguel, King Ferdinand, and
Charles Capet be severed from their bodies and roll in the dust, and
the sooner the better.” It would be unfair to the memory of Sir James
Graham if we omitted to add that he wholly disapproved of this
sentiment, and that, while applauding the revolution, he expressed
himself anxious that the French people should use their victory with
moderation.
We have now arrived at an era into the history of which it would be
out of place, while sketching Sir James Graham’s career, to enter
much at length. The elections of 1830 had gone against the
Government, and the country seemed to have become a prey to
anarchy. There were incendiary fires in many places; and when
Parliament met in November to provide a remedy, the worst spirit
manifested itself in both Houses. The King’s visit to the Lord Mayor
of London was postponed; and the Duke, with extraordinary
rashness, gave utterance to a statement which his enemies insisted
on accepting as a manifesto against all reform. A coalition between
the Whigs and the ultra-Tories to expel him from power ensued, and
Ministers, being defeated on a question of the civil-list, resigned
their places. In bringing all this to pass Sir James had taken an active
part, and he received his reward in the appointment of First Lord of
the Admiralty, with a seat in Earl Grey’s Cabinet. He was placed at
the Admiralty, however, rather as representing ultra opinions than
from any admiration of his talents and industry; for Earl Grey,
desiring above all things to throw the authority of Government into
the hands of aristocrats, was too prudent to overlook the policy,
situated as he then was, of having every great party in the State
represented in his Cabinet. Hence the Duke of Richmond, Mr Wynn,
Lord Palmerston, Lord Goderich, and Mr Charles Grant, were invited
to take their seats beside Lord Lansdowne, Lord Althorpe, and Lord
Carlisle; and Lord Durham, Sir James Graham, and Lord Melbourne
readily joined them. Among all these there was not one who
displayed so large an amount of administrative ability as Sir James
Graham, or who with so much frankness acknowledged, when the
proper time came, that the improvements effected by him in the
department were little more than the execution of plans which his
predecessor had already arranged and determined upon.
Earl Grey had taken office pledged to three things,—
Retrenchment, Non-intervention in Foreign Affairs, and
Parliamentary Reform. Into all these Sir James Graham eagerly
threw himself. Returned again without opposition for Cumberland,
he took up his residence at the Admiralty, and worked like a slave to
keep ahead of the enormous amount of business which devolved
upon him. For now his real worth was discovered. What might be
wanting in brilliancy he endeavoured to make up by labour; and he
held his own, not without a hard fight for it, in the House of
Commons. Lord Althorpe, the acknowledged leader of the
Ministerial party, was slow and confused. He derived the greatest
benefit from the subtle and ambitious promptings of Graham, and
often sought for them. Whether the proposal in the first Whig budget
to impose a tax on the transfer of stock came from this source does
not appear; but the measure, in spite of the eloquence with which Sir
James Graham supported it, met with no success, and was
withdrawn amid the jeers of the House.
This was a bad beginning, and his speech in defence of the army
estimates proved equally unfortunate. The pledge of non-
intervention had been thrown over by the Government in the case of
Belgium, and an increase to the army was asked for. In advocating
this increase, Sir James allowed himself considerable latitude of
speech in regard to the condition of Ireland, and O’Gorman Mahon,
conceiving that he, among others, had been attacked, called upon the
First Lord to retract, or else to give him personal satisfaction. Sir
James requested Lord Althorpe to act for him on that occasion, and
the quarrel was amicably settled.
The improvements introduced into the constitution of the
Admiralty were chiefly these: Sir James abolished the Victualling and
Navy Boards as separate establishments; he required the accounts of
the office to be kept by double entry; he proposed to throw open the
great national asylum at Greenwich to seamen of the mercantile
marine; and, failing to accomplish that, he relieved the mercantile
marine from the special tax which it had heretofore borne. Nor was
he all the while exempt from a full share of the burden of
administration in other respects. Earl Grey never lost sight of the
pledge which he had given to reform the representative system
throughout the United Kingdom, and a committee of four was
appointed to investigate the whole subject, and to report upon it to
the Cabinet. Lord Durham, Lord John Russell, Lord Duncannon, and
Sir James Graham composed that committee, of which no member
worked more steadily and with greater zeal than Sir James.
It is not our purpose to tell over again the thrice-told tale of the
bloodless revolution of 1831–32. In preparing the scheme which the
Government was to bring forward, Sir James Graham appears to
have been less extravagant than some of his colleagues. He desired to
interfere as little as possible with existing rights in counties, except
by adding copyholders and leaseholders to the ancient freeholders.
In boroughs he was an advocate for occupancy as a condition to
freedom, and was willing that the limit of the pecuniary
qualifications should be wide. He objected to the ballot, and to
anything like an attempt to establish perfect uniformity of franchise
anywhere. Yet such was his infirmity of purpose that he yielded his
own opinions to those of men of stronger will, and affixed his
signature to a report which recommended the ballot and other
arrangements of which he disapproved. It was this weakness, indeed
—this apparent inability to arrive at settled convictions and to stand
by them—which constituted the great flaw in Sir James Graham’s
character as a public man. His biographer, we observe, commends
him for the specialty, and endeavours to make what was mere
irresolution stand in the light of judicial impartiality. “Half his life,”
says Mr Torrens, “was spent in comparing and pondering opposite
results, and determining judicially in the silence and solitude of his
study on which side the balance lay. ‘Upon the whole’ again and
again occurs throughout his private correspondence and public
judgments, for judgments they frequently were—a phrase which a
statesman of a constitutional country may well employ as eminently
expressive of the true candour and humility of wisdom.” Doubtless
this is true; but if we find the statesman afterwards going apart from
his own conclusions, and falling in with proposals against which he
had “on the whole” decided, what can we say of him except that his
humility degenerates into weakness, and that, whatever qualities he
may possess, firmness of purpose is certainly not one of them?
It is a remarkable fact that not even now could Sir James Graham
command the attention of the House. His great attention to business,
his value on a committee, and his administrative abilities, were very
generally acknowledged, but as a speaker he made little or no
impression. Even his advocacy of what may be called his own
measure was felt to be feeble—a strange medley of confused
discussion and turgid enunciations. But the bill had other sources of
strength to depend upon than the logic of its Parliamentary
supporters. Political unions and conspiracies out of doors did the
work, and the King and the House of Lords were forced to accept
their own humiliation. First came the dissolution on the 23d of April
1831, a step into which William IV. was coerced by the overbearing
insolence of Earl Grey and Lord Chancellor Brougham. Then
followed elections wherein brute force bore down all opposition, and
by-and-by such an assembly at Westminster as struck terror into the
hearts of the Ministers who had brought it together. On the top of
that wave Sir James Graham was again borne into Parliament—a
colleague being given to him of opinions far more advanced than his
own. So it befell in the borough of Carlisle, so also in the
neighbouring county of Westmoreland. It is quite certain that Sir
James Graham did not contemplate the crisis, which he had helped
to bring on, without alarm. “We have ventured,” he says, speaking of
himself and his colleagues, “to drive nearer the brink than any other
statesman ever did before; but we did so because aware that if we let
go the reins the horses would be maddened into plunging headlong
into the abyss, where extrication would be impossible.”
We have alluded elsewhere to Sir James Graham’s reconstruction
of the departments in the Admiralty. It is creditable to him that he
disclaimed all the merit of originality in such reconstruction. He
discovered, on acceding to office, that plans of practical reform were
already settled, and he had the good sense to accept and act upon
them as his own. He found a willing adviser likewise in Lord Melville,
who kept back nothing from him when consulted. Having completed
this job, he set himself next to devise some means of getting rid of
the necessity of impressment, and was again fortunate enough to
have brought to him an important letter, addressed by Lord Nelson
to Earl St Vincent. The letter in question suggested that there ought
to be a registration of seamen, among whom, at the sudden outbreak
of war, a ballot should take place, with permission, as in the militia,
to find substitutes. But, anxious as he was to accomplish this object,
he shrank as a Minister of the Crown from openly striking a blow at
the prerogative. When, therefore, Mr Buckingham moved, “That the
forcible impressment of seamen for His Majesty’s navy was unjust,
cruel, inefficient, and unnecessary,” Sir James Graham resisted the
motion. He fought, however, less for the evil itself than for the
manner of applying a remedy, and obtained leave of the House to
bring in a bill which has many admirable points in it, but which he
was not destined to guide through its various stages till it became
law.
The years 1833 and 1834 were seasons of sore trial to the Reform
Government. They had evoked a power at home which they found
themselves ill able to control. They had entered into treaties and
engagements abroad, the necessity of acting up to which involved
them in heavy expenses. But most of all were they hampered and
annoyed by the operations of the Irish party, which, after helping
them to carry their great measure, asked for its reward. The Irish
Established Church must be sacrificed; and the better to insure a
speedy attainment of that object, an agitation was got up for the
repeal of the Union. Now, Earl Grey was not a man to endure
contradiction calmly; he introduced a stern Coercion Bill into the
House of Lords, which his colleagues fought inch by inch in the
House of Commons. In order to conciliate their Radical supporters,
they proposed at the same time to reduce the number of Irish
bishops, and to substitute for church-rate in Ireland moneys to be
raised by taxes imposed on all sees and benefices. Finally, after
providing, as was assumed, a better method of managing episcopal
and chapter lands, a clause in their bill declared “That it should be
lawful to appropriate any portion thence accruing to purposes of
secular utility, without regard to the religious opinions of persons to
be benefited.” This famous clause (the 147th) was warmly debated,
and in the end withdrawn. But neither section of the Legislature
seemed to be satisfied. Indeed, in the Cabinet itself diversity of
opinion was held in regard to that matter, and no great while elapsed
ere diversity of opinion led to separation.
The first overt proof of schism in the Cabinet was presented by the
opposite sides which Sir James Graham and his colleagues took on
Mr O’Connell’s motion of censure upon the Irish judge, Sir William
Smith. Sir James stoutly resisted it. Mr Stanley, Lord Althorpe, and
Lord John Russell voted for it. On a division, Sir James went out
with a minority of 74, and next morning tendered his resignation. He
had proved himself, however, too valuable a member of the
Administration to be cast adrift, and Earl Grey refused to part with
him. Three nights afterwards he committed another crime by
acknowledging in his place that the economy effected by his
predecessors at the Admiralty was quite equal to his own. Then
followed a discussion upon the Corn Laws, which he defended as
they stood; whereas Mr Poulett Thompson, Vice-President of the
Board of Trade, proposed to substitute a fixed duty for a sliding-
scale. And here an incident befell which deserves notice. Mr Poulett
Thompson endeavoured to confute his opponent by reading extracts
from a pamphlet which had appeared in 1830, and in which the
author, under the nom de guerre of a Cumberland Landowner,
advocated entire freedom of trade in corn, as in other commodities.
Strange to say, Sir James Graham took no notice of the ironical
cheers which followed these quotations, and which marked the
conviction of the House that the pamphlet had emanated from his
pen. Yet such was not the case. The pamphlet was the work of a Mr
Rooke, and was acknowledged as such when, four years
subsequently, the author gave to the world a volume on the science
of geology. Why Sir James Graham did not decline the honour thrust
upon him at the moment, we are at a loss to conceive, and his
biographer certainly assigns no satisfactory reason for the
proceeding.
The Cabinet worked on not very amicably, and Sir James Graham
did it what service he could by taking charge of its bill for
remodelling the Exchequer Office. But the time was come when he
felt that he could serve it no longer. Lord Wellesley’s measure for
converting tithes in Ireland into a permanent rent-charge on the land
was cumbered by a question from Mr Shiel, drawing from Lord John
Russell something like a pledge, that the Government might
hereafter consider the propriety of applying a portion of this rent-
charge to secular purposes. And a few days later Mr Ward brought
forward his motion, “That the Protestant Episcopal Establishment in
Ireland exceeds the spiritual wants of the Protestant population, and
that, it being the right of the State to regulate the distribution of
Church property in such a manner as Parliament might determine, it
is the opinion of this House ‘that the temporal possessions of the
Church of Ireland, as established by law, ought to be reduced.’”
There was no evading a movement like this. The Cabinet must either
resist or accept Mr Ward’s motion, and a majority determined to
accept it. Now, however Radical Sir James Graham’s views might be
on other points, he was then, as he always had been, a consistent
Churchman. On many previous occasions he had declared his
determination to defend to the uttermost the inviolability of what he
regarded as a fundamental institution of the Empire; and the Duke of
Richmond, Lord Ripon, and Mr Stanley agreed with him. When,
therefore, this Act for confiscating the property of the Church was
accepted by the Cabinet as its own, the four Ministers above named
felt that only one course lay open to them: they retired from the
Administration, and shook it thereby to its base.
Sir James sat below the gangway, on the Ministerial side of the
House, while those gyrations went on which ended in shaking Earl
Grey out of the Premier’s chair, and Lord Melbourne into it. With Mr
Stanley, and the half-dozen friends who adhered to him, Sir James
kept aloof from each of the rival parties, becoming one of the
company who, as Mr O’Connell described it, “travelled by themselves
in the Derby Dilly.” It is not for us to inquire into the motives which
animated the little band at that time. But considerations of delicacy
towards old friends were surely rated above their just value when
they induced Mr Stanley and Sir James Graham, a few months
subsequently, to decline taking office under Sir Robert Peel. Had
they met his advances as frankly as they deserved, the Conservative
Government of 1835 would have probably stood its ground; and
though it be difficult to conceive, looking both at things present and
things past, how the commercial system, now in the ascendant, could
have been pushed aside, still the progress of that system would have
been probably more gradual; it certainly might have achieved its
triumph at a sacrifice less costly than the disruption of the great Tory
party, which followed on the repeal of the Corn Laws in 1846.
Sir James was coldly looked upon by the Liberals for abandoning
Earl Grey’s Administration, and a cabal was got up to resist his re-
election for East Cumberland in the event of his taking office with Sir
Robert Peel. He refused to take office, as we have shown, and
defended himself well at the hustings against the attacks which were
made upon him. East Cumberland chose him again to be its
representative, and he again took his seat below the gangway on the
Ministerial side of the House. As an independent member, however,
he stood aloof from the struggle between Sir Robert Peel and the
Whigs, till Lord John Russell brought forward his famous motion
“For the appropriation to secular purposes of a portion of the Church
property in Ireland.” Then Sir James Graham threw over all party
scruples. He delivered against the motion one of the most telling
speeches which he ever uttered in Parliament, and went out into the
gallery with that gallant band which failed to keep their chief in office
by twenty-five votes only. From that moment his severance from the
Whigs became a mere question of time, and the bitterness with
which the Municipal Reform Bill was argued hurried it on. Sir James
had never desired to swamp the poorer voters, either in counties or
boroughs, and voted against the extinction of the class of freemen.
Having gone out with the Tories, he was preparing to cross the
House to his old seat, when a storm of derisive cheering greeted him,
accompanied by shouts of “Stay where you are!” He stopped, looked
angrily at the benches whence the sounds proceeded, and then sat
down with a smile of scorn on his lips on one of the Opposition
benches.
For the part which he took in resisting the extension to Ireland of
the municipal changes which were effected in England and in
Scotland, Mr Torrens severely censures Sir James Graham. This is
natural enough. Going far beyond his hero in Radical propensities,
Mr Torrens dispenses blame where men of moderate views would
award praise. He seems to forget that all legislation for Ireland was
undertaken in those days with a twofold purpose only—to conciliate
Mr O’Connell, and to humble the House of Lords. The Melbourne
Ministry, however, rode their hobby too fast. Not a few of the most
distinguished of the old reformers fell off from them. Indeed, to such
a height was the spirit of alienation carried, that not Sir James
Graham only, but likewise Lord Brougham, Sir Francis Burdett, and
Lord Stanley, withdrew their names from Brookes’s, into which Mr
O’Connell had been received as a member.
From this date up to the death of William IV. in 1837, party spirit
prevailed in Parliament and out of it, with a bitterness which has no
parallel in modern times. The Ministers, existing by the breath of Mr
O’Connell and the Radicals, seemed indifferent to the consequences
of the measures which they proposed. The great body of the
Opposition, carried away by personal dislike to their opponents,
fought more than one battle which it would have been wise to avoid,
and compelled their more judicious leaders to fight with them. On
the whole, however, the Duke in the House of Lords and Sir Robert
Peel in the Commons managed matters well; and it is only just to Sir
James Graham to add, that they found in him a hearty as well as a
prudent coadjutor.
The accession of her present Majesty led, of course, to a
dissolution, and Sir James Graham had the mortification to find
himself opposed in East Cumberland by Major Aglionby, formerly
his fastest friend. He received, on the other hand, but a doubtful
support from the Conservatives, and on the day of nomination the
mob refused to hear him. Naturally proud, and perhaps a little
dissatisfied with himself, he quitted the hustings, and went to the
poll in bad heart. He was defeated by a majority of upwards of 500
votes, and withdrew, full of indignation, to Netherby. He had
suffered not long before this a heavy domestic affliction in the death
of his mother; and mortified ambition, coming on the back of private
sorrow, wellnigh broke him down. He took no further part in county
business; he shut himself out from county society, and spent his time
chiefly in reading every new book that came out, and corresponding
on important subjects with Sir Robert Peel. It was the interval
between his defeat for East Cumberland and his return to Parliament
as member for the Welsh borough of Pembroke which made him,
what he ever after continued to be, a Peelite to the backbone.
In 1838 Sir James Graham was elected Lord Rector of the
University of Glasgow, in opposition to the Duke of Sussex. He
delivered an inaugural address, which is probably still remembered
in consequence of the uproar which it called forth by certain
allusions to the necessity of keeping the Church in alliance with the
State; for then the fever of Free-Kirk folly was at its height in
Scotland. But in 1839 he had graver matters to attend to. That
systematic agitation against the Corn Laws having already begun of
which Mr Charles Villiers, and not Mr Cobden, was the author. Sir
James spoke in his place against interference with the sliding-scale;
at the same time he guarded himself from the charge of desiring to
secure a monopoly in the corn-market for the English landowner,
and went out of his way to warn the House that nothing could be
more perilous to English interests than that monopoly in the supply
of cotton which had been conceded to America. He was anxious even
then that steps should be taken to encourage the better cultivation of
the plant in India, and pressed upon the President of the Board of
Control the wisdom of originating such a scheme. Words of warning
which, disregarded at the moment, come back upon us now with a
melancholy echo!
The progress of the struggle, which ended in the withdrawal of the
Appropriation Clause and the passing of the Irish Municipal Reform
Bill through both Houses of Parliament, is of too recent date to
require that we should speak of it in detail. So is the contest which
arose about softening down some of the clauses in the New Poor-
Law, of which Sir James, though advocating the law itself, was a
strenuous advocate. His speech on that occasion, as well as his
censure of the job which pensioned Sir John Newport and raised Mr
Spring Rice to the peerage, more and more drew towards him the
sympathies of the Conservative party, which indeed had already
begun to look to him as one of its future leaders. He was equally
efficient in his attacks on the Whig mismanagement of affairs in
India and in China, and certainly did not spare his old friends when
stirred by their rebukes into invective. At last the collapse came, and
in 1841 the country declared against the Whigs. A new
Administration was formed, with Sir Robert Peel at its head. Sir
James Graham accepted the seals of the Home Office, and for five
years public affairs were carried on, if not smoothly in all respects,
with remarkable success upon the whole. No doubt, Lord Aberdeen’s
legislation in the matter of the Church of Scotland proved
unfortunate, and there was little in Sir James Graham’s manner to
reconcile the discontented portion of the Scottish clergy to the law as
it stood. Indeed, it is a remarkable fact, that almost all the failures in
Sir Robert Peel’s policy occurred on points of which the management
devolved upon Sir James Graham. To him, in a great degree, was
attributed the disruption in the Scottish Church. His bill for the
amendment of the Factory Act of 1833 hung fire, and was withdrawn;

You might also like