Marco Jansen and Kagiso Rabada forged a crucial ninth-wicket partnership to rescue South Africa from the brink of defeat.