Carbonated drinks contain dissolved CO2 under pressure, when the pressure is release by opening the bottle (or pouring into a glass), the CO2 is released from the solution and appears as bubbles. One of the reasons why so much CO2 can dissolve in water is because it forms carbonic acid (however, as the CO2 bubbles out of solution, the carbonic acid is converted back to CO2).
In some cases, the bubbles can collect at the surface of the liquid as a foam, or head.
The formation of foams is complex and depends on the presence of 'surfactants' which are substances that alter the surface tension of the liquid. You cannot form a head in water, no matter how hard you try, because it contains no surfactants. Similarly, relatively pure water - like some sodas - will not form a significant 'head'.
However, beer contains lots of organic substances which can act as surfactants - these allow the bubbles to form a stable foam.
Similarly, detergents/soaps are surfactants - so when added to water tend to allow foams to form if bubbles of gas are present (e.g. through stirring or shaking).
Note that some types surfactants seem to destabilise foams and are used where foams aren't wanted - e.g. laundry detergent usually contains anti-foam agents to stop the machine filling with foam, some sodas may also use anti-foam agents because people don't like 'head' on their sodas.