Pages

Xerces 3.1.1

I have to do some xml related job in C++, so I'm installing Apache Xerces-C 3.1.1 on my current test environment (Windows 7 - VC++ 2010).

Once you install xerces in [YOUR_XERCES_PATH], you have to settle a few values in your project property pages:

Among C/C++, General, Additional Include Directories: [YOUR_XERCES_PATH]\include
In Linker, General, Additional Library Directories: [YOUR_XERCES_PATH]\lib
In Linker, Input, Additional Dependencies: xerces-c_3.lib

And, xerces-c_3_1.dll should available to the application you are going to write. You could easily achieve this adding [YOUR_XERCES_PATH]\bin to your system PATH.

Once you have done all of this, you are ready for your first Xerces application, as reported by the minimal official Xerces C++ 3.1.1 Programming Guide.

It is the bit of code that any application designed to use Xerces has to implement, and it just initializes and terminates the Xerces system:
#include <iostream>
#include <xercesc/util/PlatformUtils.hpp>

XERCES_CPP_NAMESPACE_USE

int main(int argc, char* argv[])
{
   std::cout << "Initializing Xerces" << std::endl;
   try
   {
      XMLPlatformUtils::Initialize();
   }
   catch(const XMLException& toCatch)
   {
      std::cout << "Failure on Xerces: " << toCatch.getMessage() << std::endl;
      return 1;
   }

   // Do your actual work with Xerces-C++ here.

   std::cout << "Terminating Xerces" << std::endl;
   XMLPlatformUtils::Terminate();

   system("pause");
   return 0;
}

Go to the full post

CSS specific style for div id descendant

I give for known div, the useful block element used as a container of other elements, that helps us to give more structure to our HTML page.

Here the problem is that we want to specify the style for an element in a specific div in a page without affecting all the other elements of the same type.

We can do that giving a id to the div we want to customize, and specify the style for the element by the div id and the element type.

Say that all the h2 element in our page should be displayed in gray:
h2 { color: gray; }
But we want the h2 element in the "extra" div being blue.

Here is the HTML for that div:

<div id="extra">
<h2>Mocha Cafe Latte, €2.35</h2>
<p>Espresso, <em>steamed milk</em> and chocolate syrup.</p>
<blockquote class = "brown">
It is what you are looking for<br />
And when you find it<br />
You gonna love it<br />
</blockquote>
</div>

And here is how we specify in the CSS how we want this special effect:
#extra h2 { color: blue; }
Just the h2 included in the container having id "extra" would be affected.

A fun book for HTML beginners: Head First HTML. You will find a lot more details on div in its chapter eleven.

Go to the full post

CSS and id

We have seen how to use an element identified by its id attribute with JavaScript, we know how to use the elements identified by the class attribute with CSS. It shouldn't be strange to think that we can use the id as selector in CSS.

The reason to use id and not class should be self-evident: we have just one single element in our HTML page that we want to comply with a very specific style. For instance, we could use it for the page footer:
<p id="footer">Please steal this page, it isn't copyrighted in any way</p>
In the CSS we write:
#footer { color: red; }
We can be even more specific, and say that the style is defined for the footer attribute on a paragraph element:
p#footer { color: red; }

A fun book for HTML beginners: Head First HTML.

Go to the full post

CSS class

A style could be applied not only to a specific HTML tag, but also to a class. We can create a style for a couple tag/style or just for a class. In the last case all the tags referencing to that class would use that style.

To mark that a specific tag should conform to a specific style class, we set for it the attribute class with the required value. So, this paragraph would use the style defined for the green class:
<p class="green">A smooth, mild blend of coffees from Mexico, Bolivia and Guatemala.</p>
In the CSS file we define a style for a tag in this way:
p.green { color: green; }
We can define a class style that could be used by all tags:
.brown { color: brown; }
In this case we could use the brown style in each tag that supports the class attribute.

A fun book for HTML beginners: Head First HTML. If you are interested in CSS, go to chapter eight.

Go to the full post

CSS basics

In the previous post we had an informal introduction to CSS, now we are giving some more details.

Instead of putting the CSS in the HTML itself, we put it in a dedicated file. So we don't use anymore a style tag, but a link one, like this:
<link type="text/css" rel="stylesheet" href="ch08.css" />
In the href attribute we have a link to the actual file containing the style for the page.

We call "selector" the element to which we are applying a style in the current block, specified before the beginning of the block.

For instance if we write:

h1 {
color: gray;
}

In this context h1 is the selector, and we apply the color style to it.

We could specify more than a selector at time. So, if we want both h1 and h2 having color gray, we write:

h1, h2 {
color: gray;
}

We could have more sections for the same selector. For instance, if we want both h1 and h2 with the same color text (as above) but only h1 having a line below, we can add this section:

h1 {
border-bottom: 1px solid black;
}

A comment in CSS is written using the C-style convention, from slash-star to star-slash:

p {
/* background-color: red; */
color: blue;
border: 1px solid gray;
}

The "cascading" property of CSS is such that the style we specify for a more extern tag is applied to a contained tag, too, if no override is specified in the contained tag.

So, the style specified for body should be applied to all the document:

body {
font-family: sans-serif;
color: red;
}

But, given the previously written style for h1 and h2, in that case the text color would still be gray. And, given this:

em {
font-family: serif;
}

The emphasis is written using a serif font, and not a sans-serif, as specified by the body.

A fun book for HTML beginners: Head First HTML. If you are interested in CSS, go to chapter eight.

Go to the full post

CSS - Cascading Style Sheets

Head First HTML looks a good book to read if you want to have a fun introduction to HTML. Actually, I should consider myself too experienced for it, but I enjoy a lot the "Head First" style, so I'm reading it anyway.

Talking about style, the first real argument in the book, after a couple of dozen of pages, is CSS that stands for Cascading Style Sheets and provides a way to specify the style used of presenting our pages.

As usual, an example should help understanding the concept:

<html>
<head>
<title>Starbuzz Coffee</title>
<style type="text/css">
body {
background-color: brown;
margin-left: 25%;
margin-right: 25%;
border: 2px dotted black;
padding: 10px 10px 10px 10px;
font-family: serif;
}
</style>
</head>
<body>
<h1>Starbuzz Coffee Beverages</h1>
<h2>House Blend, €1.49</h2>
<p>A smooth, mild blend of coffees from Mexico, Bolivia and Guatemala.</p>
<h2>Mocha Cafe Latte, €2.35</h2>
<p>Espresso, steamed milk and chocolate syrup.</p>
<h2>Cappuccino, €1.89</h2>
<p>A mixture of espresso, steamed milk and foam.</p>
<h2>Chai Tea, €1.85</h2>
<p>A spicy drink made with black tea, spices, milk and honey.</p>
</body>
</html>

The only "strange" part in this HTML page is the style tag, in the document head.
In it we are specifying the style for the body. Best way to understand how to work is try the code, making a few changes. All the attributes should be self-explaining; a simple change we can do for the font-family is using sans-serif instead of serif.

I have some spare time, and I'm using it in quite a nerdy way, reading a book on HTML. But at least it is a fun book: Head First HTML.

Go to the full post

Self join

We have seen how to retrieve data from related tables using an inner join, but sometimes it makes sense even perform an inner join from a table to itself. This is what is usually called a self join.

Let's add another field to our contact table, it looks a bit strange at first view, because it is a foreign key referring to the primary key of the same table. In this case we call it ref_id because it identify the contact who acted as reference for him to be entered in the contact table itself:

alter table contact add(ref_id number(*,0));

alter table contact add constraint
ref_contact_fk foreign key(ref_id ) references contact(id);

Let's say that Jones has id 1 and no one referenced him: his ref_id would be 1. Smith, on the other side, was referenced by Jones, so his ref_id is Jones's - that is 1.

The self join select showing the contact last names and their reference's one is:

select c.last_name, c2.last_name as ref
from contact c
inner join contact c2
on c.ref_id = c2.id;

We are using two different aliases (c and c2) to refer to the same table in the two different roles, c as "left" table (borrowing the outer join terminology) and c2 as "right".

