St Johnstone nicked all three points when Brian Graham came off the bench to score the only goal on his debut after joining the club on loan from Dundee United.
The winner, which came four minutes from the final whistle, was a bit harsh on Motherwell who slumped to their fourth consecutive defeat despite looking the more likely to score in the second half.
Motherwell gave a debut to on-loan Mark O'Brien and the Derby player was quickly into action as Saints, aiming to build on their win over Aberdeen last week, forced play from the start.
After only seven minutes Chris Millar whipped in a cross which Scott Brown met on the volley just outside the six yard box but his shot was bravely blocked by Craig Reid.
A minute later Dan Twardzik made the first save of the game when Millar tried his luck from 20 yards but his drive was straight at the home keeper.
Twardzik was again in the right place when Lee Croft's cross evaded the home defence, only for Gary McDonald to head the ball into his hands.
Motherwell then had a series of shots on the visitors' goal but long range efforts from Henrik Ojamma and Paul Lawson trundled harmlessly through to Alan Mannus.
Lawson, making his first appearance of the year after a lengthy injury, then broke into the visitors box only to watch his low drive blocked by Tam Scobbie.
While there was plenty of play towards both there was little to worry either keeper. On the half hour mark Twardzik was tested but this time Scott Brown's drive was easily saved.
Just before half-time, Ainsworth curled in an inviting cross which found John Sutton but his header drifted away from goal.
The Fir Park striker had the first chance of the second half, but from an angle he shot tamely at Mannus.
Ten minutes into the half the Saints goal had a double escape. Firstly Ainsworth's cut back was cleared only as far as Reid, whose drive cannoned off Scobbie, with the home side screaming for handball. From the resulting corner Sutton's downward header was net-bound until the grounded Mannus cleared the ball with his feet.
As the pressure on the visitor's goal mounted Tommy Wright replaced Croft with Michael O'Halloran, before Motherwell made their first change sending on striker Lee Erwin for Josh Law.
It was O'Halloran, though, who came closest to scoring when his cross struck the outside of the keeper's left hand post.
In a final attempt to break the deadlock Saints sent on former Well player Simon Lappin and on-loan striker Graham.
The game looked to be heading for a draw after Twardzik held a McDonald header before the Saints sub finally found the net four minutes from time. McDonald crossed from the right inviting Graham to rise in front of the home defence and head powerfully beyond the keeper.