Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Applied User Data Collection and

Analysis Using JavaScript and PHP 1st


Edition Kyle Goslin
Visit to download the full and correct content document:
https://ebookmeta.com/product/applied-user-data-collection-and-analysis-using-javas
cript-and-php-1st-edition-kyle-goslin/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Applied Modeling Techniques and Data Analysis 1:


Computational Data Analysis Methods and Tools 1st
Edition Yiannis Dimotikalis

https://ebookmeta.com/product/applied-modeling-techniques-and-
data-analysis-1-computational-data-analysis-methods-and-
tools-1st-edition-yiannis-dimotikalis/

Statistics for Ecologists Using R and Excel Data


Collection Exploration Analysis and Presentation 2nd
Edn 2nd Edition Mark Gardener

https://ebookmeta.com/product/statistics-for-ecologists-using-r-
and-excel-data-collection-exploration-analysis-and-
presentation-2nd-edn-2nd-edition-mark-gardener/

Data Analysis and Related Applications, Volume 1:


Computational, Algorithmic and Applied Economic Data
Analysis 1st Edition Konstantinos N. Zafeiris

https://ebookmeta.com/product/data-analysis-and-related-
applications-volume-1-computational-algorithmic-and-applied-
economic-data-analysis-1st-edition-konstantinos-n-zafeiris/

Learning JavaScript Data Structures and Algorithms


Write complex and powerful JavaScript code using the
latest ECMAScript 3rd Edition Loiane Groner

https://ebookmeta.com/product/learning-javascript-data-
structures-and-algorithms-write-complex-and-powerful-javascript-
code-using-the-latest-ecmascript-3rd-edition-loiane-groner/
Algebraic Foundations for Applied Topology and Data
Analysis 1st Edition Hal Schenck

https://ebookmeta.com/product/algebraic-foundations-for-applied-
topology-and-data-analysis-1st-edition-hal-schenck/

Learning PHP, MySQL & JavaScript, 7th Edition Robin


Nixon

https://ebookmeta.com/product/learning-php-mysql-javascript-7th-
edition-robin-nixon/

Data Analytics in Football: Positional Data Collection,


Modelling and Analysis 2nd Edition Daniel Memmert

https://ebookmeta.com/product/data-analytics-in-football-
positional-data-collection-modelling-and-analysis-2nd-edition-
daniel-memmert/

Pro Data Visualization Using R and JavaScript: Analyze


and Visualize Key Data on the Web 2nd Edition Tom
Barker

https://ebookmeta.com/product/pro-data-visualization-using-r-and-
javascript-analyze-and-visualize-key-data-on-the-web-2nd-edition-
tom-barker/

Applied Missing Data Analysis, 2nd Edition Craig K.


Enders

https://ebookmeta.com/product/applied-missing-data-analysis-2nd-
edition-craig-k-enders/
Applied User Data
Collection and
Analysis Using
JavaScript and PHP
Applied User Data
Collection and
Analysis Using
JavaScript and PHP

Kyle Goslin
Markus Hofmann
First edition published 2021
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742

and by CRC Press


2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

© 2021 Taylor & Francis Group, LLC

CRC Press is an imprint of Taylor & Francis Group, LLC

The right of Kyle Goslin and Markus Hofmann to be identified as authors of this work has been as-
serted by them in accordance with sections 77 and 78 of the Copyright, Designs and Patents Act 1988.

Responsibility for the validity of all materials or the consequences of their use. The authors and pub-
lishers have attempted to trace the copyright holders of all material reproduced in this publication
and apologize to copyright holders if permission to publish in this form has not been obtained. If any
copyright material has not been acknowledged, please write and let us know so we may rectify in any
future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information stor-
age or retrieval system, without written permission from the publishers.

For permission to photocopy or use material electronically from this work, access www.copyright.
com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA
01923, 978-750-8400. For works that are not available on CCC, please contact mpkbookspermis-
sions@tandf.co.uk

Trademark notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.

ISBN: 978-0-367-75682-6 (hbk)


ISBN: 978-0-367-75680-2 (pbk)
ISBN: 978-1-003-16354-1 (ebk)

Typeset in Computer Modern font


by KnowledgeWorks Global Ltd.
For Amanda and Noah.
For when distraction was needed, and for when it was
not. — Kyle

In memory of Johann Trautwein, who, as an early


adopter of computing, not only paved my path to the
world of informatics but also instilled many other
values I cherish. A true gentleman - missed but never
forgotten by all who knew him. — Markus
Contents

Preface xi

Authors xiii

Acknowledgments xv

List of Figures xvii

List of Tables xxiii

Chapter 1  Introduction 1

1.1 INTRODUCTION 1
1.2 WHO THIS BOOK IS AIMED AT 2
1.3 TECHNOLOGIES USED 2
1.4 VARIATIONS OF DATA 3
1.4.1 Active Data 4
1.4.2 Passive Data 4
1.5 WHAT YOU NEED 5
1.6 DEVELOPMENT ENVIRONMENT 6
1.7 CODE EXAMPLES 8
1.8 BOOK OUTLINE 9
1.9 SUMMARY 10

vii
viii  Contents

Chapter 2  Active Data Collection 11

2.1 INTRODUCTION 11
2.2 BINARY DATA COLLECTION 11
2.3 TEXT-BASED DATA COLLECTION 16
2.4 STAR RATINGS 21
2.5 CUSTOM RESPONSE FORM 29
2.6 SUMMARY 38

Chapter 3  Passive Data Collection 39

3.1 INTRODUCTION 39
3.2 COOKIES AND SESSIONS 40
3.3 READING FROM FILES 49
3.4 USER IP ADDRESS 58
3.5 FINDING THE USER AGENT 64
3.6 USER GEOGRAPHIC LOCATION 67
3.7 TIME SPENT ON PAGES 71
3.8 TRACKING INDIVIDUAL DIV TAGS 73
3.9 LOGGING TIMES 75
3.10 WHERE A USER CAME FROM 80
3.11 SOCIAL MEDIA CONTENT HARVESTING 81
3.12 SUMMARY 86

Chapter 4  Custom Dashboards 87

4.1 INTRODUCTION 87
4.2 USER LOGIN 88
4.3 USER REGISTRATION 95
4.4 MULTI-COLUMN BAR CHART 104
4.5 BINARY BAR CHART 110
4.6 DYNAMIC DASHBOARD 115
4.7 SUMMARY 150
Contents  ix

Chapter 5  Working with Text 151

5.1 INTRODUCTION 151


5.2 NATURAL-LANGUAGE PROCESSING 151
5.3 STOP WORDS 152
5.4 RED-FLAG MONITORING 158
5.5 N-GRAMS 167
5.6 SENTENCE COMPLETION 170
5.7 WORD STEMMING 173
5.8 SYNONYMS 174
5.9 TERM WEIGHTING 178
5.10 SENTIMENT ANALYSIS 184
5.11 SUMMARY 188

Chapter 6  Text Visualization 189

6.1 INTRODUCTION 189


6.2 WORD CLOUD 189
6.3 COLLAPSIBLE TREE LAYOUT 195
6.4 TERMS OF INTEREST NODE GRAPH 200
6.5 TIME-SERIES ANALYSIS WITH POSITIVE AND NEGA-
TIVE REVIEW CHART 211
6.6 SUMMARY 219

Chapter 7  Time-Based Feedback Analysis 221

7.1 INTRODUCTION 221


7.2 GATHERING TIMELINES AND DATABASE DATA TYPES 221
7.3 TIME-SEGMENT ANALYSIS AND VISUALIZATION 223
7.4 REAL-TIME FEEDBACK ANALYSIS 237
7.5 POSITIVE VS. NEGATIVE FEEDBACK CALENDARS 244
7.6 FEEDBACK HEAT MAP 252
7.7 SUMMARY 265
x  Contents

Chapter 8  Feedback Statistics and Overviews 267

8.1 INTRODUCTION 267


8.2 BASIC STATISTICS 267
8.3 WORKING WITH SAMPLES 273
8.4 PERCENTAGE DIFFERENCE 275
8.5 SUMMARY 283

Chapter 9  Hosting, Reporting, and Distribution 285

9.1 INTRODUCTION 285


9.2 REPORT GENERATION 285
9.3 CRON AND TASK SCHEDULING 291
9.4 CLOUD E-MAIL SERVICE INTEGRATION 295
9.5 HOSTING A PHP/JAVASCRIPT APPLICATION 300
9.6 SUMMARY 308

Index 309
Preface

The driving force behind any web application is the users of the appli-
cation and the developers creating the application. During development,
however, the interests and needs of the user can often fall behind, in
favor of what the developer thinks they need. This development style of-
ten leads to complicated user interfaces, poor design choices, and content
overload.
To mitigate against this, the daily interaction a user can have with
an application and their overall opinion should be considered paramount
during development. This book aims to provide the tools and knowledge
required for the collection and analysis of data, irrespective of the format
or source.
This book places a dividing line between the types of data that can
be collected from users. Active data is defined as data that is collected
by providing the user with the means to enter their opinion, and sen-
timent, toward a feature or topic. These solutions can often be seen on
websites in the form of rating systems, feedback boxes, and user surveys.
In contrast to this, passive data is defined as the data that is collected
in the background without any direct user interactions. This data takes
the form of browser fingerprinting, IP addresses, geolocation data, time
spent on pages, and the location of the mouse during interactions with
an application.
With the advent of cloud storage solutions, more data is being re-
tained than before. Sales data, transaction logs, and user surveys all
become sources for data analysis. Data can come from a number of dif-
ferent sources, some of which may have existed before an application has
been developed. Emphasis is placed on collecting this data and placing
it in a usable format for analysis.
After this data has been collected, the analysis process can begin.
For each different data type—e.g., numeric or text—statistics and vi-
sualizations can be generated. This book provides the foundations for
creating meaningful insights and visualizations from the data that are
relevant to both business and developer needs.

xi
xii  Preface

As with any new technologies, a common issue with any new solu-
tion is integrating it into an existing system or implementation. To aid
development, each of the examples in this book has been developed in
isolation to allow for easy integration. An emphasis is placed on the di-
versity of technologies to provide a well-rounded understanding of what
is available.
The complete development life-cycle is described in this book, out-
lining how data can be collected, analyzed, and reported to the key
stakeholders in a project.
Authors

Kyle Goslin Markus Hofmann


TU Dublin TU Dublin
Dublin, Ireland Dublin, Ireland

xiii
Acknowledgments

I would like to thank Amanda for her continued support allowing me


to hide away in my office to write and review no matter the weather
inside or outside the house. Your opinions and sentiment mean more
to me than any other. I would also like to thank my parents, Ted and
Claire, for their unwavering support of all things academic. The pursuit
of knowledge and taking risks were always encouraged, as the reward
was always better once failure had, many times, been achieved. I would
also like to thank my brother, Darragh, for being the ears of patience
when frustration or writer’s block dawned.
I would also like to thank Daniel McSweeney, head of the Department
of Informatics at TU Dublin Blanchardstown campus, for his support
and encouragement. Ideas were always met with guidance and reflection.
I cannot forget my co-workers in Peter Alexander, Tara Cambell, Jane
Hanratty, and all others in office A57 for their ongoing support and
encouragement. The experience is always better when shared. I would
also like to thank Philip Kavanagh for his technical review of this book.
This book was the combination of many ideas and concepts derived
from teaching at TU Dublin, Blanchardstown campus. I would like to
thank my students, who are the lifeblood of academia.

— Kyle Goslin

xv
List of Figures

1.1 Viewing the developer console in Google Chrome. 7


1.2 Disabling the cache in the developer console. 8

2.1 Yes and No binary options. 16


2.2 Alert box showing the selected radio button value. 16
2.3 No option expanding allowing the user to expand their
response in text format. 21
2.4 Star-rating example. 23
2.5 Star rating with preset rating. 28
2.6 Completed response form. 37
2.7 Bootstrap modal shown to the user after the form has
been submitted. 38

