How can I run a mysql query when the user selects an new option in a select field?

拜拜、爱过 提交于 2019-12-14 03:59:33

问题


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 need to use AJAX with this application? Any examples about doing this? Here is the code I'm working with:

These functions build the options of each select field.

function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
        FROM tbl_category
        ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
    list($id, $parentId, $name) = $row;

    if ($parentId == 0) {
        // we create a new array for each top level categories
        $categories[$id] = array('name' => $name, 'children' => array());
    } else {
        // the child categories are put int the parent category's array
        $categories[$parentId]['children'][] = array('id' => $id, 'name' =>   
$name); 
    }
}   

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
    $name     = $value['name'];
    $children = $value['children'];

    $list .= "<option value=\"$key\"";
    if ($key == $catId) {
        $list.= " selected";
    }

    $list .= ">$name</option>\r\n";

    foreach ($children as $child) {
        $list .= "<option value=\"{$child['id']}\"";
        if ($child['id'] == $catId) {
            $list.= " selected";
        }

        $list .= ">&nbsp;&nbsp;{$child['name']}</option>\r\n";
    }
}

return $list;
}

/* Build the product options list for the radio options */

function buildProductOptions($catId = 0)
{
$sql = "SELECT pd_id, pd_name, cat_id
    FROM tbl_product
    WHERE cat_id = $catId 
    ORDER BY pd_name";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$numProduct = dbNumRows($result);

$products = array();
while($row = dbFetchArray($result)) {
    list($id, $name) = $row;
        // we create a new array for each top level categories
        $products[$id] = array('name' => $name);
}   

// build combo box options
$list = '';
foreach ($products as $key => $value) {
    $name     = $value['name'];

    $list .= "<option value=\"$key\"";

    $list .= ">$name</option>\r\n";

}

return $list;

}

This is the page of the select fields:

$catId = (isset($_GET['catId']) && $_GET['catId'] > 0) ? $_GET['catId'] : 0;

$categoryList = buildCategoryOptions($catId);
$productList = buildProductOptions($catId);

<!--- Category Select --->
<select name="cboCategory" id="cboCategory" class="box">
   <option value="" selected>-- Choose Category --</option>
<?php
        echo $categoryList;
 ?>  
</select>

<!--- Products Select : category is changed the products need to be from selected cat -    
 -->

<select name="selectOptions" id="selectOptions" class="box" multiple="multiple" >
   <option>--Pick the other options--</option>
<?php
    echo $productList;
 ?> 
</select>

回答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

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

var req = getXMLHTTP(); // function to get xmlhttp object
if (req) {
    req.onreadystatechange = function() {
        if (req.readyState == 4) { // data is retrieved from server
            if (req.status == 200) { // which reprents ok status
                document.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

<select onchange="getProducts()" id="cboCategory" class="box">
  ...
</select>
<!-- Can be anywhere on same page -->
<div id="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 json. Check it's tag wiki for more info. Also you can use jquery to do ajax call.



来源:https://stackoverflow.com/questions/12482632/how-can-i-run-a-mysql-query-when-the-user-selects-an-new-option-in-a-select-fiel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!