Hernan Perez struck deep into injury time as Villarreal scored twice in the final 10 minutes to come from behind and beat Malaga 2-1.
After an early Marcos Senna effort had rattled the crossbar it was the visitors who largely controlled proceedings and they deservedly took the lead when Santi Cazorla came back to haunt his old club with a left-foot shot from the edge of the area that gave Diego Lopez no chance.
However, Villarreal rallied in the final quarter and were handed a route back into the game when Carlos Kameni up-ended Perez in the box with seven minutes remaining.
The goalkeeper was sent off and Senna duly tucked away the penalty.
Perez capped a remarkable comeback four minutes into stoppage time as he slammed the ball home from outside the box to give Villarreal a vital three points in their battle to avoid relegation from the Primera Division.
Malaga had come into the game on the back of a run that had seen them take 19 points from 24 and rise to third in the table at the weekend, but it was the hosts who were first to threaten as Senna's effort from distance caught Kameni unaware and came back off the bar.
Thereafter it was Manuel Pellegrini's men who controlled the flow of the game in the first period, although they did not create too many chances.
Salomon Rondon headed over from Duda's free-kick before Isco's rasping effort was held at the second attempt by Lopez.
Malaga continued to press after the break and eventually did find a way through as Cazorla arrowed an effort into Lopez's bottom left-hand corner with 25 minutes remaining.
The goal though forced Villarreal to come out more and with the introduction of Brazilian forward Nilmar they began to pose more of a threat.
And they were handed the chance to equalise when Kameni recklessly wiped out Perez inside the area. The Cameroon international was subsequently shown a red card and substitute Ruben could not get near Senna's clinical spot-kick.
The hosts then pushed on with the man advantage and in the 94th minute the goal they craved arrived when Perez latched onto Ruben's poor punch to send the ball past the despairing Nacho Camacho on the line to move Villarreal clear of the bottom three.