send get variables for pretty url

175 views Asked by At

I'm creating a pretty url base web and I have a problem with get variables in form. I have a url like localhost/events/1 (1 is a get variable $_GET['eventID']). I want to send the eventID with a form like below

<select name='eventID'>
    <option value='1'>firstEvent</option>
    <option value='2'>secondEvent</option>
    <option value='3'>thirdEvent</option>
</select>

but when i click on submit button to send information into page and my url change to this

localhost/events/?eventID=1

but i want my url to be look like this

localhost/events/1

how could I achive to this?

3

There are 3 answers

0
Hmmm On

According to W3C The question mark is part of the definition of form submission with the GET method, so you can't actually do this. but you can redirect the page with javascript.

 <form id="form" method="get">
 <select name='eventID'>
     <option value='1'>firstEvent</option>
     <option value='2'>secondEvent</option>
     <option value='3'>thirdEvent</option>
 </select>
 <input type="button" onclick="document.location.href= '/events/' + form.eventID.value" value="Submit">
 </form>
0
Ramin On

thanks to all. I want a solution without javascript or jquery but it seems, there is no way to do this without them both. I finally wrote some code in Jquery to solve this problem.

 <form id="events" method="get">
    <select name='eventID'>
     <option value='1'>firstEvent</option>
     <option value='2'>secondEvent</option>
     <option value='3'>thirdEvent</option>
    </select>
 <input type="button" onclick="document.location.href= '/events/' + form.eventID.value" value="Submit">
 </form>

$('#events').on('submit', function(e){
    e.preventDefault();
    document.location.href= '/events/' + $(this).find('select#sportID').val();
})
0
kafsoksilo On

If you want to do this at the client side, you can use the javascript onsubmit event and redirect to the page that you want. For example:

<script type="text/javascript">
function yourFunction()
{
    var sel = document.getElementById('eventID');
    if (sel.selectedIndex !== -1)
    {
        window.location.href = '/events/' + sel.options[sel.selectedIndex].value;
    }

    return false;
}
</script>

<form method="get" onsubmit="return yourFunction()">
<select name="eventID" id="eventID">
    <option value="1">firstEvent</option>
    <option value="2">secondEvent</option>
    <option value="3">thirdEvent</option>
</select>
<input type="submit">
</form>