Html
<select class="form-control" name="catid" id="catid">
<option value="">Select a category</option>
<?php $dm->getCategories();?>
</select>
Javascript
function brands(id)
{
var result= {};
var cbs=[];
var call = function (obj) {
cbs.forEach(element => {
//console.log(element);
element(obj);
});
};
var obj = {
len : cbs.length,
then: function(cb) {
cbs.push(cb);
return this;
},
send:function () {
var that=this;
var prob={};
var xhr = new XMLHttpRequest();
xhr.open("GET","ajax/getbrands.php",true);
xhr.onload = function(){
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.response);
data.forEach((element)=>{
if (element.cate_id == id) {
that.result = element;
call(that.result);
}
});
}
}
xhr.send();
return this;
}
}
return obj.send();
}
var xx= brands(2);
console.log(xx.len);
xx.then((obj)=>{
console.log(obj);
});
document.getElementById("catid").addEventListener("change",(event)=>{
if (event.target.value.length !== 0)
{
console.log(event.target.value);
var xyz= brands(event.target.value);
xyz.then((obj) =>
{
console.log(obj);
var text = "";
obj.forEach((element)=>{
text += "<option value='"+element.brand_id+"'>"+element.brand_name+"</option>"
});
document.getElementById("brands").innerHTML = text;
});
}
});
I am extremely new to javascript, I assume, I may have the problem with basic understanding of javascript. so, what happened is I was thinking of making a module which basically does nothing but to fetch all the value at once. as I am new to javascript I did not know how to create the module and how it works.
then I copied a piece of code from some of the old projects and tried to understand how it works. here comes the main question.
xx.then((obj)=>{
console.log(obj);
});
when I am running this piece of code it's showing all three rows of values from the database, but when I am running the same code inside the event handler its showing only one row of data! that's strange, I just could not figure out what the hell is going here,
picture of two different output result when its running globally
result when its called from the event
I am highly grateful to the person who takes time to make me understand these concept. and how should I do them all, thanks in advance
Comments
Post a Comment