3.1 Value being retrieved from a cookie. 41


3.2 Set and get JSON value. 43
3.3 Iterating over JSON values. 45
3.4 JSON added using custom JavaScript function. 47
3.5 Unique session ID echoed to the web browser. 48
3.6 Text output to the browser from an array stored in the
session. 49
3.7 Folder structure of the jQuery File Upload plug-in. 51
3.8 Default layout of the jQuery File Upload plug-in. 51
3.9 Google Form sample. 54
3.10 Google Form export options. 54
3.11 Google Form download CSV responses. 55
3.12 Sample Google Form CSV file. 55

xvii
xviii  LIST OF FIGURES

3.13 CSV file contents output to a browser. 57


3.14 Three individual lines that are read in from a text file
are output to the browser. 58
3.15 IP address in JSON format. 59
3.16 Yes/No option presented to the user. 63
3.17 Message displayed to the user after selecting Yes or No. 64
3.18 User agent printed to the console. 66
3.19 user agent.php — User agent retrieved using PHP. 66
3.20 Example geographical information. 69
3.21 Geographical information shown in JSON format in a
browser. 70
3.22 Current location associated to the IP address is printed
to the console. 71
3.23 Output to the console after four seconds. 72
3.24 Number of seconds a user has spent on a div tag. 74
3.25 Message printed to the console when the user navigates
away from the current page. 76
3.26 Sample timings logged to the database table. 80
3.27 Output from calling the PHP REFERRER variable. 81
3.28 Sample composer.json contents for a new project. 83
3.29 Composer library installation console output. 83
3.30 Twitter API search results. 86

4.1 Custom dashboard for the login page. 93


4.2 Completed dashboard register page. 103
4.3 Bootstrap modal shown when the registration was suc-
cessful. 104
4.4 List of download options for Charts.js. 105
4.5 Contents of Chart.js zip file. 105
4.6 Contents of Chart.js folder. 106
4.7 index.html containing a list of working samples. 106
4.8 Bar chart showing the count of each score. 111
4.9 Two-column bar chart for binary data. 116
LIST OF FIGURES  xix

4.10 Database table with sample data sources and configura-


tion options. 119
4.11 Sample Bootstrap dashboard. 119
4.12 Bootstrap default dashboard with a nav bar. 123
4.13 Select campaign modal with two available campaigns. 129
4.14 Viewing a list of campaigns with a single campaign ele-
ment selected. 130
4.15 Example dashboard with two visualizations added. 139
4.16 Two text fields allowing the user to create a new campaign. 143
4.17 The process of adding a new campaign element and se-
lecting the data source. 150

5.1 Before and after stop-word removal with JavaScript. 156


5.2 stopwords.php — Before and after stop-word removal
with PHP. 158
5.3 Sample comment records. 160
5.4 View red-flags menu option. 163
5.5 Select date and CID modal. 163
5.6 jQuery datepicker. 164
5.7 Each comment is output with the red flag terms high-
lighted. 167
5.8 Sample n-gram output with N =2. 170
5.9 Result of searching for the word staff inside a feedback
records. 173
5.10 Result after calling the stemming algorithm. 174
5.11 BigHugeLabs.com API key creation process. 175
5.12 BigHugeLabs.com sample REST URLs. 176
5.13 Example synonyms returned from the Big Huge Labs
API called via a GET request. 178
5.14 Example TF-IDF output for each term in a single docu-
ment. 185
5.15 Result of the sentiment-analysis process. 187

6.1 Sample word cloud without stop words removed. 191


xx  LIST OF FIGURES

6.2 Output from the dynamic generation of a word cloud


using term frequency. 194
6.3 Completed tree-based structure with the root of the sen-
tence as the parent node. 201
6.4 Vis.js graph output for two keywords and a single date. 212
6.5 Time graph showing seven days of positive and negative
feedback for a week. 219

7.1 Time-segment analysis controls. 227


7.2 Selecting the start time for the analysis process. 227
7.3 Selecting the start time of interest. 228
7.4 Time-segment analysis for positive and negative feedback
for a two-hour window. 238
7.5 Real-time feedback score-report line graph. 244
7.6 Calendar view of positive and negative feedback. The
shading of the cells indicates the number of records. 252
7.7 Mouse hovering shows the number of records for a given
day. 253
7.8 Calendar day picking using the jQueryUI date picker. 263
7.9 Heat map showing 24 hours in a single calendar day. 264
7.10 Tooltip showing the number of feedback records for a
given time slot. 265

8.1 Output showing the mode and total count of records for
the mode. 269
8.2 Average result for a given column. 271
8.3 Example standard deviation result. 273
8.4 Calculating the percentage difference. 283

9.1 Statistics rendered in a PDF file. 291


9.2 cron-job.org website. 294
9.3 Creating a sample cron on cron-job.org. 295
9.4 Creating a sample schedule for a cron job. 296
9.5 The SendGrid API being installed by composer. 297
9.6 Amazon Lightsail dashboard. 301
LIST OF FIGURES  xxi

9.7 Selecting Lightsail image type and blueprint. 301


9.8 Selecting the Lightsail instance type. 302
9.9 Providing a name to a Lightsail instance. 303
9.10 Lightsail instance in a pending state. 303
9.11 Running Lightsail instance. 303
9.12 Lightsail-integrated console. 304
9.13 Options to create or download existing keys. 305
9.14 FileZilla homepage. 305
9.15 FileZilla new connection window. 306
9.16 List of files and folders on the Amazon Lightsail instance. 307
9.17 Selecting files in FileZilla to upload to the instance. 307
9.18 Sample application viewed in a web browser. 308
List of Tables

5.1 Sample n-grams with N =2 168


5.2 Sample n-grams with N =3 168
5.3 Sample Records for Term Frequency 179
5.4 Sample Term Frequency Scores 181
5.5 Sample Records for Term Frequency—Inverse Document
Frequency 181

7.1 MySQL Database Data Types for Time and Dates 222

xxiii
CHAPTER 1

Introduction

1.1 INTRODUCTION
Understanding a user’s needs and requirements is one of the main driving
forces for any business. Collected data provides insights into how users
feel about a given feature or topic and how they work on a day to day
basis. This data can be gathered directly from users by providing simple
questions and allowing the user to select an option from a predefined
list, or to enter their own text-based responses.
Although asking a user for their opinion is possible, other methods
can be used to gather data. Data can be collected indirectly through
a web application by monitoring the interactions and behaviors a user
has with it. The collected data can be processed to generate meaningful
statistics and visualizations, providing both overviews and a deep-dive
analysis of user interests and needs.
Each different data type, such as numerical data and text data, comes
with methods of identifying importance and relevance. Both quantita-
tive and qualitative analysis approaches can be used to extract these
insights. In this book, we explore the different methods available for
data collection, extraction, and analysis. This book aims to describe the
many different approaches that can be taken with the aim to capture as
much data as possible for analysis.
To provide a complete solution, the process of developing and de-
ploying the developed solutions on a cloud-based server is explored with
additional features such as report generation and delivery. An emphasis
in this book is placed on the diversity of technologies exposing you to
many different alternatives for data collection and analysis, providing
you with the tools needed to develop a well-rounded solution.

1
2  Applied User Data Collection and Analysis Using JavaScript and PHP

1.2 WHO THIS BOOK IS AIMED AT


This book is aimed at web application developers who have some knowl-
edge with the basics of JavaScript and PHP. This book builds on this
basic knowledge and provides complete working examples that can easily
be deployed into existing web applications.
This book is not directed toward people who do not have these skills,
however, the knowledge about gathering data and generating insights are
still valuable to gain an understanding of what tools and approaches are
available if you do have developers to implement these solutions.

1.3 TECHNOLOGIES USED


In this book, a clear line between the technologies used throughout the
chapters can be seen. On the client-side, e.g., in the web browser of
the user, HTML and JavaScript will be used. On the server-side, PHP
version 7.41 running on an Apache version 2.4 web server2 is used to do
the bulk of the processing of the data, e.g., storing the information in a
database and calculating statistics.
JavaScript is used as it provides the ability to manipulate and present
data to the user without the need to redirect the user to multiple differ-
ent pages. Using the collected data, visualizations will be created using
JavaScript and HTML/CSS libraries. As JavaScript is a browser-based
programming language implemented by individual web browser vendors,
each of the browsers can have slight variations as to how it is interpreted.
To side-step the problem of cross-browser compatibility issues, we will
utilize JavaScript libraries wherever possible. The main JavaScript li-
brary that is used in this book is jQuery version 3.5.3
jQuery offers all the features that plain JavaScript has to offer, but all
of the cross-browser issues have been thoroughly tested. Any new user to
JavaScript often searches for code and finds browser-specific JavaScript
code, considering this the correct solution. But code that may work
correctly in one browser may not work on a different browser. Much to
the developer’s frustration, even a different version of the same browser
may also cause issues when the sample code is run. For this reason, we
will use libraries extensively to fast track the development process.
To aid the visualization process, JavaScript-based libraries such as
1
https://www.php.net
2
https://www.apache.org
3
https://www.jquery.com
Introduction  3

D3.js, Charts.js, and Google Charts are explored as they offer high-
quality interactive visualizations. A focus is placed on the diversity of the
libraries used in this book to provide a learning experience with different
code bases.
As all data collected needs to be retrieved for analysis, different
data sources will be explored. Examples of this include utilizing comma-
separated value (CSV) files, simple text files, JSON files, and database
tables. In this book, the core database we will be using is the MySQL
8 community edition4 database as it is free, widely used, and integrates
with PHP.
Although many different web browsers exist, Google Chrome5 version
80 was used during the development of the examples in this book.

1.4 VARIATIONS OF DATA


In this section, we will begin the process of breaking down the two ap-
proaches that can be taken to gather data from users. The first approach
is active data collection, whereby the user is directly polled to provide
answers or judgments. The second approach is passive data collection,
whereby all of the data is gathered in the background without the need
for user intervention. Examples of this include gathering data by listen-
ing to the browser environment. As a user navigates a web application,
data can be recorded and saved for future retrieval.
Data can come in both structured and unstructured formats. An
example of structured data is a database table that contains the user level
of interest graded by the user between one and ten. The only possible
variations of this data are the numbers between the ranges provided
to the user. An additional component of this structured data is the
processing speed, as little to no processing is required since the data is
already in the desired format. To gain insights from this data, simple
metrics such as the total, sum, and average can be used.
Structured data is in contrast to unstructured data that may be held
in any number of different storage locations such as a text file, CSV file,
or a database table. This form of data inherently has no structure to it.
This adds complexity to processing the data as it is not just a simple
calculation or predefined column in a table. To extract meaning from this
4
https://dev.mysql.com/downloads/mysql
5
https://www.google.com/chrome
4  Applied User Data Collection and Analysis Using JavaScript and PHP

data, additional processing such as identifying relevance and importance


must be performed.
After processing, additional steps can be performed to identify the
relationships between individual pieces of data. Examples of this include
the use of charts to visualize these relationships. As the quantity of data
grows during the interactions with an application, methods of filtering
the data to provide focus on the crucial trends can be performed.

1.4.1 Active Data


Active data is any data that has been directly provided by a user. This
data can be collected by asking a user their opinion about a topic to a
brief “yes” or “no” answer to a question. Often users do not have the
time to give a wealth of information outlining how they feel about a
particular page or subject. This often leads developers to consider the
best time or approach to take to pose questions to the user.
The disadvantage of active data is that there is a cost associated with
interacting with users. At the end of any process, many users simply
do not want to leave any form of data and consider the process an
annoyance. Example of active data include:

• Number of times a user has shared or “liked” a particular page on


a website through a social media interface.

• Leaving a rating for a product on a website.

• Answering the questions in a survey.

• Setting custom options on a website.

1.4.2 Passive Data


