How to use AJAX for fetching data in child dropdown by selecting Parent dropdown - Nodejs , Expressjs, MongoDB
// so here i have dummy database to understand -
suppose we have Thee product categories electronic, Garments & home appliance , In which we have subcategories please refer below two pictures
1. Category (parent Dropdown ) // MongoDB database
2. Subcategory (child Dropdown )
now I want that if I would select product category, product subcategories should automatically fetched in in second or child dropdown
=====================//addProduct.ejs Start =================================
<form method="post" action="/admin/launchp" enctype="multipart/form-data">
<div class="form-group">
<label for="catnm" style="color: #870A30;">Product Category </label>
<select class="form-control" id="category-dropdown" name="catnm">
<option value="">Product Category:</option>
<% if(clist.length){
for(var i = 0; i< clist.length; i++) {%>
<option id="catnm_id" value="<%= clist[i].catnm %>">
<%= clist[i].catnm%>
</option>
<% } } %>
</select>
</div>
<div class="form-group">
<label for="subcatnm"style="color: #870A30;" >Product Sub Category:</label>
<select class="form-control" id="subcategory-dropdown" name="subcatnm">
</select>
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$('#category-dropdown').on('change', function() {
var _id = $('#category-dropdown').val();
$("#subcategory-dropdown").html('');
$.ajax({
url: "/admin/get-subcat-by-category",
type: "POST",
data:{ catnm : _id },
dataType: 'json',
success: function(result) {
console.log(result);
$('#subcategory-dropdown').html('<option value="">Select Subcategory </option>');
$.each(result.states, function(key, value) {
$("#subcategory-dropdown").append('<option value="' + value.subcatnm + '">' + value.subcatnm + '</option>');
});
}
});
});
</script>
//====================addProduct.ejs End =========================
//=================Backend Code Start ==============================
//router.js //create your own router & schema file or modify & Put this code in your file
//= using AJAX fetch product subcategory on behalf of product category
router.post("/get-subcat-by-category",(req,res)=>{
CategorySchemaModel.find(req.body,(err,result)=>{
console.log(result[0].subcatnm)
res.json({
msg: 'success',
states: result
});
}).catch((err)=>{
console.log(err);
res.json({
msg: 'error'
});
});
});
===================== router.js end ==================
here here is our final result -
Comments
Post a Comment