A fun basic book on SQL: Head First SQL.

Go to the full post

Outer join

An inner join select returns a row for each data coming from the two tables involved being connected by the "on" condition (or the "natural" PK -> FK relation).

If there a row in a table that has no relation with a row in the other table is simply skipped from the result.

If we actually want it in the result we use an OUTER JOIN. In this case the fields referring to the other table would report NULL as a value.

Let's add another contact to our table, this one with no job associated:
insert into contact values (3, 'Bill', 'Countless', NULL);


The inner join select we have written in the previous post would run giving the same result. If we want to see Bill last name, and a NULL as its job, we should use an outer join like this:

select c.last_name, j.description
from contact c
natural left outer join job j;

Being a LEFT outer join we have the data coming from the first table cited in the query (contact) and NULL for the missing data on the second one.

If we write the query the other way round, using job as first table, we get all the job descriptions and a NULL for the (eventually) missing relations:

select c.last_name, j.description
from job j
natural left outer join contact c;

We could achieve the same result keeping the tables in the same position and using a RIGHT outer join instead of a LEFT one:

select c.last_name, j.description
from contact c
natural right outer join job j;

The last two outer joins lead to the same result. It is a matter of taste using one style or the other.

A fun basic book on SQL: Head First SQL.

Go to the full post

Inner join

An inner join shows data coming from two tables connected using a comparison operator in a condition.

The generic syntax for an inner join is:

SELECT columns
FROM table1
INNER JOIN table2
ON condition;

Let's add a new column to our contact table, a foreign key to a brand new table, defining the main job of our contact.

This is how we created the job table:

create table job (
job_id number(*,0) not null,
description varchar2(20 byte) not null,
constraint job_pk primary key (job_id)
);

And here is the change we made in the contact table:

alter table contact add(job_id number(*,0));

alter table contact add constraint contact_job_fk foreign key(job_id)
references job(job_id);

We add a few job titles in the job table, and assign a job to each contact. Now we can use an inner join to see name and job for contacts:

select c.last_name, j.description
from contact c
inner join job j
on c.job_id = j.job_id;

This is called equijoin, since is based on an equality check. Sometimes we could be interested in a non-equijoin, that means, getting all the "wrong" cases. In our case, all the possible job our contacts are not associated to:

select c.last_name, j.description
from contact c
inner join job j
on c.job_id != j.job_id;

You may have noticed I gave name job_id to the primary key for the job table, and I used the same name for it as foreign key in the contact table.

This gives us a way of simplify a bit the notation for the inner join, since it id considered just natural using the relation between primary and foreign key with the same name, so natural that we call it a natural join:

select c.last_name, j.description
from contact c
natural join job j;

A fun basic book on SQL: Head First SQL.

Go to the full post

Cartesian join

A cartesian join - also knwon as cross product - is not very commonly used, at least intentionally. The fact is that it generates an awful huge quantity of data, and usually not with much sense in it.

A cartesian join of a n row table with with a m row table gives an n x m table. Any row in the first table is joined with any row in the second one.

When we really want to get a cartesian join, say we want display all the possible combination between the last names in the contact table with the interest descriptions, we write something like this:

select c.last_name, i.description
from contact c
cross join interest i;

Go to the full post

Many to many

In the previous post we created a relation one-to-many between two tables, and probably that was not the best solution, because this means that a contact could have as many interests as it wants (and this is ok) but an interest should be owned by just one contact.

A better one would be estabilish a many-to-many relation between them.

To implement a many-to-many relation we use a joining table, that stores the foreign keys for both tables.

So, we redesign the interest table in this way:

create table interest (
id number(*,0) not null,
description varchar2(20 byte) not null,
constraint interest_pk primary key (id)
);

And add a couple of items to it:

insert into interest (id, description)
values(1, 'trekking');

insert into interest (id, description)
values(2, 'reading');

Now this interests are not related with a specific contact (no FKs is in the table), but could be shared among many of them.

The joining table is:

create table contact_interest
(
contact_id number(*,0) not null,
interest_id number(*,0) not null,
constraint contact_fk foreign key (contact_id) references contact(id),
constraint interest_fk foreign key (interest_id) references interest(id)
);

No actual data in it, just FKs.

Adding trekking and reading to the number of the interests for the contact identified by id 1 is done in this way:

insert into contact_interest (contact_id, interest_id)
values(1, 1);

insert into contact_interest (contact_id, interest_id)
values(1, 2);

Having created the foreign key constraints, we can't "cheat". If we try to add an interest that is not in the table:

insert into contact_interest (contact_id, interest_id)
values(1, 99);

leads to an error.

A fun basic book on SQL: Head First SQL.

Go to the full post

Foreign key

We can put estabilish a relation between two different tables. As a connector, we use a field, the foreign key, that identifies the row from the first table referring to row in the second one.

As an example, think of a table defining contacts in this way:

create table contact (
id number(*,0) not null,
first_name varchar2(20 byte) not null,
last_name varchar2(20 byte) not null,
constraint contact_pk primary key(id)
);

We have a primary key, id, and a couple of data fields, first name and last name.

We want each contact having a undefined number of interests. To implement this requisite we create another table, interest, where we store each interest description in a row, and then we link it to the actual owner of the interest through a foreing key:

create table interest (
id number(*,0) not null,
description varchar2(20 byte) not null,
contact_id number(*,0) not null,
constraint interest_pk primary key (id),
constraint contact_fk foreign key (contact_id) references contact(id)
);

Say that we have inserted a contact like this:

insert into contact (id, first_name, last_name)
values(1, 'tom', 'jones');

We can create a couple of his interests in this way:

insert into interest (id, description, contact_id)
values(1, 'trekking', 1);

insert into interest (id, description, contact_id)
values(2, 'reading', 1);

We use interest.contact_id to estabilish a connection to contact.id.

A fun basic book on SQL: Head First SQL.

Go to the full post

Min, max and group by

Another variation on the same story. Now we want to identify the top salary and the bottom one for each department in our firm.

We spice the SQL statement a bit add the requirement to show in a dedicated column the gap between max and min salary, displaying as column name a short label, and ordering the report accordingly to the gap:

select department_id as dep, max(salary) - min(salary) as gap,
max(salary) as max, min(salary) as min
from employees
group by department_id
order by gap desc;

A fun basic book on SQL: Head First SQL.

Go to the full post

Avg and group by

Now we are interested in the average salary for the departments we have seen in the previous post.

We apply the ROUND() function to the result of AVG() to keep the result more readable. The rest of the statement is quite the same as the previous example.

To add a diversion, we show the result in ascending order, and we put the ASC modified esplicitely in the ORDER BY clause, even though that is not necessary, since ASC is the default:

select department_id, round(avg(salary))
from employees
group by department_id
order by avg(salary) asc;

If you want a fun introduction to SQL, consider reading Head First SQL.

Go to the full post

Sum and group by

If you have an Oracle database available, you should also have access to the hr test schema where are defined a few tables. Among them there is employees, that stores data that I'm about to use in this post.

We want to see how much is the salay costs for all the employees, grouped by the department they are working for.

This is a classical problem that could be solved easily using the SUM() function in conjunction with the GROUP BY clause in a SELECT statement.

We get the department id, the sum of all related employees salary and, to make this report more readable, we order it from the most wealthy department down to the poorest one:

select department_id, sum(salary)
from employees
GROUP BY department_id
order by sum(salary) desc;

If you want a fun introduction to SQL, consider reading Head First SQL. Actually, it uses MySQL, and not Oracle, as I'm doing currently. But this is not a big issue.

Go to the full post

Ordering data

It is a common request showing data in a table ordered accordingly to some requirement. We can achieve that using the ORDER BY directive applied to the SELECT command.

For instance, say that we want to get names and prices of all the pastries with a price less than 3, and we want them ordered by name:

select name, price
from pastry
where price < 3
order by name;

The order is implicitely ascending (ASC) meaning from A to Z, and to 0 to 9.
If we want it backward we can specify DESC (descending) in the ORDER clause.

All pastries name and price, ordered from the most expensive to the cheapest:

select name, price
from pastry
order by price desc;


