开发者

One dropdownlist depending on the other

开发者 https://www.devze.com 2023-04-06 11:24 出处:网络
I develop a php web page that contains two dropdownlists (select tags) as one of them used to display the car types like Toyota, Nissan, Chevrolet and so on.

I develop a php web page that contains two dropdownlists (select tags) as one of them used to display the car types like Toyota, Nissan, Chevrolet and so on.

Toyota
Nissan
Chevrolet

The other should be used to display the car models like Toyota Camry, Toyota Corrolla, Toyota Cressida, Toyota Eco and son on depeding on the Car Type selected from the first dropdownlist.

I use PHP as a development language plus Sybase as database and I connect to it using ODBC. I use Windows-1256 as Character Encoding as my displayed data is Arabic.

I try to use Ajax to implement that but I do not know how as I used Ajax before to return one value only but in this case I need to reply with some database records in the following format:-

15 "Toyota Camry"
16 "Toyota Corrolla"
17 "Toyota Cressida"
18 "Toyota Eco"

plus that the data is sent in arabic not in English as listed above so the list may be as the following:-

15 "تويوتا كامري"
16 "تويوتا كرولا"
17 "تويوتا كرسيدا"
18 "تويوتا إيكو"

how I can do that using Ajax and make sure that the Arabic text will be displayed well?

I wait your answer and help and Thanks in advance .....

My Code is written in the following to make things more clear and be useful for others and to get the right answer:

The first file

showCarData.php File (Saved as ANSI PHP File)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript" /></script>
<script type="text/javascript"> 
$(document).ready(function()
{ 
$('#selectCarType').change(function ()
{ 
$('#selectCarModel option').remove();
$.ajax(
{
url: "getCarModels.php", 
dataType: 'json', 
data: { CarType: $('#selectCarType').val() }, 
async: true,
success: function(result)
{   
//var x = eval(result);
$.each(result, function(key, value) { $('#selectCarModel').append('<option value="' + key + '">' + value + '</option>'); } );
}
});
$('#selectCarModel').show(); 
});
});
</script> 
</head>
<body>
<select id="selectCarType">     
<option value="0" selected="selected">select car type</option>
<?php
//Connecting To The Database and getting $conn Variable       
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarTypes = "SELECT DISTINCT CarTypeID AS CarTypeCode, CarTypeDesc AS CarTypeName FROM tableCarTypes ORDER BY CarTypeDes开发者_开发百科c ASC";
$rsCarTypes = odbc_exec($conn,$sqlCarTypes);
if (!$rsCarTypes)
{
echo "<option class='CarType' value='n' >Not Available</option>";
}                                   
else
{                                   
while ( odbc_fetch_row($rsCarTypes) )
{
//Assigning The Database Result Set Rows To User-Defined Varaiables
$CarTypeCode = odbc_result($rsCarTypes,"CarTypeCode");
$CarTypeName = odbc_result($rsCarTypes,"CarTypeName");
//Creating the options
echo '<option class="CarType" style="color:#060;" value="'. $CarTypeCode . '"';
echo '>' . $CarTypeName . '</option>' . "\n";               
}                                   
}
odbc_close($conn);
?>
</select>
<select id="selectCarModel">        
<option value="0" selected="selected">select car model</option>
</select>
</body>
</html>

and the other file is

getCarModels.php File (Saved as ANSI PHP File)

<?PHP
//determine the Characterset
header('Content-Type: text/html; charset=windows-1256');

//Recieve CarType variable
$CarType =  $_GET['CarType'];
// initialize an array that will hold the rows 
$result = array();

if ($CarType != Null)
{
//Connecting To The Database and getting $conn Variable       
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarModels = "SELECT DISTINCT CarModelID AS CarModelCode, CarModelDesc AS CarModelName FROM tableCarTypes WHERE CarTypeID='$CarType' ORDER BY CarModelDesc ASC ";
$rsCarModels  = odbc_exec($conn,$sqlCarModels);
if ( $rsCarModels )
{
while ( odbc_fetch_row($rsCarModels) )
{
$CarModelCode = odbc_result($rsCarModels,"CarModelCode");
$CarModelName = odbc_result($rsCarModels,"CarModelName");
$CarModelName = utf8_encode($CarModelName);
$result [$CarModelCode] = $CarModelName;
}
}
else
{
echo "No Data";
}
odbc_close($conn);
}
//send the result in json encoding
echo json_encode($result);
?>

I hope this clear what I asked about and that any one could help me finding where is the error or the thing I miss to get the output in a proper format instead of the strange symbols and characters that could not be read as it shows in the second dropdown list.

Thanks in advance


What I do in such scenario is the following:

  1. I construct the first dropdownlist on the server, with PHP while over the car categories from the database, for example. I place the id of the category as a value of the option. The resulting HTML should look something like this:

    <select id="cars-categories"> <option value="1">Toyota</option> <option value="2">Nissan</option> <option value="3">Chevrolet</option> ... </select>

  2. Then on the page, with JavaScript, I listen for onchange event of the select and when occurs send the category id to the server

  3. PHP code on the server picks the category id and makes a SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']. Send the result as JSON with json_encode

  4. Finally, parse the returned data with JavaScritp and fill the model dropdownlist.

Here is what the client script basically can look like:

<script type="text/javascript">
$(document).ready(function() {
    $('#cars-categories').change(function () {
        $('#car-models option').remove();
        $.ajax({
            url: "get_data.php",
            dataType: 'json',
            data: { category: $('#cars-categories').val() },
            async: true,
            success: function(json){
                $.each(json, function(key, value){
                    $('#car-models').append('<option value="' + value.id + '">' + value.name + '</option>');
                });
            }
        });
        $('#car-models').show();
    });
});
</script>

Encoding shouldn't be an issue.

EDIT: As requested by the author of the question, here is a simple way to get all the rows from the DB query and to send them back to the page as JSON encoded string.

<?php
// connect to DB
...
// initialize an array that will hold the rows
$rows = array();
// sanitize the category id. since it is an int, it is safest just to cast it to an integer
$cat_id = (int)$_GET['category'];
$result = mysql_query("SELECT id, name FROM `models` WHERE cat_id = $cat_id");
while($row = mysql_fetch_assoc()){
   $rows[] = $row;
}
// do a regular print out. It is not going to the screen but will be returned as JavaScript object
echo json_encode($rows);
// you have to exit the script (or at least should not print anything else)
exit;
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号