Today, I went to code a form with Dynamic dropwdown list in it.
Mission : I want to make dynamic dropdown list when User choose Category, then the store with that category will appear.
It is the form :
<select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
<option value="-1"> - Choose Category -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select>
<label for="inputName" class="control-label">Store Name</label>
<select name="store" class="form-control" id="store">
<option value="-1"> - Choose Store -</option>
</select>
This is the AJAX :
<!-- linking drop down AJAX -->
<script type="text/javascript">
var ajaxku=buatajax();
function ajaxStore(id){
var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
ajaxku.onreadystatechange=stateChanged;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function buatajax(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function stateChanged(){
var data;
if (ajaxku.readyState==4){
data=ajaxku.responseText;
if(data.length>=0){
document.getElementById("store").innerHTML = data
}else{
document.getElementById("store").value = "<option selected>- Choose Store -</option>";
}
}
}
</script>
And this the code of StoreAPIService.php :
session_start();
$stores = array();
$store_category_id = $_GET['category'];
try
{
//$client = new GuzzleClient();
$response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
echo"<option value=''>- Choose Store -</option>";
foreach ($error['stores'] as $store)
{
$mainStore = new StoreSummary();
echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
array_push($stores, $mainStore);
}
}
}
I got no error, but the Store with 'Category' that I Choose is not appearing.
Could anyone please check if I went wrong.
thanks for your helps.