Passive data is data collected in the background of an application with-
out any user intervention. Although the user is navigating through con-
tent and selecting different articles of interest, at no time is the user
ever formally requested to provide input about what they are currently
viewing or their opinions. Passive data collection approaches include:

• Length of time a user remains on a section of web application or


viewing a page.

• Statistics about popular pages that a user is viewing.


Introduction  5

• Amount of time a user has spent inside of a particular collection


of pages that are all directly related to each other.

• Demographic of a user.

• Click times when users are interacting with an application.

• Log files generated by an application.

• Geographic location/IP address of a user.

• Application usage patterns.

1.5 WHAT YOU NEED


As the focus of this book is the development of web applications, a
complete server stack is required. The three main technologies that are
used throughout this book include an Apache web server with the PHP
module and a MySQL database. For new developers, consider using a
pre-packaged solution such as XAMPP6 that is a preconfigured solution
for web developers offering all of these services without the need for
any effort installing and configuring each of the individual components.
XAMPP is currently available for Microsoft Windows, Apple Mac, and
Linux distributions.
Alternatives to XAMPP include tools such as MAMP7 , EasyPHP8 ,
and AMPPS.9
To aid the development process, JavaScript libraries are used
throughout this book. Instead of downloading the JavaScript files re-
quired for each different example, and to ensure the latest available
codebase is used, Content Delivery Networks (CDN) are used where
possible. These can be seen in the opening lines of each example.
As most PHP libraries are available pre-packaged, we will use
the command line application composer. This is a dependency
management tool for PHP. Composer can be downloaded from
https://getcomposer.org/download. During the installation process of
composer, it will ask to point to the location of the php.exe file. If you
are using a local web server, this is typically installed inside of the php/
folder that is detected automatically. Once composer has been installed,
6
https://www.apachefriends.org
7
https://www.mamp.info/en
8
https://www.easyphp.org
9
https://www.ampps.com
6  Applied User Data Collection and Analysis Using JavaScript and PHP

open a command prompt and navigate to the root folder of your project.
After this, issue the composer init command to begin the creation pro-
cess of the composer.json file.
Composer is different from other tools as it does not work on a per-
system basis, it is focused on a per-project basis. Each individual project
will have a collection of libraries specified that are defined inside of the
composer.json file. This is a human-readable file that contains a list of
different requirements for a given PHP project in JSON format.
An example of this is a composer file that defines a reference to
the PHPinsight package along with the version number of the pack-
age. Additional PHP packages to add to a project can be found at
https://packagist.org. Below is a sample of the JSON in a composer.json
file.

{
"require" : {
"jwhennessey/phpinsight": ">=2.0.9"
}
}

After the composer.json has been added to the project folder, com-
poser can be used to manage additional packages. By opening up a
command prompt and navigating into the root of the project where
composer.json is located, the install command can be issued to com-
poser. By doing this, the contents of the JSON file are parsed, and all
specified dependencies are downloaded and installed into the project.

composer install

In cases where we want to add a new dependency to the project we


can use the require command:

composer require jwhennessey/phpinsight

This process greatly improves the manual installation process of dif-


ferent packages that make up a project.

1.6 DEVELOPMENT ENVIRONMENT


Through the course of this book, a heavy focus is placed on the client-
side programming language JavaScript. When working with JavaScript,
a very small issue with one section of code can quickly bump into other
Introduction  7

sections, causing a cascade of errors. To help during the debugging pro-


cess of JavaScript, the console.log() function should be used frequently.
This function can be called from any location inside of a web page as
long as it is placed inside a JavaScript script tag. Sample Code 1 shows
a simple example of a web page with a call to this function.

1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>Hello World</title>
6 </head>
7 <body>
8 <p>Hello World!</p>
9
10 <script>
11 console.log("Hello world!");
12 </script>
13 </body>
14 </html>

SAMPLE CODE 1: Sample HTML document with embedded


JavaScript.

To access this console log in Google Chrome, the Ctrl+Shift+I keys


can be pressed together to view the developer tools, as shown in Figure
1.1.

FIGURE 1.1: Viewing the developer console in Google Chrome.

This console provides information about the errors that are encoun-
tered in JavaScript code and also information about which line the error
has occurred on. Individual JavaScript variables, objects and strings can
8  Applied User Data Collection and Analysis Using JavaScript and PHP

be passed to the console.log() function. To aid the debugging process,


calls can be made to the function to print before and after a piece of
JavaScript code has run. This allows us to easily see if the code has run
as expected.
As working with a local web server is designed to mimic the behavior
of a commercial server for development purposes, sometimes unwanted
features are implemented. One example of this is the browser-based web-
site caching that is performed when a local web page is opened. As
changes are being made to an application during the course of develop-
ment, the browser will often not render the latest version of the code,
opting to return a cached version. To prevent this, the developer tools
allow us to disable this caching feature.
By entering into the Network tab in Google Chrome developer tools,
the option to disable cache can be ticked during development, as shown
in Figure 1.2.

FIGURE 1.2: Disabling the cache in the developer console.

1.7 CODE EXAMPLES


This book contains a number of JavaScript/HTML and PHP code ex-
amples that can be run on your local Apache/PHP/MySQL server. To
aid development, complete examples can be downloaded from the official
website for this book at https://www.kylegoslin.ie/applied. For samples
that require the use of a database, the SQL create and insert state-
ments are also available. These should be added to your database prior
to running the examples locally.
These examples can be run with very minimal modifications. Typi-
cally, the access details for your database may be the only modification
that is needed to the original code. A focus has been placed on the de-
velopment of code examples that will run in isolation rather than part
of a larger framework. This provides the opportunity for these examples
to be placed into an existing application.
Although security is a significant component of web application de-
velopment, it is not the focus of this book. For this reason, if any
examples are used in a live environment, additional care should be taken
to implement correct security mechanisms.
Introduction  9

1.8 BOOK OUTLINE


In this section, a brief outline of the structure of this book is presented.
Chapter 1: Introduction, provided an outline of the core types of data
that can be gathered for analysis and the tools required to get started.
Chapter 2: Active data collection explores the various approaches that
can be used to collect data from a user directly, such as rating stars, bi-
nary feedback, and custom response forms. The foundation of JavaScript
tools that are used through this book is explored.
Chapter 3:Passive Data Collection, provides an outline of the pas-
sive data collection processes. Common data sources such as cookies,
server-side sessions, and files are explored as possible data sources. The
interactions that a user has with an application are explored, detailing
how data can be gathered using additional JavaScript tools and third-
party resources. As social media is a common source of data, the process
of gathering data from a social media website is explored using authen-
ticated API calls.
Once data has been gathered, a method of viewing the results can be
implemented. In Chapter 4: Custom Dashboards, the process of creating
a custom visualization dashboard with login and registration pages is
described. To aid the visualization of data, the process of adding simple
bar charts in both single and multi-column form are described. This
provides a data analyst with the means to dynamically add visualizations
based on data from any source dynamically.
In addition to numeric data, text forms the basis of many data
sources. In Chapter 5: Working with Text, the processing of text is de-
scribed. The identification of stop words is first described along with the
process of identifying red-flag terms that help identify terms of interest.
To gain a deeper insight into the context of text, n-grams are described.
To further aid this, the process of sentence completion, word stemming,
and synonym detection is described to provide the data analyst with a
method of identifying other relevant text of interest. To add a numeric
component to text, a focus is placed on term weighting approaches. Fi-
nally, when working with text-based feedback records, an approach for
sentiment analysis is described.
For gathered data, visualizations can easily be applied. In Chapter 6:
Text Visualization, the process of generating visualizations is described.
Word clouds are described to view the frequency of individual terms.
The relationships between data are outlined using a tree-based graph
format. To identify the relationships between custom terms of interest
10  Applied User Data Collection and Analysis Using JavaScript and PHP

on any given day, a linked graph is described. As data is often collected at


different times, a time-series analysis approach is described for positive
and negative feedback records.
Chapter 7: Time-based Feedback Analysis outlines the time-based
component of data and how it can be used for the segmentation of data.
As time is an ongoing entity, an approach based on time segment analysis
and visualization is described, allowing for individual time windows to be
viewed. The area of real-time feedback analysis is described for situations
where the data collection process is actively happening. To view larger
data sets in a single visualization, the process of creating positive and
negative feedback calendars for a given year is described. To view large
data sets on a smaller scale, the process of viewing custom color-coded
feedback heat map is described.
For any type of data, statistics can be derived. In Chapter 8: Feedback
Statistics and Overviews, the basics of statistics is described with com-
plete examples. As working on large data sets is often time-consuming,
the process of working with representative samples is described. The pro-
cess of calculating the percentage difference is then described as most of
the statistics generated can be represented as a percentage.
Finally, Chapter 9: Hosting, Reporting, and Distributing, the process
of PDF report generation based on PHP is described. As many of the
tasks that are performed on data are performed on a daily basis, the
process of task scheduling is described for both local and external ser-
vices. To provide the key stakeholders with the generated reports, the
process of integrating a cloud-based e-mail service is described. Finally,
once a complete application has been developed, the process of hosting
a PHP/JavaScript application on the Amazon Lightsail is described.

1.9 SUMMARY
This chapter introduced the tools and environment needed for running
the examples in this book. The concept of passive and active data was
described, outlining that data does not directly need to be harvested
from a user. Indirect methods, such as logging interactions with an ap-
plication and identifying relevant data sources, e.g., existing files and
social media streams, can be used to gather data for analysis. In Chap-
ter 2, the process of collecting data through active methods is described
to begin the cycle of data collection for analysis and visualization.
CHAPTER 2

Active Data Collection

2.1 INTRODUCTION
In this chapter, we will describe the process of collecting data from users
directly. This is done through the use of simple binary choices, text-based
content, and star ratings. The data is categorized as active data, as the
user is required to participate in the data collection process. However,
gathering data directly from users can be difficult, as users are often
unwilling to put time into the process. We attempt to make the process
of gathering data as simple and unobtrusive as possible for the user.

2.2 BINARY DATA COLLECTION


Many modern web applications provide the user with a simple data
collection mechanism in the form of a binary choice. Typically, this is
the result of answering a question. A simple Yes or No input field can
quickly gather a user’s opinion with minimal effort. These mechanisms
purposely limit the number of options and interactions a user can have.
The submission process for this data can also be automatic to prevent
the user from selecting a choice and then unintentionally forgetting to
press the submit button.
To aid the process of future analysis, each page in this sample appli-
cation is considered an individual article. Each article has a unique ID
to differentiate articles from one another.

Example 1: Binary data collection


This example consists of three core files and one library:

1. create.sql — This file is used to create the yesno database table.

11
12  Applied User Data Collection and Analysis Using JavaScript and PHP

2. binary.html — The main HTML/JavaScript binary data collection


interface.

3. ajax.php — Used to receive data and store it in a MySQL database.

4. jQuery — Used to perform a JavaScript POST to the ajax.php


page.

Example code: create.sql


