Skip to content Skip to sidebar Skip to footer

How Can I Run A Mysql Query When The User Selects An New Option In A Select Field?

I want to have a select box that list categories of products. When a category is selected I want to simultaneously select the products in that category from the database. Do I nee

Solution 1:

Yes you do need to use ajax here. Check following code and notes.

Write the function that returns a ActiveXObject() which would do a ajax call as

function getXMLHTTP() {
    var xmlhttp = false;
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e1) {
                    xmlhttp = false;
                }
            }
        }
    }

    return xmlhttp;
}

Then write a function specific to your site that would get the desired data as

functiongetProducts(){
var select1 = document.getElementById("cboCategory");
var strURL = "getproducts.php?city="+select1.options[select1.selectedIndex].value;

var req = getXMLHTTP(); // function to get xmlhttp objectif (req) {
    req.onreadystatechange = function() {
        if (req.readyState == 4) { // data is retrieved from serverif (req.status == 200) { // which reprents ok statusdocument.getElementById('productsdiv').innerHTML = req.responseText; // div to be updated
            } else {
                alert("[GET Products]There was a problem while using XMLHTTP:\n" + req.statusText);
            }
        }
    };
    req.open("GET", strURL, true); // open url using get method
    req.send(null);
}

}

This function would be called on change event of the cboCategory select options, so the corresponding html would be

<selectonchange="getProducts()"id="cboCategory"class="box">
  ...
</select><!-- Can be anywhere on same page --><divid="productdiv"></div>

Your getproduct.php page would return a html as string that would over-write the contents of producstdiv tag in your html page.

You can also return data from php as . Check it's tag wiki for more info. Also you can use to do ajax call.

Post a Comment for "How Can I Run A Mysql Query When The User Selects An New Option In A Select Field?"