I'm reading Head First SQL, a fun book good to have an introduction to SQL - based on MySQL implementation.

Go to the full post

Update with case-when

When we want to change a table so massively as shown in the previous post, we usually prefer to have a better control on the rows we are working with.

The case-when(-else) statement is what we are looking for.

Say that we want put as description for each row in the pastry table a different string accordingly with this rule:
All the names ending with "berry" should have a "With berries!" description.
All the other rows having a price less than 3 are a "Special offer".
Anything else would be a "A good choice".

This schema translates very well to this SQL statement:

update pastry
set description =
case
when substr(name,-5) = 'berry' then 'With berries!'
when price < 3 then 'Special offer'
else 'A good choice'
end;

The "else" is optional, if we don't have a default we could simply skip it.
Notice that the destination field is fixed, while I can vary the condition to select the row subset at my wish.

There is a fleeble connection between this post and Head First SQL, chapter six, because I wrote it while reading this fun book.

Go to the full post

A couple of string functions

Lot of the work in a database is about text management, so any good database makes available a good number of string function to help us in the job.

To extract a section of a string we could use substr() in this way:

select substr(name, 1, 2) from pastry;

select substr(name, -2) from pastry;

The first first call shows us the first two character of all the pastry names; the second one all the last two characters.

We can combine the result to another useful string function, upper(), to convert to uppercase the string passed, and we can use the result to populate another field in the table:

update pastry
set description = upper(substr(name, 1, 2));

Here we'll have in description just the first two characters of the name in the same table row.

Post written while having fun reading Head First SQL

Go to the full post

Table alterations

Instead of dropping an recreating a table we usually prefer a more conservative approach, altering the existing table, keeping the structure.

Here is how we want to add a column to the table:

alter table doughnut
add description varchar2(20);

We can even change the name of a table, maybe we want extend our business and doughnut is seen too limiting as a name, and we would like to rename the table pastry:

alter table doughnut
rename to pastry;

Or we could strip a column out of a table, if not used anymore:

alter table pastry
drop column created;

Post written while having fun reading Head First SQL

Go to the full post

Auto-incrementing Primary Key

Our doughnut table has a serious issue: we forgot to give it a primary key.

Luckily it contains just a small useless bunch of fake data, so we can happily dump it and rebuild from scratch.

Here is how to destroy (for good!) that table:
drop table doughnut;

Our new doughnut table will have a new shiny column named id that we plan to use as primary key. The issue is that Oracle does not provide the handy autoincrement attribute for a primary key that so many other database make available, so we emulate it, doing it by hand.

Firstly we create a sequence like this one:

create sequence seq_doughnut
increment by 1
start with 1;

Secondly we have to create a trigger, that basically is a function called by the database when an event is, how to say, triggered. This is not so intuitive like the sequence, but it is not too complex either:

create or replace trigger trg_doughnut
before insert on doughnut
for each row
begin
if :new.id is null then
select seq_doughnut.nextval into :new.id from dual;
end if;
end;

If no id is passed to the database by the insert statement, a value coming from the sequence is used.

Go to the full post

Update

We can change the values stored in our tables using the update command. As insert and delete, also update has to be confirmed with a commit, or could be canceled with a rollback.

Say that we want to change the price of the existing stock of blueberries:

update doughnut
price = 3.09
where name = 'Blueberry';

We asks to the database to set the price to a (new) value for all the rows having the specified name. If we don't use the "where" clause, we have the unpleasant (if not required) effect to change the price to all the items in the table.

We can change more than one field at once. Say that we want to reset price and stock for the blueberries:

update doughnut
set stock = 39, price = 3.19
where name = 'Blueberry';

If we want to increase the price of a fixed amount (say 0.20) to both blueberry and raspberry we can do it in one shot:

update doughnut
set price = price + 0.20
where name = 'Blueberry' or name = 'Raspberry';

Post written while having fun reading Head First SQL

Go to the full post

Delete from

Better testing the delete command on a safe environment, given that we are about to remove data. So I switch back to use my temp schema.

Actually, if you delete by mistake rows in a table you can restore the previous status through the rollback command. The deletion becomes irreversible only when you confirm it using the commit command.

In any case, as they say, better safe than sorry, so at least the first try on delete is better if given on a useless table.

Nothing is more useless here around than the doughnut table that I created in my test schema. Currently it has a few rows in it, some of them with the CREATED field set to NULL. I decided to remove them, so I execute this SQL command:
delete from doughnut where created is null;
I can now check the result of my job, for instance selecting all the rows left in the table:
select * from doughnut;
And if I'm happy of the result I commit the operation. Otherwise I can easily change my mind:
rollback;
Bad idea is calling delete without the where clause, 'cause that means "delete all rows in the table". And since the database should generate a way to rollback the operation, that could result in a very long time execution, if we are working on a big table. To perform such an operation is better firstly being really sure of what we are about to do, and secondly using the truncate command, that remove all the table's rows in a whiff (but no rollback available!).

Post written while having fun reading Head First SQL

Go to the full post

Advanced selecting

To play around with select in Oracle, there is nothing better than using the preset hr schema. There is a number of way we can access it through our test user. We could connect to the database using the hr user, or we could change the current_schema used by the current session, using this command:
alter session set current_schema = hr;
Or maybe we could use the qualified name for the table we want to access:
select * from hr.countries;

The american countries in the the countries database have region_id 2, so to select all of them we write this query:
select * from countries where region_id = 2;
The star (*) means "all the columns".

The american countries in the the countries database have region_id 2, so to select all of them we write this query:
select * from countries where region_id = 2;
The star (*) means "all the columns".

If we are not interested in seeing all the columns we could specify just the ones we want to see:
select country_name from countries where region_id = 2;
We can have a better selection ANDing more conditions:
select * from employees where department_id = 90 and salary > 20000;
And what if we'd like to select all the employees having first name starting with S? We could write something like that:
select * from employees where first_name > 'S' and first_name < 'T';
Actually, there is another way to get the same result, using the "like" keyword:
select * from employees where first_name like 'S%';
The percent means any number of any character. If we want just one 'jolly' character we use the underscore:
select * from countries where country_id like 'C_';
Another way to select a range of values is achieved using the between keyword:
select * from employees where first_name between 'S' and 'T';

We can also ORring different clauses:
select * from employees where department_id = 40 or department_id = 50;

A different approach is required to find the rows having a specific field set to NULL. If we are looking for the boss, we can get it knowing he has no manager, meaning his manager_id is NULL:
select * from employees where manager_id is null;

If we know the values we are looking for, instead of ORring all the conditions referring to them we can use the IN clause:
select * from employees where first_name in ('Steven', 'John');
Or we can select all the rows that are not in a set of values:
select * from employees where department_id not in (40, 50);

Post written while reading Head First SQL

Go to the full post

Variations on create

We have seen a basic usage of the SQL CREATE TABLE command. Now we see how to say that a field must be specified and how to specify a default value.

No field is mandatory in a table. If we don't specify it in a INSERT statement Oracle simpy put a NULL in it. If we want to force the caller to specify a value for a given field we could use the NOT NULL attribute. If we have a reasonable default for a field we can specify it using the DEFAULT attribute.

I'm not sure what is the sense in using NOT NULL and DEFAULT together, but we can do it. Just remember that, for Oracle, you should put first the DEFAULT attribute and then NOT NULL:

CREATE TABLE doughnut (
name VARCHAR2(10) NOT NULL,
price DEC(5,2) DEFAULT 2.99 NOT NULL,
stock INT,
created DATE
);

If we have a doughnut table created in this way and we try to insert a row in this way:

INSERT INTO doughnut (PRICE, STOCK, CREATED)
VALUES (2.99, 33, to_date('12-01-2007','dd-mm-yyyy'));

We get an error: cannot insert NULL.

Post written while reading Head First SQL

Go to the full post

A new database is born

I'm about to do some database testing using Oracle 10 on Windows 7. First step I do is creating a new user. Then I create a first table.

To create a user I refer to the Oracle home page page available through web browser. In the Administration section, Database Users, I select the Create User option.

