Democrat Doug Jones defeated Republican Roy Moore Tuesday night in the Alabama special Senate election — dealing a stunning blow to President Trump, who endorsed Moore despite allegations that the former judge had sexually abused at least one underage girl and tried to date others.

Jones’ jubilant supporters broke into cheers at his headquarters in Birmingham at about 10:30 p.m., when news organizations called the race for him as he was leading 49.7 to 48.6 percent with 99 percent of precincts reporting. “Thank you ALABAMA!!,” Jones tweeted.

His victory means that the Republicans’ majority in the Senate will sink to a razor-thin 51-49 when Jones is sworn in right after the first of the year, making it tougher for the president to pass his legislative agenda, including tax reform and an ObamaCare repeal.

The Democrat will serve out the term of now-Attorney General Jeff Sessions and will next face a GOP challenger in 2020.

Despite tallies showing Jones up by more than 20,000 ballots, Moore refused to concede, saying, “When the vote is this close, it’s not over,” and “God is in control.”

Nevertheless, Jones claimed victory as he took the stage at his campaign headquarters and said his race against Moore “has been about the rule of law.”

“I have always believed that the people of Alabama had more in common than to divide us,” he Jones. “We have shown not just around the state of Alabama, but we have shown the country the way that we can be unified.”

Jones added, “Tonight, ladies and gentlemen, you took the right road,” as supporters broke out into chants of “USA, USA, USA!”

A gracious President Trump, who had in the past week given Moore a full-throated endorsement, tweeted congratulations to the Democrat.

“Congratulations to Doug Jones on a hard fought victory,” Trump posted moments after Jones’ victory speech. “The write-in votes played a very big factor, but a win is a win. The people of Alabama are great, and the Republicans will have another shot at this seat in a very short period of time. It never ends!”

New York Democratic Sen. Kirsten Gillibrand, whom Trump attacked in a tweet earlier in the day, tweeted her congratulations.

“Congrats, @GDouglasJones, on your win in Alabama! This is a victory for showing up, fighting to the end, and standing for what’s right,” she said.

Trump had backed Moore despite the lurid allegations because the Moore had vowed to back the president’s agenda.

Moore’s loss was a black eye for anti-establishment guru Steve Bannon, who had bucked the GOP establishment to back him.

Tuesday morning, wearing a cowboy hat, Moore galloped up to the polling place on his horse, Sassy, to cast his vote at the Gallant Fire Department.

With David K. Li and Post Wires