Raith Rovers lost their unbeaten record in devastating fashion, despite a spirited performance with 10 men.
The Kirkcaldy side played for more than an hour with a man down after teenager Ross Callachan’s 28th-minute red card in his first start for the club.
Despite being a goal down at the time, Raith equalised and looked set to claim a deserved point until Ayr grabbed a last-gasp winner 30 seconds into injury time.
Boss John McGlynn felt the result was harsh on his team.
“I’m really disappointed for the players because they put so much into the game but ended up not getting anything from it,” he said.
“The players worked extremely hard and showed great character and spirit. We didn’t just sit back with 10 men. We tried to take the game to Ayr and had a couple of good chances in the second half. We were well-disciplined and had a good shape to us.
“Ayr pushed forward with the extra man, and they had a number of corners, free-kicks and throw-ins and unfortunately one goes in when we defended the majority of them well.
“We’ve done it before when we’ve scored late goals and won games, and it’s great when you do, but it’s never nice when you’re on the receiving end of it.”
Ayr started the match on the front foot and took the lead on 22 minutes when Michael Moffat nipped ahead of defender Reece Donaldson to stab home Michael McGowan’s cross.
It looked a tall order for Raith six minutes later when Callachan flew into a late tackle on Mark Roberts with his studs showing, and referee Matt Northcroft deemed it worthy of a straight red card.
The sending-off galvanised Rovers and they were level on 34 minutes when Joe Hamill danced between two players before drilling a low shot into the bottom corner from the edge of the box.
There was little to separate the sides after the break, with Rovers frustrating the hosts with some impressive ball retention that led to goal-scoring chances.
John Baird forced Ayr keeper Kevin Cuthbert to tip over his 25-yard chip shot on 57 minutes before Brian Graham shaved the post with a left foot drive from 18 yards, 20 minutes from time.
Ayr upped the pressure late in the game in a bid to claim their first league win of the season, and defender Andy Geggan hit the bar with an 82nd-minute header, while David McGurn had to beat away a powerful James McKernon strike.
Raith looked to have earned the point that would have preserved their unbeaten start to the league season, but disaster struck in injury-time.
Sub Ross Robertson peeled to the back post to meet a deep cross, and sent a superb header back across goal to find the net via the inside of McGurn’s post.
But McGlynn had few complaints with the referee’s decision to show youngster Callachan a red card.
“It’s a sending-off and we deal with it,” he said. “He’s a young boy. His touch was bad, and he’s tried to win the ball back.
“We’ve had the referees in and seen that you get sent off for tackles like that. It’s unfortunate but he’ll learn.”