Before creating the user interface, a new MySQL database table is first
required to be titled yesno, as shown in Sample Code 2. The table con-
sists of four different attributes, where two of these are automatically
generated when a new record is inserted. The first of these is the ID
column that is auto-incremented and a primary key. Every time a new
record is created in the database, the ID will increment by 1. This is
useful for uniquely identifying the record in the future. The second col-
umn is titled mytime. Every time a new record is created, the current
time stamp on the server will be logged with the record. The third and
fourth columns are the two that will vary depending on what article is
being viewed by the user, and the choice selected.
As the articleid is numeric, the data type for this will be set to int.
The result column, however, contains the string Yes or No. To hold this,
the result column data type is set to varchar.
1 CREATE TABLE `yesno` (
2 `id` INT NOT NULL AUTO_INCREMENT,
3 `mytime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
4 `articleid` INT,
5 `result` VARCHAR (10),
6 PRIMARY KEY ( `id`)
7 );

SAMPLE CODE 2: create.sql — yesno database table SQL.

Example code: binary.html


In Sample Code 3, on line 1, a reference to the jQuery1 Content Delivery
Network (CDN) is first added. Two radio buttons are added along with
a simple div tag to make the form uniquely identifiable on lines 4 and 6.
1
https://code.jquery.com
Active Data Collection  13

JavaScript will be responsible for listening to the changes that have been
made to the form, and also for passing the data off to the web server
to be saved in a database table. In the example code, both of the radio
buttons have the same name attribute. This is done as both are part of
the same group, preventing both from being selected at the same time.
On line 10, a jQuery click() listener is added. This listens to clicks
that are made on the radio buttons. When identifying the radio buttons,
the input:radio value is passed to the jQuery selector specifying that we
are interested in the radio buttons that have the name attribute defined
as answer. When either of the radio buttons is clicked, the JavaScript
inside of the click function will trigger. Inside this function on line 11, we
can use the keyword this, which represents the radio button that has just
been clicked. Using this, we can call the val() function that will return
the value from the radio button that has been selected.
After this on line 12, a custom JavaScript function titled saveAn-
swer() is called. When called, the current value the user has selected
will be passed to this function. The saveAnswer() function on line 15
takes a single parameter in the form of the value the user selected. In-
side this function, a jQuery POST is added on line 16 to send the an-
swer variable to a server-side page titled ajax.php to save the data to
the database table. Inside the jQuery POST the first parameter that
is passed is ajax.php. This is a reference to the page that will handle
the database interactions. A custom type parameter is added so we can
reuse the same ajax.php page for multiple different purposes by uniquely
identifying the different types of requests we are sending to the page.
The type variable is set to yesno. Next, we will pass the articleid that
is used to identify the page where the data has come from. The articleid
is set to 1221. The final parameter that is passed is titled result. The
value for this variable comes from the user selection that was passed to
the saveAnswer() function titled answer. On line 18, a done() function
is added. This function is called when all of the processing has been
completed, and the data has been sent to the database. A simple alert()
function is added on line 19 to tell the user Thank you! after they have
submitted the data.
14  Applied User Data Collection and Analysis Using JavaScript and PHP

1 <script src="https://code.jquery.com/jquery-3.5.1.min.js"
2 crossorigin="anonymous">
3 </script>
4 <div id="binaryfeedback">
5 Are you happy with this service?
6 <input type="radio" name="answer" value="Yes"> Yes
7 <input type="radio" name="answer" value="No"> No
8 </div>
9 <script>
10 $( "input:radio[name=answer]" ).click(function() {
11 var val = $(this).val();
12 saveAnswer(val);
13 });
14
15 function saveAnswer(answer){
16 $.post( "ajax.php", { type: "yesno", articleid: "1221",
17 result: answer })
18 .done(function( data ) {
19 alert('Thank you!'+data);
20 });
21 }
22 </script>
SAMPLE CODE 3: binary.html — Yes/No options being presented to
the user.
Example code: ajax.php

In Sample Code 4, a new PHP page is created titled ajax.php. This


additional page is never directly opened by the user; it is called dynami-
cally through the jQuery POST function. When this page is called every
time the data will be saved to a database table using a PHP Data Object
(PDO). On line 2, the POST variable is referenced to extract the value
that was passed across from the JavaScript request. On line 3, a simple if
statement is used to check what value the type variable contained. If the
type was set to yesno, a call is made to the yesNoLog() PHP function on
line 4. After the if statement, the function definition for the yesNoLog()
function is added on line 6.
In the body of the PHP function on lines 7 and 8, two variables
are created to catch the values that have been sent across from the
jQuery POST request. It is important to ensure that the variable names
inside the POST match to the variables that were sent across using the
JavaScript POST earlier. In this example the articleid and the result
are extracted from the POST. Once the variables have been gathered,
a connection to the database can be made. The database interactions
Active Data Collection  15

is performed inside of a try-catch statement that begins on line 9. The


host, dbname, user, and pass variables are defined on lines 10 to 13.
These variables reflect the MySQL database that is being used. On
line 14, a new PHP PDO is created. On line 16, a simple SQL INSERT
statement is created. Two question marks are inserted at the end of the
statement. These are unnamed placeholders that hold the place for the
variables that will be appended.
The two variables that we caught from the POST are passed to
the SQL statement using the bindParam() function on lines 19 and 20.
This is a safe method of passing variables to a database without caus-
ing any security issues as sanitization is performed on the variables. As
the articleid is an integer, the type of parameter being added is set to
PARAM INT. The type of result being added is set as a PARAM STR.
The final step in this process is to run the SQL statement. On line 21,
the execute() function is called. A catch is added on line 22 to com-
plete the try-catch block. If any errors are presented when connecting
to the database or running the code, the catch block will run, and the
getMessage() function will be called to retrieve the error message.
1 <?php
2 $type = $_POST['type'];
3 if($type == 'yesno'){
4 yesNoLog();
5 }
6 function yesNoLog(){
7 $articleid = $_POST['articleid'];
8 $result = $_POST['result'];
9 try {
10 $host = 'localhost';
11 $dbname = 'bookexamples';
12 $user = 'sampleuser';
13 $pass = '3C9038A509BE6145AAD6827B4568AD918BC3DAC0';
14 $DBH = new PDO("mysql:host=$host;dbname=$dbname",
15 $user, $pass);
16 $sql = "INSERT INTO `yesno` (`articleid`, `result`) VALUES
17 (?, ?);";
18 $sth = $DBH->prepare($sql);
19 $sth->bindParam(1, $articleid, PDO::PARAM_INT);
20 $sth->bindParam(2, $result, PDO::PARAM_STR);
21 $sth->execute();
22 } catch(PDOException $e) {echo $e->getMessage();}
23 }
SAMPLE CODE 4: ajax.php — PHP logging binary choice to the
yesno database table.
16  Applied User Data Collection and Analysis Using JavaScript and PHP

Output

Figure 2.1, shows the output of these radio buttons with a small
question such as Are you happy with this service?

FIGURE 2.1: Yes and No binary options.

In Figure 2.2 the alert box that is shown to the user after the data
has been recorded in the database table is shown.

FIGURE 2.2: Alert box showing the selected radio button value.

2.3 TEXT-BASED DATA COLLECTION


A further adaptation to a basic binary data collection process can be
added to include an additional text field that only appears if a user
selects the No option. Although text requires additional processing to
quantify and gather insights from, it nonetheless is useful as a number
of derivative statistics can be drawn from this data.

Example 2: Providing an option to gather text


This example consists of three core files and one library:

1. create.sql — This file is used to create the whyanswerlog database


table. This table has an additional column to store text.

2. binary.html — The main HTML/JavaScript binary data collection


interface with an additional text field.
Active Data Collection  17

3. ajax.php — Used to receive data and store it in a MySQL database


table.

4. jQuery — Used to add a click handler and to perform a JavaScript


POST to the ajax.php page.

Example code: create.sql

To store text, an additional database table is required. In Sample


Code 5, the result column is set to 500 characters to allow for the text-
based answer.
1 CREATE TABLE `whyanswerlog` (
2 `id` INT NOT NULL AUTO_INCREMENT,
3 `mytime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
4 `articleid` INT,
5 `result` VARCHAR (500),
6 PRIMARY KEY ( `id`)
7 );

SAMPLE CODE 5: whyanswer log database table SQL.

Example code: binary.html


In Sample Code 6, on line 5, a div tag is added to hold the text area for
the user to elaborate on why they chose No. On line 11, a simple submit
button is added to trigger the saving process. The submit button has an
onclick set to call the saveWhyAnswer() JavaScript function.
On line 14, a click() handler for the radio button is added. On line 19,
a simple if statement that will check to see if the user clicked No is added.
If they did, we will call the findOutWhy() function that will trigger the
input field for user input to open on line 20. On line 31, a function
titled findOutWhy() is added. Inside this on line 32, the jQuery show()
function is called on the jQuery selector that references the explainwhy
div tag.
When the user clicks the submit button, a call is made to the save-
WhyAnswer() function as shown on line 34. In this function on line 35,
the text entered by the user is gathered using the getElementById() func-
tion that takes a reference to the whyanswer text area. On line 36, the
POST function is called that is similar to the previous example. On line
18  Applied User Data Collection and Analysis Using JavaScript and PHP

39 a simple alert() statement is used to present the user with the text
thank you for your comments!.
On line 42, when the page is finished loading, a shorthand version
of the document ready function is used. This ensures that the page is
loaded, and all the different elements on the page are ready. Once the
page has fully loaded, jQuery is used to hide the div that we have just
created using the hide() function on line 43 until the user selects the No
option.

1 <script src="https://code.jquery.com/jquery-3.5.1.min.js"
2 crossorigin="anonymous"></script>
3 <input type="radio" name="answer" value="Yes"> Yes <br>
4 <input type="radio" name="answer" value="No"> No<br>
5 <div id="explainwhy">
6 Sorry to hear you were not happy,<br>
7 Would you like to say why?<br>
8 <textarea id="whyanswer" rows="5" cols="50">
9 </textarea>
10 <br>
11 <button onclick="saveWhyAnswer()">Submit</button>
12 </div>
13 <script>
14 $( "input:radio[name=answer]" ).click(function() {
15
16 var val = $(this).val();
17 saveAnswer(val)
18
19 if(val == 'No'){
20 findOutWhy();
21 }
22 });
23
24 function saveAnswer(answer){
25 $.post( "ajax.php", { type: "yesno", articleid: "1221",
26 result: answer })
27 .done(function( data ) {
28 alert('Thank you!');
29 });
30 }
31 function findOutWhy(){
32 $("#explainwhy").show();
33 }
34 function saveWhyAnswer(){
35 var answer = document.getElementById('whyanswer').value;
Active Data Collection  19

36 $.post( "ajax.php", { type: "whyanswer", articleid: "1221",


37 result: answer })
38 .done(function( data ) {
39 alert('Thank you for your comments!');
40 });
41 }
42 $(function() {
43 $("#explainwhy").hide();
44 });
45
46 </script>

SAMPLE CODE 6: binary.html — HTML form with additional div tag


allowing the user to enter comments.

Example code: ajax.php


Instead of using the ajax.php page for one purpose, it was set up in
the previous example to use the type variable that allows us to perform
multiple different functions with the same page. In Sample Code 7, we
will add an else if statement on line 6 that will be used to redirect the
flow of execution to the whyAnswer() function if the type variable is set
to whyanswer. In the whyAnswer() function on lines 28 and 29, the two
variables articleid and result are first extracted from the POST variable.
A connection to the database is created on line 39 inside the try-catch
statement. A simple INSERT statement is used on line 37 to put the
record in the database table. The values for both columns are represented
with question marks that are later replaced by values when a call is
made to the bindParam() function on lines 40 and 41. As the result
contains text, the data type in the second bindParam() call is set to
PARAM STR.

1 <?php
2 $type = $_POST['type'];
3 if($type == 'yesno'){
4 yesNoLog();
5 }
6 else if($type == 'whyanswer'){
7 whyAnswer();
8 }
9 function yesNoLog(){
10 $articleid = $_POST['articleid'];
11 $result = $_POST['result'];
20  Applied User Data Collection and Analysis Using JavaScript and PHP

12 try {
13 $host = 'localhost';
14 $dbname = 'bookexamples';
15 $user = 'sampleuser';
16 $pass = '3C9038A509BE6145AAD6827B4568AD918BC3DAC0';
17 $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user,
18 $pass);
19 $sql = "INSERT INTO `yesnolog` (`articleid`, `result`)
20 VALUES (?, ?);";
21 $sth = $DBH->prepare($sql);
22 $sth->bindParam(1, $articleid, PDO::PARAM_INT);
23 $sth->bindParam(2, $result, PDO::PARAM_STR);
24 $sth->execute();
25 } catch(PDOException $e) {echo $e;}
26 }
27 function whyAnswer(){
28 $articleid = $_POST['articleid'];
29 $result = $_POST['result'];
30 try {
31 $host = 'localhost';
32 $dbname = 'bookexamples';
33 $user = 'sampleuser';
34 $pass = '3C9038A509BE6145AAD6827B4568AD918BC3DAC0';
35 $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user,
36 $pass);
37 $sql = "INSERT INTO `whyanswerlog` (`articleid`, `result`)
38 VALUES (?, ?);";
39 $sth = $DBH->prepare($sql);
40 $sth->bindParam(1, $articleid, PDO::PARAM_INT);
41 $sth->bindParam(2, $result, PDO::PARAM_STR);
42 $sth->execute();
43 } catch(PDOException $e) {echo $e;}
44 }
45 ?>

