Gillingham needed a stoppage-time penalty from Danny Kedwell to see off the challenge of Northampton.
Jo Kuffour put the Gills in front with a neat finish and doubled the lead with a backheel before Saido Berahino made it 2-1 with a 25-yard strike.
Kuffour completed his hat-trick from the spot after he was felled before Kelvin Langmead's superb angled shot and Berahino's lash home made it 3-3.
But Kedwell gave the Gills the points after Frank Nouble was fouled.
The result leaves Northampton just three points clear of the relegation zone while Gillingham are now two points outside the play-off places.
The Cobblers have failed to register a win since 1 October.
VIEWS FROM THE DRESSING ROOM
On-loan Gillingham striker Jo Kuffour told BBC Radio Kent:
"It was nice. Every striker dreams of that. I'm just glad it was me today.
"I thought we did well but we could have done better and it's nice to get the three points at the end.
"I love it here, there's a great bunch of lads. Hopefully we can agree something.
"It's out of my hands but I would love to stay but it's up to Gillingham and Bristol Rovers."
Northampton Town manager Gary Johnson told BBC Radio Northampton:
"You go through every emotion that the supporters go through. There was some great attacking and some really poor defending.
"We took the game to them in the second half and had three or four unbelievable chances to have won the game.
"You've got to look at the back four's defending. We look like we're going to score now, we've got a shape that looks good going forward but we have to start making teams work for their goals."
Gillingham 01 Flitney 03 Frampton Booked 06 Richards (Fish - 38' ) 12 Martin 15 Lawrence 18 Jackman 04 Lee Booked (Rooney - 72' ) 07 Whelpdale (Weston - 83' ) 09 Kedwell 29 Nouble 33 Kuffour Substitutes 28 Gazzaniga 16 Fish 10 Weston 14 Rooney 23 Payne Northampton 01 Walker 05 Tozer 14 Johnson 25 Westwood 28 Langmead Booked 02 Young 17 Jacobs Booked 29 Arthur Booked (Robinson - 79' ) 31 Niven (Turnbull - 86' ) 09 Berahino 10 Akinfenwa Booked Substitutes 26 Hall 15 Turnbull 22 McKoy 08 Robinson 27 Savage
Ref: Carl Berry