I have three HTML DropDownList (<select><option></option></select>). The first DropDownList contains categories, the second one contains subcategories of different products and the third one contains brands (or manufacturers).
When a category is selected, two drop downs subcategory and brand should be populated at once from the database according to the category id being passed to an Ajax function. I’m using the following Ajax code.
function ajax()
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp = new ActivexObject("Microsoft.XMLHTTP");
}
}
function getBrandList(selected) //selected is the category id.
{
ajax();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("brandList").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/BrandAjax.php?selected="+selected, true);
xmlhttp.send();
alert(selected);
}
function getSubcategoryList(selected) //selected is the category id.
{
getBrandList(selected); //First above function is invoked to populate brands.
ajax();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("subCategoryList").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/SubCatAjax.php?selected="+selected, true);
xmlhttp.send();
}
When a category is selected, the getSubcategoryList(selected) Javascript function is invoked which does the Ajax request. The problem is that I need to populated both subcategory and brand drop down at once (when a category is selected).
It is working and both the drop downs are populated at once according to the category id being passed (it’s the parameter of the above functions selected).
I’m unnecessarily using an alert box at the bottom of the function getBrandList(). When this alert box is commented, only one drop down which is subcategory is populated. Brands remain empty. I don’t need this alert box anymore.
Why does this happen? What is the solution?
seriyPS’s basically hit the target on this. The issue is in fact the xmlhttp variable. You need to declare it local within each function it is being used. Basically, create a closure for the function calls. The issue isn’t necessarily that it needs to be “local” however, but it is being redefined in the second request as a result of being a global variable. This essentially kills the initial request because the variable now points to the second request.
The reason the alert box makes it work is because the first request is finishing the ajax request before you can “click” ok. (The alert box will pause the javascript execution and therefore delay the second request until after you have clicked ok.)
To fix this, you can modify your code to use a different variable for each request. Try changing your function to something like this: