Ayr United avoided automatic relegation after striking late to beat Dundee but Brian Reid's side will need to survive the play-offs to stay in the Scottish First Division.
Ryan Conroy fired Dundee ahead on 14 minutes and it took Ayr until after the hour mark to level through Keigan Parker's superb free-kick.
But the visitors quickly regained the lead when Steven Milne headed home.
Parker's second, an overhead kick, levelled the score again on 84 minutes and Ross Robertson pounced from close range to snatch the hosts' win a minute from the end.
Ninth-placed United are three points behind Raith Rovers with one game to play, the Fife side having a significantly better goal difference.
Cuthbert, Tiffoney, Dodd (Longridge 19), John Robertson (Hutchinson 8), Smith, Geggan, Trouten, Tomsett, Parker, Roberts, Moffat, Hutchinson (Ross Robertson 85). Subs Not Used: McWilliams, Paterson.
Parker 61, 84, Ross Robertson 89.
Douglas, Irvine (Mcintosh 90), Lockwood, O'Donnell, McKeown, Weston, Riley, McBride, Milne, Benedictis, Conroy. Subs Not Used: Gibson, Fotheringham, Hyde, Chisholm.
Conroy 14, Milne 70.