I specify a lousy username (test) and an even lousier password (password) count on the fact that I'm going to put in a bunch of worthless data on a local database. For the same reason I'm not be picky in assigning priviledges to this use, I give it all of them. Not a good idea, usually.

In any case, I click on the Create button, and that's done. I have my test user ready to act.

To work on it, I use Oracle SQL Developer, I create a new Oracle connection, specifying user and password as just created.

When I open the newly created connection, a new working space window is opened. In there I could now create a table for the test user:

CREATE TABLE doughnut (
name VARCHAR2(10),
price DEC(5,2),
stock INT,
created DATE
);

In this way we are saying that DOUGHNUT is the name of a new table containing four fields:
NAME a string that can't be longer that 10;
PRICE is a floating point number, maximum five digits, two of them are are reserved for fractional side, so we can use not more that three digits for the integer side;
STOCK is a integer;
CREATE is a date.

To see what we actually have created we can ask to Oracle to describe the table:
desc doughnut;
If we are not happy anymore with a table, we can remove it for good using the drop command:
drop table doughnut;
We can insert an item in our table using the insert command:

INSERT INTO doughnut (NAME, PRICE, STOCK, CREATED)
VALUES ('Blueberry', 2.99, 33, to_date('12-01-2007','dd-mm-yyyy'));

We ask Oracle to insert into our table a new row. We specify the fields we want to set and then the values. Notice that the string is delimited by single quotes, and that we specify explicitely the date format, to avoid ambiguity.

Head First SQL is about SQL - as one could expect - but seen from the point of view of a MySQL user. I'm actually reading it just for fun (I know, I'm a bit on the nerdy side in these days) but I'm working with Oracle 10, and not with MySQL. That means I twist a bit the examples showed in the book to adapt them to the environment I'm using.

Go to the full post

Class method

We have seen that a method could be assigned to any instance of a given class, or could be put in the class prototype, and having the same behaviour: a full access to all the other properties and methods in the class.

But we can also define a method as class member. This method wouldn't see "this", so could be used only to access class properties and methods.

To create a new class method we simply create it at class level, like this:

BlogEntry.showSignature = function() {
alert(BlogEntry.prototype.signature);
}

More information on custom objects in chapter ten of Head First JavaScript.

Go to the full post

Extending standard classes

We have another change request of our toy blog manager. The user is happy with the signature we added at the end of each post, but he is not so happy with the format we are using to display the post date. He wants it to be showed in an his own specific format.

This is quite a nuisance 'cause we can't use a standard method but we have to create a brand new one. On the other side it is very easy to add a custom method to an existing class (even a standard one): it is just a matter of adding a new function to the prototype object of the class.

Here what we do for customizing Date:

Date.prototype.shortFormat = function() {
return this.getDate() + "/" + this.getMonth() + "/" + this.getFullYear();
}

Now we can call shortFormat() from any date objects in our code:

BlogEntry.prototype.toHTML = function() {
return "<b><i>(" + this.date.shortFormat() + ")</i> " + this.title +
"</b><br />" + this.body + "<br /><i>" + this.signature +"</i>";
}

More information on custom objects in chapter ten of Head First JavaScript.

Go to the full post

Class properties

We have just seen that makes sense putting the method definition in the prototype property of a class, and now it comes natural to us asking: and what about properties?

It could make sense too. But only if you really need that the same piece of information is shared among all the objects of that kind.

Let's say we want to show a signature at the end of each post in our simple blog. The signature should be the same for all the posts, so in this case it makes sense to have it defined as class property. Curiosly enough, even though a class property is not related with a single instance of the class, when we want to access it from a class method we have to qualify it by using "this". It is kind of obvious, though, if we think that it is actually stored in the prototype property, that is accessed as a normal property in a object.

In the coding of the class this resolves in adding the definition of the signature property and using it in the required methods:

BlogEntry.prototype.signature = "The blog owner";

BlogEntry.prototype.toHTML = function() {
return "<b><i>(" + this.date.toDateString() + ")</i> " + this.title +
"</b><br />" + this.body + "<br /><i>" + this.signature +"</i>";
}


More information on custom objects in chapter ten of Head First JavaScript.

Go to the full post

Assigning methods to prototype

We have implemented a simple JavaScript class defining a few methods in the constructor. There is a better way of doing it, using the prototype property.

Every class has its own property property, that is a sort of blueprint used to create a new object of that kind. So, instead of creating a different instance of the same method for each instantiated object, we can have a unique method for each instance of that class.

To get this result we rearrange the code in this way:

function BlogEntry(title, body, date) {
this.title = title;
this.body = body;
this.date = (typeof(date) == "undefined" || date == null) ? new Date() : date;
}

BlogEntry.prototype.toString = function() {
return this.title + " (" + this.date.toDateString() + "): " + this.body;
}

BlogEntry.prototype.toHTML = function() {
return "<b><i>(" + this.date.toDateString() + ")</i> " + this.title +
"</b><br />" + this.body;
}


More information on custom objects in chapter ten of Head First JavaScript.

Go to the full post

Random post

Our simple little blog manager is boring. We want to enjoy the thrill of reading a random post, and we can do it easily using a couple of mathematical methods made available to our JavaScript code by the Math class.

We are going to use Math.random(), that gives us a pseudo-random number in (0,1), and Math.floor() that truncates a number to the lower integer.

We add a button to the HTML code and make it call, as onclick reaction, this function:

function randomPost() {
var i = Math.floor(Math.random() * blog.length);
var element = resetBlog();
showPost(element, i, false);
}

Math.random() generates a number in (0,1), we multiply it for the number of items in the blog, and then we reduce it to an integer in [0, blog.length - 1] through Math.floor().

More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

Go to the full post

String searching

A common requirement for a blog is a way to search for the post having a specific text in it. A requirement that could be easily implemented considering that any string in JavaString is actually an instance of the class String, that offers a bunch of useful methods. Among them indexOf() that returns the index of the passed substring in the current string, if it is there, or -1.

First thing, let's change the HTML for our blog, adding a button and a text input element, so that the user could perform a search:

<input id="btnSearch" type="button" value="Search the blog" />
<input id="txtSearch" type="text"/>

In the script, we specify the onclick behaviour for the search button:
document.getElementById("btnSearch").onclick = searchBlog;
The search function is this:

function searchBlog() {
var element = resetBlog(); // 1.

var text = document.getElementById("txtSearch").value; // 2.
var found = false;
var yellow = false;

for(var i = 0; i < blog.length; ++i) { // 3.
if(blog[i].body.indexOf(text) != -1) { // 4.
showPost(element, i, yellow); // 5.
yellow = !yellow;
found = true;
}
}

if(!found)
showNoPost(element); // 6.
}

1. remove all elements previously in the blog section
2. get the searching text specified by the user
3. loop on all the blog items
4. call indexOf() on the current post body, looking for the search text
5. show the post - yellow is a boolean set alternatively to true and false, to alternate the text background
6. if no post has been found display a dummy element

The resetBlog() function was part of the already existing showBlog() function, I have extracted its functionality in a new function so that it could be used here too, without duplicating code:

function resetBlog() {
var element = document.getElementById("blog");

while(element.firstChild)
element.removeChild(element.firstChild);

return element;
}

The showPost() function has been redesigned to be more flexible, now the decision if the background color should be yellow is left to the caller:

function showPost(element, i, yellow) {
var newNode = document.createElement("p");
newNode.appendChild(document.createTextNode(""));
newNode.innerHTML = blog[i].toHTML();
if(yellow)
newNode.setAttribute("style", "background-color: yellow");
element.appendChild(newNode);
}

A dummy element is put as child of the passed element by this function:

function showNoPost(element) {
var newNode = document.createElement("p");
newNode.appendChild(document.createTextNode("No item selected"));
newNode.setAttribute("style", "background-color: orange");
element.appendChild(newNode);
}


More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

Go to the full post

Array sorting

Now that we have provided a date field to our blog, it strucks to us that maybe we should provide a way to keep it ordered.

This is very easy to be done, because the JavaScript Array class has a method sort() that is exactely what we want.

