If you are asking about the historical reasons, then asking in History.SE might be better. From the literature point of view the answer lies in text:
This class of women is consigned by our laws entirely to
the discretion of the police. The latter do what they please,
punish them, as seems good to them, and confiscate at their
will those two sorry things which they entitle their industry and their liberty
‘Take three men and conduct this creature to jail.’ Then, turning to Fantine, ‘You are to have six months of it.’
So it seems that Javert is legally able to sentence a prostitute to jail. Notice - "jail", not "prison":
We define prison as “a place of confinement especially for lawbreakers”, and jail as “a place of confinement for persons held in lawful custody.[...]Prison is “an institution (such as one under state jurisdiction) for confinement of persons convicted of serious crimes” and jail is “such a place under the jurisdiction of a local government (such as a county) for the confinement of persons awaiting trial or those convicted of minor crimes.” Source
Even in current world, police can send you to jail for a short time (24-48 hours, depending on country) without conviction.
As for the mayor stepping in: he can override Javert's rule, because mayor is the chief of police - Javert's boss and appears to have legal rights to do so:
Then M. Madeleine folded his arms, and said in a severe
voice which no one in the town had heard hitherto:—
‘The matter to which you refer is one connected with the
municipal police. According to the terms of articles nine,
eleven, fifteen, and sixty-six of the code of criminal examination, I am the judge. I order that this woman shall be set
at liberty.
EDIT:
I've asked this question on History.SE: it seems that the actions depicted in the book are possible for one strange reason - prostitution was a crime that was tolerated, but also punished without a trial:
The legality of prostitution was left conveniently vague; women were, however, allowed to engage in the trade so long as they followed police regulations governing their conduct. Violation of the rules resulted in something euphemistically referred to as "administrative detention," or imprisonment without trial.
The arrested woman had no recourse to a court of law. Indeed, she was for all intents and purposes already placed outside the law by the very fact of her accusation. As soon as the commissaire in her quartier had written up a procès-verbal of the offense, the woman was arbitrarily subject, as a report of 1819 puts it, "to incarceration by administrative decision." Her hearing before the Bureau of Morals was a purely procedural matter.