shibbir ahmed shibbir ahmed - 1 month ago 6
Apache Configuration Question

How to modify query string to plain url using PHP?

I have following html form :

<div class="row form">
<div class="col-md-offset-3 col-md-6 col-md-offset-3">
<form class="form-inline" role="form" method="get" action="<?php echo htmlspecialchars(SITE_URL.'location'); ?>">
<div class="form-group col-md-10 no-p-m">
<select class="form-control" id="basic" name="location" required>
<?php
$get_location = mysqli_query($conn, "SELECT * FROM product_sub_area");
if(mysqli_num_rows($get_location) == 0 ) {
$choose = 'No City found';
} else {
$choose = 'Choose City';
}
?>
<option value=""><?php echo $choose; ?></option>
<?php
while($get_location_result = mysqli_fetch_array($get_location) ) {
$location_id = (int) $get_location_result['psub_area_id'];
$location_name = htmlspecialchars($get_location_result['psub_name']);
echo "<option value='$location_id'>$location_name</option>";
}
?>
</select>
</div>
<div class="form-group col-md-2 no-p-m" id="basic">
<input type="submit" class="btn btn-default filter-search" value="BROWSE">
</div>
</form>
</div>
</div>


When I submit this form the url is showing like bellow :


http://localhost/freelancer/happiechef/location?location=1


But I need to show this type of url :

http://localhost/freelancer/happiechef/location/carlifonia

here
/location/
is a page called
location.php
. I am hiding page extension using
.htaccess
.

So from
location.php
page I want to get
$_GET['location']
value =
$location_id


for eg.

$_GET['location'] = 1 or 2 ( select tag option value)

Existing .htaccess code

ErrorDocument 404 not-found.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^location/([\w-]+)$ location.php?location=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

Answer

Here is an example of how this can be accomplished in jQuery:

First, add an id to your <form> tag so you can access it easily:

<form id="formname" class="form-inline" role="form" method="get" action="<?php echo htmlspecialchars(SITE_URL.'location'); ?>">

You also have a duplicate id called "basic". Make sure you leave it only on the <select> tag and remove the other one.

Then in your JS:

$("#formname").submit(function(event) {
    event.preventDefault();
    var loc = $("#basic option:selected").text();
    window.location.href = '/freelancer/happiechef/location/' + loc;
});

This will forward the user to the URL, for example http://localhost/freelancer/happiechef/location/carlifonia. Then .htaccess will rewrite this URL to location.php?location=california.

Comments