Soda is pressurized with carbon dioxide gas, making it bubbly and fun-tasting. When you open a can or bottle, the pressure is released, and the gas expands to fill the greater volume, in this case, into the air around you. In most instances, the excess gas is on the top of the liquid and is able to freely expand into the air.
When the can or bottle is shaken, however, the gas is mixed with the liquid inside. Some of this gas gets stuck on the sides of the can or bottle. When that gas tries to leave the open can and fill the new volume, it takes the liquid with it, and you are left with the big mess.
The best way to prevent the mess is to tap the sides of the can prior to opening the can. Tapping the side dislocates the gas stuck on the sides of the can and lets it escape out the top, which is where you want it. Often, you see people tapping the top of the can. This is effective too; however, it is only effective in that tapping the top of the can causes vibrations down the sides of the can. It is more efficient to tap the sides directly.