When soap is added to hard water, the displacement of sodium takes place and calcium, magnesium salts of fatty acid are formed. Since these salts are insoluble in water, they form a precipitate, therefore, soap forms a precipitate in the hard water and does not foam.