Why do chemicals foam up?

Because they release gas.

The most familiar foaming reaction is probably that of baking soda and vinegar. A similar reaction is what makes pancake batter rise. Sodium bicarbonate is a salt of a strong base (sodium hydroxide) and a weak acid, carbonic acid. When you add an acid to a salt of another acid, you generally release a gas that makes the second acid when mixed with water. Baking soda releases carbon dioxide gas, which makes carbonic acid when mixed with water.

You have swallowed carbonic acid – it is the bubbly water to which sugar and flavorings are added to make flavored sodas.

Another familiar reaction that produces bubbles of gas is that of hydrogen peroxide when it meets a catalyst that breaks it down into water and oxygen. That catalyst is a protein called catalase that most living things produce, because hydrogen peroxide is a harmful byproduct of metabolism, and the catalase breaks it down.

Reacting any of several metals (such as aluminum, magnesium, or zinc) with an acid will release hydrogen gas. The metal replaces the hydrogen in the acid, leaving a salt (such as aluminum chloride if the acid was hydrochloric acid) and bubbles of hydrogen.

Electricity can create bubbles of gas. In water, electricity will release hydrogen bubbles from one electrode, and oxygen from the other. In salt water, chlorine gas is released instead of oxygen.

To make bubbles into a foam, it helps to have some molecules that reduce the surface tension in the liquid the bubbles are in. Soap and detergents will do this. By lowering the surface tension, the soap stabilizes the thin layer of water around the bubble in the foam. What is called the Marangoni effect says that water will flow into the area that has the lowest surface tension. As the bubble stretches, the concentration of soap is reduced. This causes water to rush in to strengthen the thinnest layers in the bubble.