Believe it or not this actually works for most synthetic carpets and rugs. I would not recommend trying this on a wool or silk rug. It could create problems and should be used only after performing a test clean in a small area that can easily be hidden.
Shaving cream is designed to lift using a fairly stiff foam and does a good job at lifting out recent spills and carpet messes. I would recommend staying away from using a shaving cream that has too many additives or lotions that might leave residues in the carpet. I would also recommend doing a post rinse with some water to make sure the shaving cream is rinsed away.