user3477805 user3477805 - 3 months ago 8
Ajax Question

Dynamically loading content in div using select list

I am trying to load contents in div section using the drop down select menu. When user selects any category, contents of that category should be displayed.
(I don't want to make different page for every category,just update the contents based on selected category)
On selecting a category by user,popular brands of that category must be displayed. For example,if user selects Vehicles then div section should display brands of car,bikes etc.

I tried searching but in every tutorial but it is given to dynamically load a new page inside div tag,I just want to show some static contents without creating separate page for each category.What code should be written inside script tag to do that?

<html>
<head>
<script type="text/javascript">



</script>
</head>

<body>

Browse Category:
<select id="category" onChange="displayCategory()">
<option value="MobilesAndTablets"></option>
<option value="Electronics">Electronics</option>
<option value="Vehicles">Vehicles</option>
<option value="HomeAndFurnitures">Home and Furnitures</option>
<option value="Animals">Animals</option>
<option value="BooksAndSports">Books and Sports</option>
<option value="FashionAndBeauty">Fashion and Beauty</option>
<option value="RealEstate">Real Estate</option>
<option value="AllCategories">All Categories</option>
</select>
<br>

<div id="ContentArea">

</div>

</body>
</html>

Answer
<html>
<head>
    <script type="text/javascript">
        $('#category').on('change', function(event) {
            var val = $(this).val();
            $.ajax({
                url: 'test.php',
                type: 'POST',
                data: {cat: val},
            })
            .done(function(data) {
                $('#ContentArea').html(data)
            })
            .fail(function() {
                console.log("error");
            })
            .always(function() {
                console.log("complete");
            });

        });

    </script>
</head>

<body>

    Browse Category:
    <select id="category" name='category'>
        <option value="MobilesAndTablets"></option>
        <option value="Electronics">Electronics</option>
        <option value="Vehicles">Vehicles</option>
        <option value="HomeAndFurnitures">Home and Furnitures</option>
        <option value="Animals">Animals</option>
        <option value="BooksAndSports">Books and Sports</option>
        <option value="FashionAndBeauty">Fashion and Beauty</option>
        <option value="RealEstate">Real Estate</option>
        <option value="AllCategories">All Categories</option>
    </select>
    <br>

    <div id="ContentArea">

    </div>

</body>
</html>

UPDATE:

Server side result depends to your work. for example I get category name and echo that:

<?php

if (isset($_POST['category'])) {
    echo $_POST['category'];
}

?>