The two men were among seven candidates vying to lead the conservative Islamic republic. Because neither candidate scored a majority of votes, a runoff is scheduled for Friday.
Rafsanjani, who came in first, was a favorite in recent polls. Ahmadinejad, who trailed by 400,000 votes, surprised analysts by outpacing other well-known and better-financed competitors, according to the Washington Post.
Rafsanjani served two terms as president in the 1980s, a time of frequent government crackdowns on human rights. But in wooing young voters, who now dominate Iranian politics, he presented himself as a "pragmatic conservative."
He has vowed to bring an insider's support to the reformist program of the outgoing president, Mohammad Khatami, to open Iran's economy to foreign investment and promote improved relations with the United States. The United States cut ties with Iran after Islamic radicals took over the U.S. Embassy in 1979.
Ahmadinejad was elected mayor of the capital two years ago and one of his most high-profile acts was converting the city's cultural centers into religious centers. During his campaign, he called for serving the poor as a way to make Iran an example to the Shiite vision of "global Islam," and expressed less interest in renewing relations with the United States, reported the Post.
The outcome of the vote was shrouded in some controversy. After polls closed at 11 p.m. Friday, vote tallying proceeded normally until the early hours of Saturday morning. With one-third of the votes in, Rafsanjani held a firm lead and the most prominent reformist candidate, Mostafa Moin, was a solid second, according to the Post.
At 5 a.m., Ahmadinejad began to surge ahead, and a spokesman for the Guardian Council -- one of the clerical bodies that oversees the elected government -- announced the preliminary total. At that point, President Khatami rushed to the Interior building and berated the Guardian Council for interfering.
The council monitors the voting, but the Interior Ministry, an arm of the elected reformist government, conducts the actual process.
Some of the candidates charged that militias and uniformed Revolutionary Guards had intimidated voters at the polls on behalf of Ahmadinejad, but officials ended up dismissing allegations of fraud on Monday, clearing the way for Friday's runoff.
President Bush condemned the election as flawed and lacking "the basic requirements of democracy."
U.S. officials blame the conservative Guardian Council for disqualifying more than 1,000 candidates from the race, including all women and critics of the current government.