What we have to do is just call sort() on blog before using it:

window.onload = function(evt) {
blog.sort();
showBlog(2);
// ...

This way of sorting could be enough sometimes, but not in our case. We sorted the array using the standard comparison algorithm applied to the first field in the array. So we have our blog ordered alphabetically by post title.

Hardly what we usually expect.

To specify a different field and a different sorting comparison we pass a function to the sort() method. This function has to accept in input two parameters, the two array items that are about to be compared, and return an integer that should be:
  • less than zero if the first parameter should be before the second
  • zero if they are considered equal
  • greater than zero if the second parameter should be before the first
So here is a couple of function we can use to sort our blog by date:

// older first
function compare1(post1, post2) {
return post1.date - post2.date;
}

// newer first
function compare2(post1, post2) {
return post2.date - post1.date;
}

We use that functions calling sort() like this:
blog.sort(compare);
But can avoid creating a function that should be used just for one single call, and use a anonymous function. Here we choose to implement the "newer first" behaviour, that is the standard for blogs:
blog.sort(function(post1, post2) {return post2.date - post1.date;});

More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

Go to the full post

Dating a blog

The simple blog we create is so cute, that we decide give it a few improvements.

First of all, what's a blog without a date for each post? Managing dates it's a common task, so JavaScript provides a class for doing that, Date.

There are a few alternative constructors for a Date object: we can call the no-argument one creates a date for the moment we call it; or we can pass it year, month, day, ... all of them as integer (but remember: January is the month number 0, and December is 11), or we can pass the date as a string, in american format (month/day/year).

Once we have a Date object we can convert it in a readable string using a few method, toDateString() is one of them, providing a representation that is often what we are looking for.

Let's rewrite our BlogEntry class having a Date among its properties. We want preserve the existing code, so we are ready for the case the constructor is passed without specifying a date. In this case, from the point of view of the JavaScript interpreter, we say that the type of the passed date is undefined. For better robustness of our code we check also if the passed date is null, in both case we translate that as a user request to use the current date:

function BlogEntry(title, body, date) {
this.title = title;
this.body = body;
this.date = (typeof(date) == "undefined" || date == null) ? new Date() : date;

this.toString = function() {
return this.title + " (" + this.date.toDateString() + "): " + this.body;
}

this.toHTML = function() {
return "<b><i>(" + this.date.toDateString() + ")</i> " + this.title +
"</b><br />" + this.body;
}
}

Now we change our predefined blog entries:

var blog = [ new BlogEntry("Welcome", "Welcome to my new blog", new Date(2005, 11, 31)),
new BlogEntry("Last one", "Today's news"),
new BlogEntry("Again me!", "Many things to say", new Date("01/02/2006")),
new BlogEntry("Summertime", "I'm so <b>busy</b>!", new Date("07/15/2007")) ];

And we enjoy the view.

More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

Go to the full post

Class with JavaScript

JavaScript is (kind of weak) object oriented programming language. We can create our own classes, and use them to improve the readability of our code.

Here we'll write a simple blog manager based on a custom class, BlogEntry.

We will use it in an HTML page simple like this:

<h3>Welcome to My Blog</h3>
<div id="blog"></div>
<input id="btnShowAll" type="button" value="Show all entries" />

Just a div section, where we'll put our blog posts, and a button to show them all.

In the script section we specify the window onload behavior in this way:

window.onload = function(evt) {
showBlog(2);

document.getElementById("btnShowAll").onclick = function() {showBlog(blog.length);}
}

As the page is loaded, we call the showBlog() function to show a couple of items. And we associate to the button onclick property a call to the same showBlog() function, asking to show all the items in the blog. Before defining the function, and the blog itself, we need to define the BlogEntry class.

To define a JavaScript class we simply have to write its constructor, that carries the definition of the class properties and methods. So, here is our class, having title and body for a blog post, and a couple of methods to make them available as plain text, or in a fancy HTML format:

function BlogEntry(title, body) {
this.title = title;
this.body = body;

this.toString = function() {
return this.title + ": " + this.body;
}

this.toHTML = function() {
return "<b>" + this.title + "</b><br />" + this.body;
}
}

Given that, we define an array of a few blog entries:

var blog = [ new BlogEntry("Welcome", "Welcome to my new blog"),
new BlogEntry("Post 2", "Another <u>thrilling</u> post"),
new BlogEntry("Again me!", "Many things to say"),
new BlogEntry("Last one", "I am so busy with this blog!") ];

Now make sense writing the showBlog() function:

function showBlog(nr) {
const len = (nr < blog.length) ? nr : blog.length;
var element = document.getElementById("blog");

while(element.firstChild)
element.removeChild(element.firstChild);

for(var i = 0; i < len; ++i) {
showPost(element, i);
}
}

We don't trust the caller of our function so, instead of using the parameter nr, we use len, that is not bigger than the number of items in the blog array.

We get the blog element from the HTML page, we remove all its children (to avoid double insertions) and then we call the showPost() to put in all the required items:

function showPost(element, i) {
var newNode = document.createElement("p");
newNode.appendChild(document.createTextNode(""));
newNode.innerHTML = blog[i].toHTML();
if(i%2 == 0)
newNode.setAttribute("style", "background-color: yellow");
element.appendChild(newNode);
}

We append as a child to the passed element a new node, a "p" element in which we put as innerHTML the string returned by toHTML() called on the i element of the array blog. If we were not interested in fancy HTML formatting, we could have avoided using innerHTML (so practical but non-standard) and putting the result from a call to BlogEntry.toString() directly in the createTextNode() call.

To embellish a bit our page, we se the background color for alternate items in the blog, making it more readable.

More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

Go to the full post

Making history

If we can change text in a element, we also can add a completely new node in the DOM structure of a page.

We can use this feature to dinamically change the content of our HTML page to show live the decisions we are taking.

In our HTML we add a couple of buttons, as a way to take decisions:

<p>
<input type="button" id="btnLeft" value="Left" onclick="cmdButton(true)" />
<input type="button" id="btnRight" value="Right" onclick="cmdButton(false)" />
</p>

At bottom page we add a div section, where we are going to put the decisions history:

<div id="history">
</div>

In the script tag we add a variable definition, to keep track of the current step:
var currentStep = 0;
Then we define the function called to react to the buttons onclick event - currently it doesn't do much, just increasing the current step and calling a function that add a new entry in the history section:

function cmdButton(left) {
++currentStep;
setHistory(left);
}

And finally here is the real point of interest of this post. In setHistory() we get the node where we keep the history, create a new "p" element, adding to it a new text child, containing the information that we want to store, and then appending the "p" element to the history:

function setHistory(left) {
var history = document.getElementById("history");
var newNode = document.createElement("p");
var newText = document.createTextNode("Decision " + currentStep +
": you clicked " + (left ? "left" : "right"));
newNode.appendChild(newText);
history.appendChild(newNode);
}

More details on DOM in chapter eight of Head First JavaScript.

Go to the full post

Using a DOM approach instead of innerHTML

We have already seen how to modify the text (actually, an HTML fragment) included in an element accessing its innerHTML property.

The issue is that innerHTML is not a standard property, so we shouldn't actually rely on it. Expecially if we consider that we cand do the same considering the element as a node in the document, accordingly to the DOM (Document Object Model), and accessing its included text as its child.

To see this approach in action let's build an HTML page containing an image and its caption. We want our JavaScript being able to initialize and change the actual picture and text, so we put just the structure in the HTML code, and leave to the script the fun of assigning the content:

<body>
<div style="margin-top: 100px; text-align: center;">
<p><img id="sceneImg" alt="" src=""></p>
<div id="sceneTxt"></div>
</div>
</body>

We initialize the HTML from the script assiging an anonymous callback function to window.onload. Here we see what we were used to do, using innerHTML:

window.onload = function(evt) {
document.getElementById("sceneImg").alt = "The first scene image";
document.getElementById("sceneImg").src = "scene1.png";
document.getElementById("sceneTxt").innerHTML = "This is the first scene";
}

The same result of calling the third line could be achieved removing all the children from the node "sceneTxt" and assigning to it a new text node containing the requested string. To keep the code simpler, we could use a short function like this:

function setTextElement(elemId, newTest) {
var node = document.getElementById(elemId);
while(node.firstChild)
node.removeChild(node.firstChild);
node.appendChild(document.createTextNode("This is the first scene"))
}

That would be called from the anonymous function in this way:
setTextElement("sceneTxt", "This is the first scene");

More details on DOM in chapter eight of Head First JavaScript.

Go to the full post

Regular expressions with JavaScript

We could build by hand complex validation functions for our JavaScript code, but it is not a good idea. We should use instead the regular expession tool that is part of the JavaScript engine, that is close enough to other popular regex engines, like the Perl one.

In JavaScript, a regular expression is an object of a specific class (RegExp) that is created in a specific way. For instance, here is a regular expression that defines a ZIP code respecting the rule "a string of exactely 5 digit":
var pattern = /^\d{5}$/
A regular expression is delimited by two slashes. So, if we want to put a slash in a regular expression we need to escape it with a backslash.

The first character in our first regex is a "^" that stands as a marker for the beginning of the string, then we have a "\d", meaning a digit, than a specifier "{5}" that tells us that the regex is expecting 5 items just specified, i.e. five digits, and finally a "$", marker for the end of the string.

Reading all together this means: we are expecting a string described from the beginning to the end by exactely 5 digits.

To start using regular expression in JavaScript you should have a grasp on a few metacharacters:
  • . = any character but a newline
  • \d = any digit
  • \w = any alphanumeric character
  • \s = any whitespace (blank, tab, return, newline)
  • ^ = marker to the beginning of text
  • $ = marker to the end of text
  • * = preceding subpattern appears 0+ times
  • + = preceding subpattern appears 1+ times
  • ? = preceding subpattern appears 0 or 1 time
  • {n} = preceding subpattern appears exactely n times
  • () = delimiter for a subpattern

Once we create a regex, it is easy to check if a string comply to its request, we just call the method test() on the regex passing the string to be tested as parameter. Here is a function we can use to validate our text inputs:

function patternCheck(fldInput, regex, fldHelp) {

if(!regex.test(fldInput.value)) {
if(fldHelp != null) {
fldHelp.innerHTML = "Should match the pattern: " + regex.source;
return;
}
}
else {
if(fldHelp != null)
fldHelp.innerHTML = "";
}
}

In the source property of the regex we have access to the regular expression as a string, we display it to the user as an hint for the reason why we didn't accept his input - hoping this is not gibberish to him.

This is the HTML block that would display a text input for a ZIP:

<p>ZIP code:
<input id="zipId" name="zip" type="text" size="5"
onblur="patternCheck(this, /^\d{5}$/, document.getElementById('zipHlp'))" />
<i><span id="zipHlp"></span></i></p>

If we want to specify a valid range for the number of elements that should be in a regular expression, we can use the construct {min,max}, meaning that there should be at least "min" elements, and at the most "max" of them.

So we can rewrite the text input we should accept 3-12 character string in this way:

<p>Your input:
<input id="msgId" name="message" type="text" size="10"
onblur="patternCheck(this, /^\w{3,12}$/, document.getElementById('msgHlp'))" />
<i><span id="msgHlp"></span></i></p>

We can offer a limited option to the user, using the "|" operator. Here is how we permit to input just "blue" or "red":

<p>Color:
<input id="colorId" name="color" type="text" size="10"
onblur="patternCheck(this, /^(blue|red)$/, document.getElementById('colorHlp'))" />
<i><span id="colorHlp"></span></i></p>


More details on regular expression in chapter seven of Head First JavaScript.

Go to the full post

Changing the innerHTML

Popping up windows is not considered a good way of user interaction. Often is better to think of another way, less intrusive, to communicate.

With JavaScript we can modify the text in a HTML element, changing in this way the actual page, changing the content of its innerHTML property.

Let's use this capability to improve the input text validation example.

We change the HTML adding a "span" element, initially empty, just after our text input.
We change the validation function, too, to accept in input both the text input and the related span element:

<form name="order" action="notImplemented" method="POST">
<p>Your input:
<input id="msgId" name="message" type="text" size="40"
onblur="basicCheck(this, document.getElementById('msgHlp'))" />
<i><span id="msgHlp"></span></i></p>
<input type="button" value="Do it" onclick="doSomething(this.form);" />
</form>

The idea is that we are going to put a message in the "span" element, if the text input is not valid.

We change the validation function in this way:

function basicCheck(fldInput, fldHelp) {
if(fldInput.value.length == 0) {
if(fldHelp != null)
fldHelp.innerHTML = "Please enter a value";
fldInput.focus();
}
else {
// ensure no help message is showed when not required
if(fldHelp != null)
fldHelp.innerHTML = "";
}
}

If a fldHelp is specified, and if the string in fldInput is empty, the fldHelp text is set to a helper text.

More details on this stuff in chapter seven of Head First JavaScript.

Go to the full post

Validation: accessing a field in a form

We want to ensure that a text input we put in a HTML form is not empty. To do that we have to associate a function to the event handler onblur (meaning: we are leaving the element), and we should pass the element itself to the checking function.

We have a really this simple form:

<form name="order" action="notImplemented" method="POST">
<input id="msgId" name="message" type="text" size="40" onblur="basicCheck(this)" />
<input type="button" value="Do it" onclick="doSomething(this.form);" />
</form>

When we leave the text input, an onblur event is generated, and so the function basicCheck() is called.
The parameter "this" is a reference to the element that was in control, so, the text input itself.

Here is how we check the text input value:

function basicCheck(inputField) {
if(inputField.value.length == 0) {
alert("Please enter a value");
inputField.focus();
}
}

In the parameter inputField we have the "this" referring to the text input. In its "value" property we have the string input by the user. In "length" is stored is actual length, so we check it against zero.

In case of empty text, we issue an alert, reset the focus on the "bad" input, and return the control to the user.

As a bonus, in this post we have a look to the onclick for the button in our minimal form. A function is called passing the form associated with the button itself, meaning, the form that contains the button (and incidentally, the text input too).

The idea is that in this way we have an easy access to the element in the form from the function:

function doSomething(form) {
alert("You wanted to do something with: " + form["message"].value);
alert("But you can't do anything here with: " + form.message.value);
}

Not a big function, but it shows us how we can access the elements in a form. We can use the array notation, (form["message"].value), or the "dot" notation, form.message.value, for getting absolutely the same result.

More details on this stuff in chapter seven of Head First JavaScript.

Go to the full post

Callback with JavaScript

We are about to see a way to get a better separation between our JavaScript code from the HTML body.

Instead of relying on the onXXX tag attributes, we can access the even handlers from the inside of the script tag, leaving the HTML body cleaner and easier to maintain.

To do that we use the callback mechanism, that require us to manage the function address as a variable. Good news is that it quite easy to be done with JavaScript.

The basic fact is that we can see onload, that we have previously accessed as attribute of the body tag, as property of the JavaScript object "window". So we can actually use it to react on the event signalling the page has been completely loaded.

The twist is that we should put in it not a string but the address of a function that we want to be called. Luckly that is pretty easy to be done in JavaScript: just remove the brackets. So, if we had that:
<body onload="greet()"><!-- ... --->
In a script tag, we can write this:
window.onload = greet;

Actually, there is another thing. The event handler expects to be given the address of a function that accept one parameter, a so called object event. But JavaScript is a very permessive language, and there is no complain for passing something different. In any case, to avoid misunderstanding, it would be better to explicitely show that parameter in the definition of the called function, even if it is not used:

function greet(evt) {
// ...
}

It is handy sometimes using an anonymous function. Obviously this makes sense only for a function that has to be used once, like could be one that is used as callback for an event handler. And actually is typical to a piece of code like this:

window.onload = function(evt) {
// ...
}

Here the anonymous function, accepting in input an object event, represents the code that would be called as callback when the page is loaded. At that moment the JavaScript code has access to the elements defined in the page body.

So, we put inside this function all the connection between the HTML and the JavaScript. In a way, this is a sort of constructor for the script.

For instance, let's say that we have this element in the HTML body:

<div style="margin-top:100px; text-align:center">
<img id="rock" src="image1.png" alt="Bored" style="cursor:pointer" />
</div>

And we want that clicking on that element would result calling:

function comment(index) {
alert("You are accessing item " + index);
}

passing as index 42.

Instead of using the HTML attribute onclick in the element tag, we could write our onload callback function in this way:

window.onload = function(evt) {
document.getElementById("rock").onclick = function(evt) { comment(42); };
}


More on JavaScript functions in chapter six of Head First JavaScript.

Go to the full post

Cookies in action

We can use the cookie functions we have just written to improve again our interactive page giving it a way of remembering the user name, so to use it even when the user return to the page after a while.

First thing, we store the utility function in a text file in the same directory of our HTML page. The usual extension for JavaScript is js, so we call it "cookie.js". Then to include it in the HTML page we use this directive:
<script type="text/javascript" src="cookie.js"></script>

Now we modify the existing code, in the already existing script tag. First step is adding a constant, to define the name of the cookie we are about to use:

<script type="text/javascript">
var userName;
const COOKIE_NAME = "name";

<!-- ... -->

The navigator.cookieEnabled flag tells us if we have it available. Only if it is true we can work with them. So, we modify the greet() function to read the user name stored in the cookie (when possible), if have a name we use it to greet the user, otherwise to use a anonymous way to greeting him:

function greet() {
if(navigator.cookieEnabled)
userName = readCookie(COOKIE_NAME);

if(userName) {
alert("Hello " + userName + ", I missed you.");
setHappy(true);
}
else
alert("Hello from a whimsical page!");
}

Then we rewrite the touchMe() function, moving the input request in the getName() function:

function getName() {
userName = prompt("What is your name?", "Enter your name here.");
if (userName) {
alert("Nice meeting you, " + userName + ".");
if(navigator.cookieEnabled)
writeCookie(COOKIE_NAME, userName, 30);
else
alert("Cookie not enabled - I won't remember you for long.");
}
}

function touchMe() {
if (userName)
alert("I like the attention, " + userName + ". Thank you.");
else
getName();

setHappy(true);
}


More on JavaScript cookies in chapter three of Head First JavaScript.

Go to the full post

Persistence by cookies

We can't access the secondary store on the local machine with JavaScript, with the exception of cookies. So, we use a cookie to store basic information for a page.

A cookie is identified by a unique name, it is used to store a value, and it has an expiration date. All the cookies are stored in a string associated to the current web page, that makes them a bit wierd to manage. So it is customary to write a tiny library of JavaScript functions to keep easy the user code.

Here is how we are going to save a cookie:

function writeCookie(name, value, secs) {
// by default the cookie is temporary
var expires = "";

// cookie persistent for the passed number of seconds
if(secs) {
var date = new Date();
date.setTime(date.getTime() + secs * 1000);
expires = "; expires=" + date.toGMTString();
}

// set the cookie to the name, value, and expiration date
document.cookie = name + "=" + value + expires + "; path=/";
}

Normally, it would be more useful if the third parameter of writeCookie() was the number of days. But for testing purposes it is handy having a cookie that expires in a few seconds.

Once a cookie is stored, we should retrieve it:

function readCookie(name) {
var searchName = name + "=";
var cookies = document.cookie.split(';');
for(var i=0; i < cookies.length; i++) {
var c = cookies[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(searchName) == 0)
return c.substring(searchName.length, c.length);
}
return null;
}

As we said, the code is a bit involute. We split document.cookie in an array of cookies, using semicolon (";") as delimiter. [This is cool, but it leads to the inconvenience that we can't store semicolon in our cookie!]
Then we loop on all the cookies, we skip all the trailing blanks, and check for the key, if we find it then we return the substring starting just after the equal sign to the end of the current cookie.

To erase a cookie we just change it assigning a negative value as expiration:

function eraseCookie(name) {
writeCookie(name, "", -1);
}


More on JavaScript cookies in chapter three of Head First JavaScript.

Go to the full post

Size matters

We have showed a picture to the user. The issue now is that we have no idea of the client window size, that means our picture could be look to the user ridiculy small, or too huge to be seen completely.

So we should rescale the image, and we can do that changing the height (part of the style attribute) for our image, referring to the clientHeight of the document body.

We create a function to do this job:

function resizeMe() {
document.getElementById("rock").style.height =
(document.body.clientHeight - 100) * 0.9;
}

We want call this function as soon as the page is loaded, so we put it in the onload attribute of the body tag:

<body onload="resizeMe(); greet();">
<!-- ... -->
</body>

It is worth noting that it is possible to insert code snippet as argument for the onload attribute, and not just the name of a function.

The attribute onload is the event handler called when the page is loaded for the first time, or reloaded by the user (clicking on F5, for instance). But what we can do to resize our image when the user resize the browser window? Easy solution: we use the onresize attribute:

<body onload="resizeMe(); greet();" onresize="resizeMe()">
<!-- ... -->
</body>

But beware: even if onresize is widely used, it is not (yet) a standard attribute. It should be part of HTML5.

Based on an example found in chapter three of Head First JavaScript, a good book for a new starter.

Go to the full post

Timeout rocks!

We can execute a JavaScript function after a specified delay using setTimeout(). If we want to run a function many times say, any 15 seconds, we can use setInterval().

Here we'll see how to use setTimeout() - setInterval() is quite the same, just remember that to stop it calling the associated function we could call clearInterval() - in an example that is meant to be an extension of the already seen basic JavaScript example.

The point of the code is that when we click on the picture, it is changed with a second one, but the new one shift automatically back to the default after a while (specified in millisecs):

<html>
<head>
<title>A whimsical page</title>

<script type="text/javascript">
var userName;

function greet() {
alert("Hello from a whimsical page!");
}

function setHappy(happy) {
var element = document.getElementById('rock');

if(happy) {
element.src = "image2.png";
element.alt = "Happy";
}
else {
element.src = "image1.png";
element.alt = "Bored";
}
}

function touchMe() {
if (userName) {
alert("I like the attention, " + userName + ". Thank you.");
}
else {
userName = prompt("What is your name?", "Enter your name here.");
if (userName)
alert("Nice meeting you, " + userName + ".");
}

setHappy(true);

setTimeout("setHappy(false)", 3000);
}
</script>
</head>

<body onload="greet()">
<div style="margin-top:100px; text-align:center">
<img id="rock" src="image1.png" alt="Bored" style="cursor:pointer" onclick="touchMe()" />
</div>
</body>
</html>


Post based on an example found in chapter three of Head First JavaScript, you should read it too, if you want more details, and some fun, too.

Go to the full post

Dozens of donuts

Another improvement to the Donut Manager we have wrote is about accepting donuts by dozens. Besides, we check also that the user won't input negative numbers as order.

To do that we will use the indexOf() method for a string, that returns the index where starts the specified substring in the current string. If there is no such a substring, -1 is returned.

We want to write a parseDonuts() JavaScript custom function that we would call in the update() to extract the number of donuts as input by the user, in this way:

var cDonuts = parseDonuts(document.getElementById("cdonuts"));
var gDonuts = parseDonuts(document.getElementById("gdonuts"));

If we have a "bad" value in the element, we reset the text to empty string. If we find "dozen" in the text we multiply the value by 12, and we write the actual value in the text:

function parseDonuts(text) {
var nrDonuts = parseInt(text.value);
if(isNaN(nrDonuts) || nrDonuts < 1) {
text.value = "";
return 0;
}
else if(text.value.indexOf("dozen") != -1) {
nrDonuts *= 12;
text.value = nrDonuts;
}
return nrDonuts;
}


Post written while reading chapter two of Head First JavaScript, a good book if you know nothing about JavaScript and not much about programming.

Go to the full post

Data validation for donuts

The JavaScript we wrote in the previous post is really basic. Let's improve it a bit adding some data validation.

We rewrite the placeOrder() function, to check any required field. So, name should not be empty, pickup should be a number, and the sum of the requested donuts should be greater than zero.

If we detect some non numeric data in a field that is expected to be numeric, we reset it to empty string:

function placeOrder(form) {

if(document.getElementById("name").value == "") {
alert("Your name is mandatory!");
return;
}

var pickup = document.getElementById("pickup");
if(pickup.value == "" || isNaN(pickup.value)) {
alert("Please, specify the pickup time");
pickup.value = "";
return;
}

var cDonuts = parseInt(document.getElementById("cdonuts").value);
if(isNaN(cDonuts)) {
cDonuts = 0;
document.getElementById("cdonuts").value = "";
}
var gDonuts = parseInt(document.getElementById("gdonuts").value);
if(isNaN(gDonuts)) {
gDonuts = 0;
document.getElementById("gdonuts").value = "";
}
if(cDonuts + gDonuts == 0) {
alert("Please, order at least one donut!");
return;
}

// Submit the order to the server
alert("Not implemented yet!");
//form.submit();
}


Post written while reading chapter two of Head First JavaScript, a good book if you know nothing about JavaScript and not much about programming. A bit too slow otherwise.

Go to the full post

Donut Manager

A simple JavaScript application to see the language in action. You can have a first approach to constants, variables, conversion from string to integer, the meaning of NaN, and how to specify the number of decimals for a floating point value.

Lot of stuff in a handful of lines.

To define a constant value in JavaScript we use the keyword const, it is costumary to give an all-uppercase name to a constant - C-style tradition.

A variable is introduced by the keyword var, notice that we let JavaScript deduce the type of the variable by the context.

To force the variable value to a specific type we should use standard JavaScript functions. For instance, converting a string to an integer value is done by parseInt().

We we try to get a number from a variable that does not contain such a value, we get a predefined constant, NaN (Not a Number). To check if a variable for NaN we use the isNaN() function.

Given a variable containing a number value, we can use the toFixed() method that we can call on the variable itself.

Let see how to use these concepts in an HTML page:

<html>
<head>
<title>Duncan's Just-In-Time Donuts</title>

<script type="text/javascript">
function update() {
const TAXRATE = 0.0925;
const PRICE = 0.50;

var cDonuts = parseInt(document.getElementById("cdonuts").value);
var gDonuts = parseInt(document.getElementById("gdonuts").value);

// avoid NaN
if(isNaN(cDonuts))
cDonuts = 0;
if(isNaN(gDonuts))
gDonuts = 0;

var subTotal = (cDonuts + gDonuts) * PRICE;
var tax = subTotal * TAXRATE;
var total = subTotal + tax;

document.getElementById("sub").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}

function placeOrder(form) {
// Submit the order to the server
alert("Not implemented yet!");
//form.submit();
}
</script>
</head>

<body>
<h2>Duncan's Just-In-Time Donuts</h2>
<p><i>All donuts 50 cents each, cake or glazed!</i></p>
<form name="orderform" action="donuts.php" method="POST">
<p>Your name: <input type="text" id="name" value="" /></p>
<p>C donuts #:<input type="text" id="cdonuts" onchange="update()" /></p>
<p>G donuts #:<input type="text" id="gdonuts" onchange="update()" /></p>
<p>Ext. pickup: <input type="text" id="pickup" /> minutes</p>
<br />
<p><input type="text" id="sub" readonly="readonly" /> Subtotal</p>
<p><input type="text" id="tax" readonly="readonly" /> Tax</p>
<p><input type="text" id="total" readonly="readonly" /> Total</p>
<p><input type="button" value="Place Order" onclick="placeOrder(this.form);" /></p>
</form>
</body>
</html>


Post written while reading chapter two of Head First JavaScript, a fun book to read.

Go to the full post

Hello JavaScript

We are about to write a few JavaScript lines, just to see the point of using this language.

We'll how to write a JavaScript function, and how to call JavaScript function reacting to events happening on our HTML page.

To do that, we create a simple page displaying an image, spicing it up adding a few requisites:
  • we want to cheer the user with a popup message anytime the page is loaded (quite unnerving, in the long run);
  • anytime he clicks on the picture we ask him his name, so to politely say again hello to him personally, besides, we change picture and its alternate text.
Here is the page, below a few notes on it:

<html>
<head>
<title>A friendly page</title>
<script type="text/javascript">
function feedBack() {
var name = prompt("What's your name?", "Enter your name here");
if(name) {
alert("Nice meeting you, " + name + "!");
document.getElementById("img").src = "image2.png";
document.getElementById("img").alt = "another image";
}
}
</script>
</head>
<body onload="alert('Hello from a friendly page!')">
<img id="img" src="image1.png" alt="an image" style="cursor:pointer"
onclick="feedBack()" />
</body>
</html>

The script tag is used to include the code in an HTML page. Its type attribute specify the language - text/javascript in our case. Typically, we put the script section in the HTML tag - just a convention.

The function keyword marks a JavaScript function, and var is used for identifying a variable.

The standard prompt() function popups a window with the passed title and label for the input line showed to the user. The text entered is returned to the caller, if no text is entered, a null is returned.

The standard alert() function popups a window with the specified message in it.

We can access elements in the HTML page in a number of way. Here we see how to call the function getElementById() on the document to get the element with the specified id. Once we have the element, we can access its properties.

The onload event handler, used in the body tag, let us react to the complete loading of the page.

We specifiy the id of the image, so that we have a easy way to retrieve it from our custom JavaScript function.

The attribute style here is used to make the cursor shape change when we hover over it.

The onclick event handler, specified for an element in the body, let us a way to react to the user click on it.

To refresh my JavaScript I'm reading Head First JavaScript, a fun book I suggest you, if you want to do the same. I wrote this post as a comprehension exercise on its chapter one.

Go to the full post

Cooperating Tags

This post has been moved to Biting Code, my blog dedicated to JVM languages.It shows how to write Simple Tags that work together in a JSP page.

Go to the full post

Simple tag for select-option

I moved this post to Biting Code, my blog dedicated to JVM languages.There you can find an example where a Simple Tag is used to implement a flexible generator of select-option HTML code.

Go to the full post

SkipPageException

This post has been moved to Biting Code, my blog dedicated to JVM languages.It shows how to control the failure in a SimpleTag throwing exceptions, and in particular a SkipPageException.

Go to the full post

Simple tag - looping on an attribute

This post has been moved to Biting Code, my blog dedicated to JVM languages.It shows how to move a loop from JSP to a SimpleTag.

Go to the full post

Simple tag handler

This post has been moved to Biting Code, my blog dedicated to JVM languages.A simple tag handler is written and tested.

Go to the full post

Tag handler

This post has been moved to Biting Code, my blog dedicated to JVM languages.

Go to the full post

Tag Files

This post has been moved to Biting Code, my blog dedicated to JVM languages.
Tag Files are a smart way of including a file in a JSP page.

Go to the full post

JSTL - c:catch

This post has been moved to Biting Code, my blog dedicated to JVM languages.

The JSTL tag c:catch improves our error handling capabilities for exceptions in JSP pages.

Go to the full post

Error pages in Web Application

This post has been moved to Biting Code, my blog dedicated to JVM languages.

Go to the full post

JSTL - c:import

This post has been moved to Biting Code, my blog dedicated to JVM languages.

The JSTL tag c:import is another way of including content in a JSP page.

Go to the full post

JSTL - c:remove

This post has been moved to Biting Code, my blog dedicated to JVM languages.

The JSTL tag c:remove is not strictly required, since we can mimic its behavior using c:set, but using it makes our code clearer.

Go to the full post

JSTL - c:set

This post has been moved to Biting Code, my blog dedicated to JVM languages.

It provides an introduction with examples to c:set, a JSTL tag similar to the jsp:setProperty standard action, but much more powerful.

Go to the full post

JSTL - c:choose

This post has been moved to Biting Code, my blog dedicated to JVM languages.

It gives an example for using the JSTL tags c:choose, c:when, c:otherwise to generate conditional JSP pages.

Go to the full post

JSTL - c:if

This post has been moved to Biting Code, my blog dedicated to JVM languages.

It is about the JSTL tag c:if, that provides a way to elegantly organize conditional branches in a JSP page.

Go to the full post