The teams could not be separated after 20 overs each and one Super Over, before South Africa spinner Keshav Maharaj defended 24 off the second Super Over as Afghanistan managed 19.
It was a game that swung one way and then the next, but Afghanistan were denied a first ever victory over the South Africans in T20 cricket.
South Africa thought they had won the game when Aiden Markram caught Noor Ahmad in the first ball of the final over in Afganistan’s innings, but Kagiso Rabada over-stepped, one of two no-balls he bowled in the six deliveries to go with a wide in a nightmare end for him.
Afghanistan needed 13 off that over but managed 12, with Fazalhaq Farooqi run out by inches coming back for the winning run.
That meant a Super Over, with Afghanistan managing 17 off Lungi Ngidi’s six balls, and putting the side in the driving seat.
But Tristan Stubbs hit a six off the final ball to tie the scores as South Africa forced a repeat.
Stubbs hit another six and David Miller two more as South Africa set Afghanistan 24 to win in the second Super Over.
Still needing 24 from four deliveries after Maharaj was handed the ball in a gutsy move, Rahmanullah Gurbaz hit the first three of those for six before there was a wide, only to get out on the final ball in a scarcely believable finish.
The win moves South Africa top of Group D with four points, ahead of New Zealand on net run-rate. Afghanistan are likely heading home after this stage with only the top two teams advancing to the Super Eights.
They have no points, but games to come against Canada and the United Arab Emirates. They would need one of New Zealand or South Africa to be upset by a minnow in the pool to stand a chance.
Afghanistan won the toss and sent South Africa into bat, with the Proteas posting 187 for six in their 20 overs.
The innings was anchored by a superb 114-run second wicket stand from 61 balls between Quinton de Kock (59 from 41 balls) and Ryan Rickelton (61 from 28 balls), but slowed towards the end once Rashid Khan (2-28) removed both batters in the same over.
There was a late cameo from Miller (20 not out from 15 balls) to get them close to the 200 mark.
Seamer Azmatullah Omarzai picked up 3-41 in his four overs and was the pick of the Afghanistan bowlers.
A brilliant 84 from 42 balls by Gurbaz led the Afghanistan reply and was the sole reason they were able to level the scores, with no other batter scoring more than 22.
Gurbaz managed seven towering sixes as he blazed the bowling to all parts, before eventually being caught on the boundary.
Ngidi was the pick of the South African bowlers with 3-26 in his four overs, with the team's cause not helped by 11 wides to go with Rabada’s two costly and ill-timed no-balls.
