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.
Ayr: 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.
Booked: Tomsett, Geggan.
Goals: Parker 61, 84, Ross Robertson 89.
Dundee: Douglas, Irvine (Mcintosh 90), Lockwood, O'Donnell, McKeown, Weston, Riley, McBride, Milne, Benedictis, Conroy. Subs Not Used: Gibson, Fotheringham, Hyde, Chisholm.
Booked: McBride, McKeown.
Goals: Conroy 14, Milne 70.
Ref: Alan Muir.