I have 2 dropdowns called drpcategory and drpitem as below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Item</label>
<select class="form-control bg-dark btn-dark text-white" id="drpitem" name="drpitem">
<?php
$category = $_POST["drpcategory"] ?? 'Electronics';
$item = ''.$dir.'/template/post/'.$category.'/item.txt';
$item = file($item, FILE_IGNORE_NEW_LINES);
foreach($item as $item)
{
echo "<option value='".$item."'>$item</option>";
}
?>
</select>
</div>
As you can see, depending on the selected value of drpcategory, the drpitem should be dynamically populated.
In case you were wondering, both dropdowns will go through the PHP loop and populate if I set $category manually without any post checks.
Now, I'm using AJAX post to post the changes in drpcategory into the same page as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(data)
{
alert(data);
}
});
});
});
</script>
Here is the Chrome Browser > Inspect > Network tab output for the above AJAX post;
And yes, I'm posting this AJAX into the same page and the url is: http://example.com/?page=post which is the same as this Network tab shows.
I have removed the url field from AJAX function because the browser automatically picks up the current page so it's better, and no, manually writing any url in there didn't change anything about what I'm about to ask below.
Question is, how can I make that drpitem to pickup the AJAX posted drpcategory value and start populating dynamically?
I want to AJAX post to the same page and all of this should happen without a page reload.
