Iestyn Harris kicked a last-gasp penalty at Castleford as Bradford snatched a dramatic win to avoid a tough Super League play-off trip to France.
The Bulls had struggled to shake off the league's bottom side at The Jungle despite a hat-trick from winger Semi Tadulala.
With Warrington losing to Huddersfield, the late win was enough to take the Bulls above the Wolves into fifth and therefore see them avoid a tricky play-off clash away to Catalans Dragons.
Yet they had to fight hard against a Castleford side determined to end a troubled campaign on a high.
The Tigers had only a mathematical chance of avoiding the wooden spoon but they were in the mood and dominated the first half with Awen Guttenbeil prominent in his final game before retirement.
They produced a strong response after falling behind to a Tadulala try out wide, created by a fine Paul Deacon run, after just two minutes.
Deacon added the conversion but the Tigers roared back as Stuart Donlan found space and sent winger Richard Owen over with a superb long pass.
Castleford went close again only for Ned Catic to knock on but the Bulls failed to heed the warning as a slick handling move in tight space put the hosts ahead.
Kirk Dixon claimed the try after Harlequins-bound Luke Dorn had passed outside to Michael Wainwright and he in turn had fired back inside to his centre.
Dixon converted and added a penalty soon afterwards and the Bulls were fortunate to hold out after a Peter Lupton break cut them open once again.
The Bulls made the most of their reprieve and levelled the scores on the stroke of half-time as Tadulala went over for his second, again in the corner, against the run of play.
That score, and possibly news that Warrington were trailing, seemed to galvanise the Bulls as they started the second half strongly.
Yet Castleford, strong in attack earlier, proved equally proficient in defence as they limited the impact of the industrious Deacon and Wayne Godwin, who perhaps worryingly for the Bulls both left the field.
The Bulls forced successive drop-outs but Cas held firm as they waited patiently for their own opportunities.
They seized their chance just after the hour as Andrew Henderson forced his way forward and Ryan Boyle twisted and turned his way over under posts for another Dixon-converted try.
Bradford dug deep, however, and in Tadulala still had a potent weapon.
The Fiji winger looked dangerous on every carry and when Chris Nero worked the ball to him with 10 minutes remaining he made no mistake as he cut inside to score.
Harris, taking over from the absent Deacon, nailed the difficult conversion to level at 16-16 and set up a tense finale.
It was Harris, off the bench, who created the opportunity to win the game, beating his man with an outrageous dummy.
Catic caught him but was penalised and sent off for holding down. Harris held his nerve to secure the points.