taw
taw

Reputation: 18871

Rewriting form urls with javascript

Search forms go to ugly urls normally. If I want users to see nice urls I need to rewrite them on server side and http redirect them.

I'd like to avoid this round trip and rewrite this urls by some simple javascript code. (without javascript on you'll get the usual http redirect)

What's the most reliable way to do that?

Upvotes: 2

Views: 2077

Answers (2)

jensgram
jensgram

Reputation: 31518

<form action="http://host/target" method="get">
    ...
    <input type="text" name="query" value="..." />
    <input type="submit" value="Search" />
</form>

Would give http://host/target?query=...

With plain JS, you could add a listener to the onSubmit event (untested):

<form action="http://host/target" method="get" onsubmit="window.location.href=this.action + '/' + encodeURIComponent(this.elements['query'].value); return false;">
    ...
    <input type="text" name="query" value="..." />
    <input type="submit" value="Search" />
</form>

Would give http://host/target/...

Upvotes: 3

Delan Azabani
Delan Azabani

Reputation: 81502

If, for example, your ugly URI takes the form of

/search.php?query=[input]

and your nice URI takes the form of

/search/[input]

Keep the round-trip implementation (with PHP redirects and URL rewriting) in case the client does not have JavaScript. For those who do, intercept the submit event of the form in question (using the event object's preventDefault method), and in your event handler, do something like

location = '/search/' + encodeURIComponent(queryInputObject.value);

Upvotes: 4

Related Questions