SAMPLE CODE 7: ajax.php — Additional PHP function to insert


text a user has entered into a database table.

Output
Figure 2.3 shows the result of selecting No on the Yes/No radio buttons.
A question is prompted to the user along with a text area where they
can describe their issue.
Another random document with
no related content on Scribd:
—Hélas! mon pauvre aimé, ne faisons-nous pas là quelque
chose de mal? dit-elle tout émue, car nous attendrons longtemps.
—Mon oncle disait que l’adoration était le pain quotidien de la
patience, en parlant du chrétien qui aime Dieu. Je puis t’aimer ainsi,
je t’ai, depuis longtemps, confondue avec le Seigneur de toutes
choses: je suis à toi, comme je suis à lui.
Ils restèrent pendant quelques moments en proie à la plus douce
exaltation. Ce fut la sincère et calme effusion d’un sentiment qui,
semblable à une source trop pleine, débordait par de petites vagues
incessantes. Les événements qui séparaient ces deux amants
étaient un sujet de mélancolie qui rendit leur bonheur plus vif, en lui
donnant quelque chose d’aigu comme la douleur; Félicie revint trop
tôt pour eux. Emmanuel, éclairé par le tact délicieux qui fait tout
deviner en amour, laissa les deux sœurs seules, après avoir
échangé avec Marguerite un regard où elle put voir tout ce que lui
coûtait cette discrétion, car il y exprima combien il était avide de ce
bonheur désiré si longtemps, et qui venait d’être consacré par les
fiançailles du cœur.
—Viens ici, petite sœur, dit Marguerite en prenant Félicie par le
cou. Puis, la ramenant dans le jardin, elles allèrent s’asseoir sur le
banc auquel chaque génération avait confié ses paroles d’amour,
ses soupirs de douleur, ses méditations et ses projets. Malgré le ton
joyeux et l’aimable finesse du sourire de sa sœur, Félicie éprouvait
une émotion qui ressemblait à un mouvement de peur, Marguerite lui
prit la main et la sentit trembler.
—Mademoiselle Félicie, dit l’aînée en s’approchant de l’oreille de
sa sœur, je lis dans votre âme. Pierquin est venu souvent pendant
mon absence, il est venu tous les soirs, il vous a dit de douces
paroles, et vous les avez écoutées. Félicie rougit.—Ne t’en défends
pas, mon ange, reprit Marguerite, il est si naturel d’aimer! Peut-être
ta chère âme changera-t-elle un peu la nature du cousin, il est
égoïste, intéressé, mais c’est un honnête homme; et sans doute ses
défauts serviront à ton bonheur. Il t’aimera comme la plus jolie de
ses propriétés, tu feras partie de ses affaires. Pardonne-moi ce mot,
chère amie? tu le corrigeras des mauvaises habitudes qu’il a prises
de ne voir partout que des intérêts, en lui apprenant les affaires du
cœur. Félicie ne put qu’embrasser sa sœur.—D’ailleurs, reprit
Marguerite, il a de la fortune. Sa famille est de la plus haute et de la
plus ancienne bourgeoisie. Mais serait-ce donc moi qui
m’opposerais à ton bonheur si tu veux le trouver dans une condition
médiocre?
Félicie laissa échapper ces mots:—Chère sœur!
—Oh! oui, tu peux te confier à moi, s’écria Marguerite. Quoi de
plus naturel que de nous dire nos secrets.
Ce mot plein d’âme détermina l’une de ces causeries délicieuses
où les jeunes filles se disent tout. Quand Marguerite, que l’amour
avait faite experte, eut reconnu l’état du cœur de Félicie, elle finit en
lui disant:—Hé bien, ma chère enfant, assurons-nous que le cousin
t’aime véritablement; et... alors...
—Laisse-moi faire, répondit Félicie en riant, j’ai mes modèles.
—Folle? dit Marguerite en la baisant au front.
Quoique Pierquin appartînt à cette classe d’hommes qui dans le
mariage voient des obligations, l’exécution des lois sociales et un
mode pour la transmission des propriétés; qu’il lui fût indifférent
d’épouser ou Félicie ou Marguerite, si l’une ou l’autre avaient le
même nom et la même dot; il s’aperçut néanmoins que toutes deux
étaient, suivant une de ses expressions, des filles romanesques et
sentimentales, deux adjectifs que les gens sans cœur emploient
pour se moquer des dons que la nature sème d’une main
parcimonieuse à travers les sillons de l’humanité, le notaire se dit
sans doute qu’il fallait hurler avec les loups; et, le lendemain, il vint
voir Marguerite, il l’emmena mystérieusement dans le petit jardin, et
se mit à parler sentiment, puisque c’était une des clauses du contrat
primitif qui devait précéder, dans les lois du monde, le contrat
notarié.
—Chère cousine, lui dit-il, nous n’avons pas toujours été du
même avis sur les moyens à prendre pour arriver à la conclusion
heureuse de vos affaires; mais vous devez reconnaître aujourd’hui
que j’ai toujours été guidé par un grand désir de vous être utile. Hé!
bien, hier j’ai gâté mes offres par une fatale habitude que nous
donne l’esprit notaire, comprenez-vous?... Mon cœur n’était pas
complice de ma sottise. Je vous ai bien aimée; mais nous avons une
certaine perspicacité, nous autres, et je me suis aperçu que je ne
vous plaisais pas. C’est ma faute! un autre a été plus adroit que moi.
Hé! bien, je viens vous avouer tout bonifacement que j’éprouve un
amour réel pour votre sœur Félicie. Traitez-moi donc comme un
frère? puisez dans ma bourse, prenez à même! allez, plus vous
prendrez, plus vous me prouverez d’amitié. Je suis tout à vous, sans
intérêt, entendez-vous? ni à douze, ni à un quart pour cent. Que je
sois trouvé digne de Félicie et je serai content. Pardonnez-moi mes
défauts, ils ne viennent que de la pratique des affaires, le cœur est
bon, et je me jetterais dans la Scarpe, plutôt que de ne pas rendre
ma femme heureuse.
—Voilà qui est bien, cousin! dit Marguerite, mais ma sœur
dépend d’elle et de notre père...
—Je sais cela, ma chère cousine, dit le notaire, mais vous êtes la
mère de toute la famille, et je n’ai rien plus à cœur que de vous
rendre juge du mien.
Cette façon de parler peint assez bien l’esprit de l’honnête
notaire. Plus tard, Pierquin devint célèbre par sa réponse au
commandant du camp de Saint-Omer qui l’avait prié d’assister à une
fête militaire, et qui fut ainsi conçue: Monsieur Pierquin-Claës de
Molina-Nourho, maire de la ville de Douai, chevalier de la Légion-
d’Honneur, aura celui de se rendre, etc.
Marguerite accepta l’assistance du notaire, mais seulement dans
tout ce qui concernait sa profession, afin de ne compromettre en rien
ni sa dignité de femme, ni l’avenir de sa sœur, ni les déterminations
de son père. Ce jour même elle confia sa sœur à la garde de Josette
et de Martha, qui se vouèrent corps et âme à leur jeune maîtresse,
en en secondant les plans d’économie. Marguerite partit aussitôt
pour Waignies où elle commença ses opérations qui furent
savamment dirigées par Pierquin. Le dévouement s’était chiffré dans
l’esprit du notaire comme une excellente spéculation, ses soins, ses
peines furent alors en quelque sorte une mise de fonds qu’il ne
voulut point épargner. D’abord, il tenta d’éviter à Marguerite la peine
de faire défricher et de labourer les terres destinées aux fermes. Il
avisa trois jeunes fils de fermiers riches qui désiraient s’établir, il les
séduisit par la perspective que leur offrait la richesse de ces terrains,
et réussit à leur faire prendre à bail les trois fermes qui allaient être
construites. Moyennant l’abandon du prix de la ferme pendant trois
ans, les fermiers s’engagèrent à en donner dix mille francs de loyer
à la quatrième année, douze mille à la sixième, et quinze mille
pendant le reste du bail; à creuser les fossés, faire les plantations et
acheter les bestiaux. Pendant que les fermes se bâtirent, les
fermiers vinrent défricher leurs terres. Quatre ans après le départ de
Balthazar, Marguerite avait déjà presque rétabli la fortune de son
frère et de sa sœur. Deux cent mille francs suffirent à payer toutes
les constructions. Ni les secours, ni les conseils ne manquèrent à
cette courageuse fille dont la conduite excitait l’admiration de la ville.
Marguerite surveilla ses bâtisses, l’exécution de ses marchés et de
ses baux avec ce bon sens, cette activité, cette constance que
savent déployer les femmes quand elles sont animées par un grand
sentiment. Dès la cinquième année, elle put consacrer trente mille
francs de revenu que donnèrent les fermes, les rentes de son frère
et le produit des biens paternels, à l’acquittement des capitaux
hypothéqués, et à la réparation des dommages que la passion de
Balthazar avait faits dans sa maison. L’amortissement devait donc
aller rapidement par la décroissance des intérêts. Emmanuel de
Solis offrit d’ailleurs à Marguerite les cent mille francs qui lui
restaient sur la succession de son oncle, et qu’elle n’avait pas
employés, en y joignant une vingtaine de mille francs de ses
économies, en sorte que, dès la troisième année de sa gestion, elle
put acquitter une assez forte somme de dettes. Cette vie de
courage, de privations et de dévouement ne se démentit point durant
cinq années; mais tout fut d’ailleurs succès et réussite, sous
l’administration et l’influence de Marguerite.
Devenu ingénieur des ponts-et-chaussées, Gabriel aidé par son
grand-oncle fit une rapide fortune dans l’entreprise d’un canal qu’il
construisit, et sut plaire à sa cousine mademoiselle Conyncks, que
son père adorait et l’une des plus riches héritières des deux
Flandres. En 1824, les biens de Claës se trouvèrent libres, et la
maison de la rue de Paris avait réparé ses pertes. Pierquin demanda
positivement la main de Félicie à Balthazar, de même que monsieur
de Solis sollicita celle de Marguerite.
Au commencement du mois de janvier 1825, Marguerite et
monsieur Conyncks partirent pour aller chercher le père exilé de qui
chacun désirait vivement le retour, et qui donna sa démission afin de
rester au milieu de sa famille dont le bonheur allait recevoir sa
sanction. En l’absence de Marguerite, qui souvent avait exprimé le
regret de ne pouvoir remplir les cadres vides de la galerie et des
appartements de réception, pour le jour où son père reprendrait sa
maison, Pierquin et monsieur de Solis complotèrent avec Félicie de
préparer à Marguerite une surprise qui ferait participer en quelque
sorte la sœur cadette à la restauration de la maison Claës. Tous
deux avaient acheté à Félicie plusieurs beaux tableaux qu’ils lui
offrirent pour décorer la galerie. Monsieur Conyncks avait eu la
même idée. Voulant témoigner à Marguerite la satisfaction que lui
causait sa noble conduite et son dévouement à remplir le mandat
que lui avait légué sa mère, il avait pris des mesures pour qu’on
apportât une cinquantaine de ses plus belles toiles et quelques-unes
de celles que Balthazar avait jadis vendues, en sorte que la galerie
Claës fut entièrement remeublée. Marguerite était déjà venue
plusieurs fois voir son père, accompagnée de sa sœur, ou de Jean;
chaque fois, elle l’avait trouvé progressivement plus changé; mais
depuis sa dernière visite, la vieillesse s’était manifestée chez
Balthazar par d’effrayants symptômes à la gravité desquels
contribuait sans doute la parcimonie avec laquelle il vivait afin de
pouvoir employer la plus grande partie de ses appointements à faire
des expériences qui trompaient toujours son espoir. Quoiqu’il ne fût
âgé que de soixante-cinq ans, il avait l’apparence d’un octogénaire.
Ses yeux s’étaient profondément enfoncés dans leurs orbites, ses
sourcils avaient blanchi, quelques cheveux lui garnissaient à peine la
nuque; il laissait croître sa barbe qu’il coupait avec des ciseaux
quand elle le gênait; il était courbé comme un vieux vigneron; puis le
désordre de ses vêtements avait repris un caractère de misère que
la décrépitude rendait hideux. Quoiqu’une pensée forte animât ce
grand visage dont les traits ne se voyaient plus sous les rides, la
fixité du regard, un air désespéré, une constante inquiétude y
gravaient les diagnostics de la démence, ou plutôt de toutes les
démences ensemble. Tantôt il y apparaissait un espoir qui donnait à
Balthazar l’expression du monomane; tantôt l’impatience de ne pas
deviner un secret qui se présentait à lui comme un feu follet y mettait
les symptômes de la fureur; puis tout à coup un rire éclatant
trahissait la folie, enfin la plupart du temps l’abattement le plus
complet résumait toutes les nuances de sa passion par la froide
mélancolie de l’idiot. Quelque fugaces et imperceptibles que fussent
ces expressions pour des étrangers, elles étaient malheureusement
trop sensibles pour ceux qui connaissaient un Claës sublime de
bonté, grand par le cœur, beau de visage et duquel il n’existait que
de rares vestiges. Vieilli, lassé comme son maître par de constants
travaux, Lemulquinier n’avait pas eu à subir comme lui les fatigues
de la pensée; aussi sa physionomie offrait-elle un singulier mélange
d’inquiétude et d’admiration pour son maître, auquel il était facile de
se méprendre: quoiqu’il écoutât sa moindre parole avec respect, qu’il
suivît ses moindres mouvements avec une sorte de tendresse, il
avait soin du savant comme une mère a soin d’un enfant; souvent il
pouvait avoir l’air de le protéger, parce qu’il le protégeait
véritablement dans les vulgaires nécessités de la vie auxquelles
Balthazar ne pensait jamais. Ces deux vieillards enveloppés par une
idée, confiants dans la réalité de leur espoir, agités par le même
souffle, l’un représentant l’enveloppe et l’autre l’âme de leur
existence commune, formaient un spectacle à la fois horrible et
attendrissant. Lorsque Marguerite et monsieur Conyncks arrivèrent,
ils trouvèrent Claës établi dans une auberge, son successeur ne
s’était pas fait attendre et avait déjà pris possession de la place.
A travers les préoccupations de la Science, un désir de revoir sa
patrie, sa maison, sa famille agitait Balthazar; la lettre de sa fille lui
avait annoncé des événements heureux; il songeait à couronner sa
carrière par une série d’expériences qui devait le mener enfin à la
découverte de son problème, il attendait donc Marguerite avec une
excessive impatience. La fille se jeta dans les bras de son père en
pleurant de joie. Cette fois, elle venait chercher la récompense d’une
vie douloureuse, et le pardon de sa gloire domestique. Elle se
sentait criminelle à la manière des grands hommes qui violent les
libertés pour sauver la patrie. Mais en contemplant son père, elle
frémit en reconnaissant les changements qui, depuis sa dernière
visite, s’étaient opérés en lui. Conyncks partagea le secret effroi de
sa nièce, et insista pour emmener au plus tôt son cousin à Douai où
l’influence de la patrie pouvait le rendre à la raison, à la santé, en le
rendant à la vie heureuse du foyer domestique. Après les premières
effusions de cœur qui furent plus vives de la part de Balthazar que
Marguerite ne le croyait, il eut pour elle des attentions singulières; il
témoigna le regret de la recevoir dans une mauvaise chambre
d’auberge, il s’informa de ses goûts, il lui demanda ce qu’elle voulait
pour ses repas avec les soins empressés d’un amant; il eut enfin les
manières d’un coupable qui veut s’assurer de son juge. Marguerite
connaissait si bien son père qu’elle devina le motif de cette
tendresse, en supposant qu’il pouvait avoir en ville quelques dettes
desquelles il voulait s’acquitter avant son départ. Elle observa
pendant quelque temps son père, et vit alors le cœur humain à nu.
Balthazar s’était rapetissé. Le sentiment de son abaissement,
l’isolement dans lequel le mettait la Science, l’avait rendu timide et
enfant dans toutes les questions étrangères à ses occupations
favorites; sa fille aînée lui imposait, le souvenir de son dévouement
passé, de la force qu’elle avait déployée, la conscience du pouvoir
qu’il lui avait laissé prendre, la fortune dont elle disposait et les
sentiments indéfinissables qui s’étaient emparés de lui, depuis le
jour où il avait abdiqué sa paternité déjà compromise, la lui avaient
sans doute grandie de jour en jour. Conyncks semblait n’être rien
aux yeux de Balthazar, il ne voyait que sa fille et ne pensait qu’à elle
en paraissant la redouter comme certains maris faibles redoutent la
femme supérieure qui les a subjugués; lorsqu’il levait les yeux sur
elle, Marguerite y surprenait avec douleur une expression de crainte,
semblable à celle d’un enfant qui se sent fautif. La noble fille ne
savait comment concilier la majestueuse et terrible expression de ce
crâne dévasté par la Science et par les travaux, avec le sourire
puéril, avec la servilité naïve qui se peignaient sur les lèvres et la
physionomie de Balthazar. Elle fut blessée du contraste que
présentaient cette grandeur et cette petitesse, et se promit
d’employer son influence à faire reconquérir à son père toute sa
dignité, pour le jour solennel où il allait reparaître au sein de sa
famille. D’abord, elle saisit un moment où ils se trouvèrent seuls pour
lui dire à l’oreille:—Devez-vous quelque chose ici?
Balthazar rougit et répondit d’un air embarrassé:—Je ne sais
pas, mais Lemulquinier te le dira. Ce brave garçon est plus au fait de
mes affaires que je ne le suis moi-même.
Marguerite sonna le valet de chambre, et quand il vint, elle étudia
presque involontairement la physionomie des deux vieillards.
—Monsieur désire quelque chose? demanda Lemulquinier.
Marguerite, qui était tout orgueil et noblesse, eut un serrement de
cœur, en s’apercevant au ton et au maintien du valet, qu’il s’était
établi quelque familiarité mauvaise entre son père et le compagnon
de ses travaux.
—Mon père ne peut donc pas faire sans vous le compte de ce
qu’il doit ici? dit Marguerite.
—Monsieur, reprit Lemulquinier, doit...
A ces mots, Balthazar fit à son valet de chambre un signe
d’intelligence que Marguerite surprit et qui l’humilia.
—Dites-moi tout ce que doit mon père, s’écria-t-elle.
—Ici, monsieur doit un millier d’écus à un apothicaire qui tient
l’épicerie en gros, et qui nous a fourni des potasses caustiques, du
plomb, du zinc, et des réactifs.
—Est-ce tout? dit Marguerite.
Balthazar réitéra un signe affirmatif à Lemulquinier qui, fasciné
par son maître, répondit:—Oui, mademoiselle.
—Hé! bien, reprit-elle, je vais vous les remettre.
Balthazar embrassa joyeusement sa fille en lui disant:—Tu es un
ange pour moi, mon enfant.
Et il respira plus à l’aise, en la regardant d’un œil moins triste,
mais, malgré cette joie, Marguerite aperçut facilement sur son visage
les signes d’une profonde inquiétude, et jugea que ces mille écus
constituaient seulement les dettes criardes du laboratoire.
—Soyez franc, mon père, dit-elle en se laissant asseoir sur ses
genoux par lui, vous devez encore quelque chose? Avouez-moi tout,
revenez dans votre maison sans conserver un principe de crainte au
milieu de la joie générale.
—Ma chère Marguerite, dit-il en lui prenant les mains et les lui
baisant avec une grâce qui semblait être un souvenir de sa
jeunesse, tu me gronderas...
—Non, dit-elle.
—Vrai, répondit-il en laissant échapper un geste de joie
enfantine, je puis donc tout te dire, tu paieras...
—Oui, dit-elle en réprimant des larmes qui lui venaient aux yeux.
—Hé! bien, je dois... Oh! je n’ose pas...
—Mais dites donc, mon père!
—C’est considérable, reprit-il!
Elle joignit les mains par un mouvement de désespoir.
—Je dois trente mille francs à messieurs Protez et Chiffreville.
—Trente mille francs, dit-elle, sont mes économies, mais j’ai du
plaisir à vous les offrir, ajouta-t-elle en lui baisant le front avec
respect.
Il se leva, prit sa fille dans ses bras, et tourna tout autour de sa
chambre en la faisant sauter comme un enfant; puis, il la remit sur le
fauteuil où elle était, en s’écriant:—Ma chère enfant, tu es un trésor
d’amour! Je ne vivais plus. Les Chiffreville m’ont écrit trois lettres
menaçantes et voulaient me poursuivre, moi qui leur ai fait faire une
fortune.
—Mon père, dit Marguerite avec un accent de désespoir, vous
cherchez donc toujours?
—Toujours, dit-il avec un sourire de fou. Je trouverai, va!... Si tu
savais où nous en sommes.
—Qui, nous?...
—Je parle de Mulquinier, il a fini par me comprendre, il m’aide
bien. Pauvre garçon, il m’est si dévoué!
Conyncks interrompit la conversation en entrant, Marguerite fit
signe à son père de se taire en craignant qu’il ne se déconsidérât
aux yeux de leur oncle. Elle était épouvantée des ravages que la
préoccupation avait faits dans cette grande intelligence absorbée
dans la recherche d’un problème peut-être insoluble. Balthazar, qui
ne voyait sans doute rien au delà de ses fourneaux, ne devinait
même pas la libération de sa fortune. Le lendemain, ils partirent pour
la Flandre. Le voyage fut assez long pour que Marguerite pût
acquérir de confuses lumières sur la situation dans laquelle se
trouvaient son père et Lemulquinier. Le valet avait-il sur le maître cet
ascendant que savent prendre sur les plus grands esprits les gens
sans éducation qui se sentent nécessaires, et qui, de concession en
concession, savent marcher vers la domination avec la persistance
que donne une idée fixe? Ou bien le maître avait-il contracté pour
son valet cette espèce d’affection qui naît de l’habitude, et semblable
à celle qu’un ouvrier a pour son outil créateur, que l’Arabe a pour
son coursier libérateur. Marguerite épia quelques faits pour se
décider, en se proposant de soustraire Balthazar à un joug humiliant,
s’il était réel. En passant à Paris, elle y resta durant quelques jours
pour y acquitter les dettes de son père, et prier les fabricants de
produits chimiques de ne rien envoyer à Douai sans l’avoir prévenue
à l’avance des demandes que leur ferait Claës. Elle obtint de son
père qu’il changeât de costume et reprît les habitudes de toilette
convenables à un homme de son rang. Cette restauration corporelle
rendit à Balthazar une sorte de dignité physique qui fut de bon
augure pour un changement d’idées. Bientôt sa fille, heureuse par
avance de toutes les surprises qui attendaient son père dans sa
propre maison, repartit pour Douai.
A trois lieues de cette ville, Balthazar trouva sa fille Félicie à
cheval, escortée par ses deux frères, par Emmanuel, par Pierquin et
par les intimes amis des trois familles. Le voyage avait
nécessairement distrait le chimiste de ses pensées habituelles,
l’aspect de la Flandre avait agi sur son cœur; aussi quand il aperçut
le joyeux cortége que lui formaient et sa famille et ses amis,
éprouva-t-il des émotions si vives que ses yeux devinrent humides,
sa voix trembla, ses paupières rougirent, et il embrassa si
passionnément ses enfants sans pouvoir les quitter, que les
spectateurs de cette scène furent émus aux larmes. Lorsqu’il revit sa
maison, il pâlit, sauta hors de la voiture de voyage avec l’agilité d’un
jeune homme, respira l’air de la cour avec délices, et se mit à
regarder les moindres détails avec un plaisir qui débordait dans ses
gestes; il se redressa, et sa physionomie redevint jeune. Quand il
entra dans le parloir, il eut des pleurs aux yeux en y voyant par
l’exactitude avec laquelle sa fille avait reproduit ses anciens
flambeaux d’argent vendus, que les désastres devaient être
entièrement réparés. Un déjeuner splendide était servi dans la salle
à manger, dont les dressoirs avaient été remplis de curiosités et
d’argenterie d’une valeur au moins égale à celle des pièces qui s’y
trouvaient jadis. Quoique ce repas de famille durât long-temps, il
suffit à peine aux récits que Balthazar exigeait de chacun de ses
enfants. La secousse imprimée à son moral par ce retour lui fit
épouser le bonheur de sa famille, et il s’en montra bien le père. Ses
manières reprirent leur ancienne noblesse. Dans le premier moment,
il fut tout à la jouissance de la possession, sans se demander
compte des moyens par lesquels il recouvrait tout ce qu’il avait
perdu. Sa joie fut donc entière et pleine. Le déjeuner fini, les quatre
enfants, le père et Pierquin le notaire passèrent dans le parloir où
Balthazar ne vit pas sans inquiétude des papiers timbrés qu’un clerc
avait apportés sur une table devant laquelle il se tenait, comme pour
assister son patron. Les enfants s’assirent, et Balthazar étonné resta
debout devant la cheminée.
—Ceci, dit Pierquin, est le compte de tutelle que rend monsieur
Claës à ses enfants. Quoique ce ne soit pas très-amusant, ajouta-t-il
en riant à la façon des notaires qui prennent assez généralement un
ton plaisant pour parler des affaires les plus sérieuses, il faut
absolument que vous l’écoutiez.
Quoique les circonstances justifiassent cette phrase, monsieur
Claës, à qui sa conscience rappelait le passé de sa vie, l’accepta
comme un reproche et fronça les sourcils. Le clerc commença la
lecture. L’étonnement de Balthazar alla croissant à mesure que cet
acte se déroulait. Il y était établi d’abord que la fortune de sa femme
montait, au moment du décès, à seize cent mille francs environ, et la
conclusion de cette reddition de compte fournissait clairement à
chacun de ses enfants une part entière, comme aurait pu la gérer un
bon et soigneux père de famille. Il en résultait que la maison était
libre de toute hypothèque, que Balthazar était chez lui, et que ses
biens ruraux étaient également dégagés. Lorsque les divers actes
furent signés, Pierquin présenta les quittances des sommes jadis
empruntées et les main-levées des inscriptions qui pesaient sur les
propriétés. En ce moment, Balthazar, qui recouvrait à la fois
l’honneur de l’homme, la vie du père, la considération du citoyen,
tomba dans un fauteuil; il chercha Marguerite qui par une de ces
sublimes délicatesses de femme s’était absentée pendant cette
lecture, afin de voir si toutes ses intentions avaient été bien remplies
pour la fête. Chacun des membres de la famille comprit la pensée du
vieillard au moment où ses yeux faiblement humides demandaient
sa fille que tous voyaient en ce moment par les yeux de l’âme,
comme un ange de force et de lumière. Lucien alla chercher
Marguerite. En entendant le pas de sa fille, Balthazar courut la serrer
dans ses bras.
—Mon père, lui dit-elle au pied de l’escalier où le vieillard la saisit
pour l’étreindre, je vous en supplie, ne diminuez en rien votre sainte
autorité. Remerciez-moi, devant toute la famille, d’avoir bien
accompli vos intentions, et soyez ainsi le seul auteur du bien qui a
pu se faire ici.
Balthazar leva les yeux au ciel, regarda sa fille, se croisa les
bras, et dit après une pause pendant laquelle son visage reprit une
expression que ses enfants ne lui avaient pas vue depuis dix ans:—
Que n’es-tu là, Pépita, pour admirer notre enfant! Il serra Marguerite
avec force, sans pouvoir prononcer une parole, et rentra.—Mes
enfants, dit-il avec cette noblesse de maintien qui en faisait autrefois
un des hommes les plus imposants, nous devons tous des
remercîments et de la reconnaissance à ma fille Marguerite, pour la
sagesse et le courage avec lesquels elle a rempli mes intentions,
exécuté mes plans, lorsque, trop absorbé par mes travaux, je lui ai
remis les rênes de notre administration domestique.
—Ah! maintenant, nous allons lire les contrats de mariage, dit
Pierquin en regardant l’heure. Mais ces actes-là ne me regardent
pas, attendu que la loi me défend d’instrumenter pour mes parents
et pour moi. Monsieur Raparlier l’oncle va venir.
En ce moment, les amis de la famille invités au dîner que l’on
donnait pour fêter le retour de monsieur Claës et célébrer la
signature des contrats, arrivèrent successivement, pendant que les
gens apportèrent les cadeaux de noces. L’assemblée s’augmenta
promptement et devint aussi imposante par la qualité des personnes
qu’elle était belle par la richesse des toilettes. Les trois familles qui
s’unissaient par le bonheur de leurs enfants avaient voulu rivaliser
de splendeur. En un moment, le parloir fut plein des gracieux
présents qui se font aux fiancés. L’or ruisselait et pétillait. Les étoffes
dépliées, les châles de cachemire, les colliers, les parures excitaient
une joie si vraie chez ceux qui les donnaient et chez celles qui les
recevaient, cette joie enfantine à demi se peignait si bien sur tous les
visages, que la valeur de ces présents magnifiques était oubliée par
les indifférents, assez souvent occupés à la calculer par curiosité.
Bientôt commença le cérémonial usité dans la famille Claës pour ces
solennités. Le père et la mère devaient seuls être assis, et les
assistants demeuraient debout devant eux à distance. A gauche du
parloir et du côté du jardin se placèrent Gabriel Claës et
mademoiselle Conyncks, auprès de qui se tinrent monsieur de Solis
et Marguerite, sa sœur et Pierquin. A quelques pas de ces trois
couples, Balthazar et Conyncks, les seuls de l’assemblée qui fussent
assis, prirent place chacun dans un fauteuil, près du notaire qui
remplaçait Pierquin. Jean était debout derrière son père. Une
vingtaine de femmes élégamment mises et quelques hommes, tous
choisis parmi les plus proches parents des Pierquin, des Conyncks
et des Claës, le maire de Douai qui devait marier les époux, les
douze témoins pris parmi les amis les plus dévoués des trois
familles, et dont faisait partie le premier président de la cour royale,
tous, jusqu’au curé de Saint-Pierre, restèrent debout en formant, du
côté de la cour, un cercle imposant. Cet hommage rendu par toute
cette assemblée à la paternité qui, dans cet instant, rayonnait d’une
majesté royale, imprimait à cette scène une couleur antique. Ce fut
le seul moment pendant lequel, depuis seize ans, Balthazar oublia la
recherche de l’Absolu. Monsieur Raparlier, le notaire, alla demander
à Marguerite et à sa sœur si toutes les personnes invitées à la
signature et au dîner qui devait la suivre étaient arrivées; et, sur leur
réponse affirmative, il revint prendre le contrat de mariage de
Marguerite et de monsieur de Solis, qui devait être lu le premier,
quand tout à coup la porte du parloir s’ouvrit, et Lemulquinier se
montra le visage flamboyant de joie.
—Monsieur, monsieur!
Balthazar jeta sur Marguerite un regard de désespoir, lui fit un
signe et l’emmena dans le jardin. Aussitôt le trouble se mit dans
l’assemblée.
—Je n’osais pas te le dire, mon enfant, dit le père à sa fille; mais
puisque tu as tant fait pour moi, tu me sauveras de ce dernier
malheur. Lemulquinier m’a prêté, pour une dernière expérience qui
n’a pas réussi, vingt mille francs, le fruit de ses économies. Le
malheureux vient sans doute me les redemander en apprenant que
je suis redevenu riche, donne-les-lui sur-le-champ. Ah! mon ange, tu
lui dois ton père, car lui seul me consolait dans mes désastres, lui
seul encore a foi en moi. Certes, sans lui je serais mort...
—Monsieur, monsieur, criait Lemulquinier.
—Eh! bien? dit Balthazar en se retournant.
—Un diamant!
Claës sauta dans le parloir en apercevant un diamant dans la
main de son valet de chambre qui lui dit tout bas:—Je suis allé au
laboratoire.
Le chimiste, qui avait tout oublié, jeta un regard sur le vieux
Flamand, et ce regard ne pouvait se traduire que par ces mots: «Tu
es allé le premier au laboratoire!»
—Et, dit le valet en continuant, j’ai trouvé ce diamant dans la
capsule qui communiquait avec cette pile que nous avions laissée
en train de faire des siennes, et elle en a fait, monsieur! ajouta-t-il en
montrant un diamant blanc de forme octaédrique dont l’éclat attirait
les regards étonnés de toute l’assemblée.
—Mes enfants, mes amis, dit Balthazar, pardonnez à mon vieux
serviteur, pardonnez-moi. Ceci va me rendre fou. Un hasard de sept
années a produit, sans moi, une découverte que je cherche depuis
seize ans. Comment? je n’en sais rien. Oui, j’avais laissé du sulfure
de carbone sous l’influence d’une pile de Volta dont l’action aurait dû
être surveillée tous les jours. Eh! bien, pendant mon absence, le
pouvoir de Dieu a éclaté dans mon laboratoire sans que j’aie pu
constater ses effets, progressifs, bien entendu! Cela n’est-il pas
affreux? Maudit exil! maudit hasard! Hélas! si j’avais épié cette
longue, cette lente, cette subite, je ne sais comment dire,
cristallisation, transformation, enfin ce miracle, eh! bien, mes enfants
seraient plus riches encore. Quoique ce ne soit pas la solution du
problème que je cherche, au moins les premiers rayons de ma gloire
auraient lui sur mon pays, et ce moment que nos affections
satisfaites rendent si ardent de bonheur serait encore échauffé par le
soleil de la Science.
Chacun gardait le silence devant cet homme. Les paroles sans
suite qui lui furent arrachées par la douleur furent trop vraies pour
n’être pas sublimes.
Tout à coup, Balthazar refoula son désespoir au fond de lui-
même, jeta sur l’assemblée un regard majestueux qui brilla dans les
âmes, prit le diamant, et l’offrit à Marguerite en s’écriant:—Il
t’appartient, mon ange. Puis il renvoya Lemulquinier par un geste, et
dit au notaire:—Continuons.
Ce mot excita dans l’assemblée le frissonnement que, dans
certains rôles, Talma causait aux masses attentives. Balthazar s’était
assis en se disant à voix basse: «Je ne dois être que père
aujourd’hui.» Marguerite entendit le mot, s’avança, saisit la main de
son père et la baisa respectueusement.
—Jamais homme n’a été si grand, dit Emmanuel quand sa
prétendue revint près de lui, jamais homme n’a été si puissant, tout
autre en deviendrait fou.
Les trois contrats lus et signés, chacun s’empressa de
questionner Balthazar sur la manière dont s’était formé ce diamant,
mais il ne pouvait rien répondre sur un accident si étrange. Il regarda
son grenier, et le montra par un geste de rage.
—Oui, la puissance effrayante due au mouvement de la matière
enflammée qui sans doute a fait les métaux, les diamants, dit-il, s’est
manifestée là pendant un moment, par hasard.
—Ce hasard est sans doute bien naturel, dit un de ces gens qui
veulent expliquer tout, le bonhomme aura oublié quelque diamant
véritable. C’est autant de sauvé sur ceux qu’il a brûlés.
—Oublions cela, dit Balthazar à ses amis, je vous prie de ne pas
m’en parler aujourd’hui.
Marguerite prit le bras de son père pour se rendre dans les
appartements de la maison de devant où l’attendait une somptueuse
fête. Quand il entra dans la galerie après tous ses hôtes, il la vit
meublée de tableaux et remplie de fleurs rares.
—Des tableaux, s’écria-t-il, des tableaux! et quelques-uns de nos
anciens!
Il s’arrêta, son front se rembrunit, il eut un moment de tristesse,
et sentit alors le poids de ses fautes en mesurant l’étendue de son
humiliation secrète.
—Tout cela est à vous, mon père, dit Marguerite en devinant les
sentiments qui agitaient l’âme de Balthazar.
—Ange que les esprits célestes doivent applaudir, s’écria-t-il,
combien de fois auras-tu donc donné la vie à ton père?
—Ne conservez plus aucun nuage sur votre front, ni la moindre
pensée triste dans votre cœur, répondit-elle, et vous m’aurez
récompensée au delà de mes espérances. Je viens de penser à
Lemulquinier, mon père chéri, le peu de mots que vous m’avez dits
de lui me le fait estimer, et, je l’avoue, j’avais mal jugé cet homme;
ne pensez plus à ce que vous lui devez, il restera près de vous
comme un humble ami. Emmanuel possède environ soixante mille
francs d’économie, nous les donnerons à Lemulquinier. Après vous
avoir si bien servi, cet homme doit être heureux le reste de ses jours.
Ne vous inquiétez pas de nous! Monsieur de Solis et moi, nous
aurons une vie calme et douce, une vie sans faste; nous pouvons
donc nous passer de cette somme jusqu’à ce que vous nous la
rendiez.
—Ah! ma fille, ne m’abandonne jamais! Sois toujours la
providence de ton père.
En entrant dans les appartements de réception, Balthazar les
trouva restaurés et meublés aussi magnifiquement qu’ils l’étaient
autrefois. Bientôt les convives se rendirent dans la grande salle à
manger du rez-de-chaussée par le grand escalier, sur chaque
marche duquel se trouvaient des arbres fleuris. Une argenterie
merveilleuse de façon, offerte par Gabriel à son père, séduisit les
regards autant qu’un luxe de table qui parut inouï aux principaux
habitants d’une ville où ce luxe est traditionnellement à la mode. Les
domestiques de monsieur Conyncks, ceux de Claës et de Pierquin
étaient là pour servir ce repas somptueux. En se voyant au milieu de
cette table couronnée de parents, d’amis et de figures sur lesquelles
éclatait une joie vive et sincère, Balthazar, derrière lequel se tenait
Lemulquinier, eut une émotion si pénétrante que chacun se tut,
comme on se tait devant les grandes joies ou les grandes douleurs.
—Chers enfants, s’écria-t-il, vous avez tué le veau gras pour le
retour du père prodigue.
Ce mot par lequel le savant se faisait justice, et qui empêcha
peut-être qu’on ne la lui fît plus sévère, fut prononcé si noblement
que chacun attendri essuya ses larmes; mais ce fut la dernière
expression de mélancolie, la joie prit insensiblement le caractère
bruyant et animé qui signale les fêtes de famille. Après le dîner, les
principaux habitants de la ville arrivèrent pour le bal qui s’ouvrit et
qui répondit à la splendeur classique de la maison Claës restaurée.
Les trois mariages se firent promptement et donnèrent lieu à des
fêtes, des bals, des repas qui entraînèrent pour plusieurs mois le
vieux Claës dans le tourbillon du monde. Son fils aîné alla s’établir à
la terre que possédait près de Cambray Conyncks, qui ne voulait
jamais se séparer de sa fille. Madame Pierquin dut également quitter
la maison paternelle, pour faire les honneurs de l’hôtel que Pierquin
avait fait bâtir, et où il voulait vivre noblement, car sa charge était
vendue, et son oncle Des Racquets venait de mourir en lui laissant
des trésors lentement économisés. Jean partit pour Paris, où il
devait achever son éducation.
Les Solis restèrent donc seuls près de leur père, qui leur
abandonna le quartier de derrière, en se logeant au second étage de
la maison de devant. Marguerite continua de veiller au bonheur
matériel de Balthazar, et fut aidée dans cette douce tâche par
Emmanuel. Cette noble fille reçut par les mains de l’amour la
couronne la plus enviée, celle que le bonheur tresse et dont l’éclat
est entretenu par la constance. En effet, jamais couple n’offrit mieux
l’image de cette félicité complète, avouée, pure, que toutes les
femmes caressent dans leurs rêves. L’union de ces deux êtres si
courageux dans les épreuves de la vie, et qui s’étaient si saintement
aimés, excita dans la ville une admiration respectueuse. Monsieur
de Solis, nommé depuis long-temps inspecteur-général de
l’Université, se démit de ses fonctions pour mieux jouir de son
bonheur, et rester à Douai où chacun rendait si bien hommage à ses
talents et à son caractère, que son nom était par avance promis au
scrutin des colléges électoraux, quand viendrait pour lui l’âge de la
députation. Marguerite, qui s’était montrée si forte dans l’adversité,
redevint dans le bonheur une femme douce et bonne. Claës resta
pendant cette année gravement préoccupé sans doute; mais, s’il fit
quelques expériences peu coûteuses et auxquelles ses revenus
suffisaient, il parut négliger son laboratoire. Marguerite, qui reprit les
anciennes habitudes de la maison Claës, donna tous les mois à son
père, une fête de famille à laquelle assistaient les Pierquin et les
Conyncks, et reçut la haute société de la ville à un jour de la
semaine où elle avait un Café qui devint l’un des plus célèbres.
Quoique souvent distrait, Claës assistait à toutes les assemblées, et
redevint si complaisamment homme du monde pour complaire à sa
fille aînée, que ses enfants purent croire qu’il avait renoncé à
chercher la solution de son problème. Trois ans se passèrent ainsi.
En 1828, un événement favorable à Emmanuel l’appela en
Espagne. Quoiqu’il y eût, entre les biens de la maison de Solis et lui,
trois branches nombreuses, la fièvre jaune, la vieillesse,
l’infécondité, tous les caprices de la fortune s’accordèrent pour
rendre Emmanuel l’héritier des titres et des riches substitutions de
sa maison, lui, le dernier. Par un de ces hasards qui ne sont
invraisemblables que dans les livres, la maison de Solis avait acquis
le comté de Nourho. Marguerite ne voulut pas se séparer de son
mari qui devait rester en Espagne aussi long-temps que le
voudraient ses affaires, elle fut d’ailleurs curieuse de voir le château
de Casa-Réal, où sa mère avait passé son enfance, et la ville de
Grenade, berceau patrimonial de la famille Solis. Elle partit, en
confiant l’administration de la maison au dévouement de Martha, de
Josette et de Lemulquinier qui avait l’habitude de la conduire.
Balthazar, à qui Marguerite avait proposé le voyage en Espagne, s’y
était refusé en alléguant son grand âge; mais plusieurs travaux
médités depuis long-temps, et qui devaient réaliser ses espérances,
furent la véritable raison de son refus.
Le comte et la comtesse de Soly Y Nourho restèrent en Espagne
plus long-temps qu’ils ne le voulurent, Marguerite y eut un enfant. Ils
se trouvaient au milieu de l’année 1830 à Cadix, où ils comptaient
s’embarquer pour revenir en France, par l’Italie; mais ils y reçurent
une lettre dans laquelle Félicie apprenait de tristes nouvelles à sa
sœur. En dix-huit mois leur père s’était complétement ruiné. Gabriel
et Pierquin étaient obligés de remettre à Lemulquinier une somme
mensuelle pour subvenir aux dépenses de la maison. Le vieux
domestique avait encore une fois sacrifié sa fortune à son maître.
Balthazar ne voulait recevoir personne, et n’admettait même pas ses
enfants chez lui. Josette et Martha étaient mortes. Le cocher, le
cuisinier et les autres gens avaient été successivement renvoyés.
Les chevaux et les équipages étaient vendus. Quoique Lemulquinier
gardât le plus profond secret sur les habitudes de son maître, il était
à croire que les mille francs donnés par mois par Gabriel Claës et
par Pierquin s’employaient en expériences. Le peu de provisions
que le valet de chambre achetait au marché faisait supposer que ces
deux vieillards se contentaient du strict nécessaire. Enfin, pour ne
pas laisser vendre la maison paternelle, Gabriel et Pierquin payaient
les intérêts des sommes que le vieillard avait empruntées, à leur
insu, sur cet immeuble. Aucun de ses enfants n’avait d’influence sur
ce vieillard, qui, à soixante-dix ans, déployait une énergie
extraordinaire pour arriver à faire toutes ses volontés, même les plus
absurdes. Marguerite pouvait peut-être seule reprendre l’empire
qu’elle avait jadis exercé sur Balthazar, et Félicie suppliait sa sœur
d’arriver promptement; elle craignait que son père n’eût signé
quelques lettres de change. Gabriel, Conyncks et Pierquin, effrayés
tous de la continuité d’une folie qui avait dévoré environ sept millions
sans résultat, étaient décidés à ne pas payer les dettes de monsieur
Claës. Cette lettre changea les dispositions du voyage de
Marguerite, qui prit le chemin le plus court pour gagner Douai. Ses
économies et sa nouvelle fortune lui permettaient bien d’éteindre
encore une fois les dettes de son père; mais elle voulait plus, elle
voulait obéir à sa mère en ne laissant pas descendre au tombeau
Balthazar déshonoré. Certes, elle seule pouvait exercer assez
d’ascendant sur ce vieillard pour l’empêcher de continuer son œuvre
de ruine, à un âge où l’on ne devait attendre aucun travail fructueux
de ses facultés affaiblies. Mais elle désirait le gouverner sans le
froisser, afin de ne pas imiter les enfants de Sophocle, au cas où son
père approcherait du but scientifique auquel il avait tant sacrifié.
Monsieur et madame de Solis atteignirent la Flandre vers les
derniers jours du mois de septembre 1831, et arrivèrent à Douai
dans la matinée. Marguerite se fit arrêter à sa maison de la rue de
Paris, et la trouva fermée. La sonnette fut violemment tirée sans que
personne répondît. Un marchand quitta le pas de sa boutique où
l’avait amené le fracas des voitures de monsieur de Solis et de sa
suite. Beaucoup de personnes étaient aux fenêtres pour jouir du
spectacle que leur offrait le retour d’un ménage aimé dans toute la
ville, et attirées aussi par cette curiosité vague qui s’attachait aux
événements que l’arrivée de Marguerite faisait préjuger dans la
maison Claës. Le marchand dit au valet de chambre du comte de
Solis que le vieux Claës était sorti depuis environ une heure. Sans
doute, monsieur Lemulquinier promenait son maître sur les
remparts. Marguerite envoya chercher un serrurier pour ouvrir la
porte, afin d’éviter la scène que lui préparait la résistance de son
père, si, comme le lui avait écrit Félicie, il se refusait à l’admettre
chez lui. Pendant ce temps, Emmanuel alla chercher le vieillard pour
lui annoncer l’arrivée de sa fille, tandis que son valet de chambre
courut prévenir monsieur et madame Pierquin. En un moment la
porte fut ouverte. Marguerite entra dans le parloir pour y faire mettre

You might also like