One dropdownlist depending on the other - php

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 CarTypeDesc 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:
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>
Then on the page, with JavaScript, I listen for onchange event of the select and when occurs send the category id to the server
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
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;
?>

Related

Passing value from HTML form to php variable

I'm trying to pass a value from an HTML form and store it to a php variable so i can use this variable into a query to determine what row to get from database. I'm using _post['category'] to get the selected value and I'm passing the variable to the query to get the desired row but I'm not getting anything so far any help will be appreciated. Here is what I wrote so far:
<form method="post" action="a34.php">
<select name="category">
<option value="6008">15</option>
<option value="6018">25</option>
<option value="6034">30</option>
<option value="6038">40</option>
$V=$_POST['category'];
$getrow= "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID = '$V'";
I recommend you to use strip_tags function. Never put raw data into sql.
So
If(isset($_POST['category']) {
$data = strip_tags ($_POST['category']);
$getrow= "SELECT ProdID, ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable, cart_thumb
FROM accessories
WHERE ProdID = '. $data .'";
}
Okay, try the following.
The JS file detects when the user clicks an option and sends out an ajax request to the updateRow.php file with the $_POST variable of val.
updateRow.php takes the $_POST variable and casts it into an integer. The query is then updated with that variable. Process the query, then echo, print, etc. the data in the desired HTML format. Otherwise, the data echo 'failure'.
The output that is echoed, printed, etc is then sent back to the JS file under the variable data. If the data equals 'failure', then an error message is outputted. Otherwise, it inserts the HTML in the #row element.
// ------ Your JS file ---------
$(function() {
$row = $("#row");
$("#update-row").on("change", function() {
var val = $("select option:selected", this).val();
$.post('updateRow.php', {
val: val
}, function(data) {
if (data == 'failure') {
$row.text("Sorry, the row does not exist");
} else {
$row.html(data);
}
});
});
});
//------- updateRow.php ---------
//Make sure path/to/updateRow.php in the JS file is updated to here
$V = (int) $_POST['val'];
$getrow = "SELECT ProdID,
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID =" . $V;
if ( QUERY_IS_SUCCESSFUL() ) {
echo 'The <b>HTML</b> you want to display the data in';
} else {
echo 'failure';
}
<!----- HTML file ---->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="path/to/js/file.js"></script>
<form method="post" action="a34.php" id="update-row">
<select name="category">
<option value="6008">15</option>
<option value="6018">25</option>
<option value="6034">30</option>
<option value="6038">40</option>
</select>
</form>
<div id="row"></div>

Display different dive when select different select option with MySQL query

There are some table in my DB. In "level" table, there are 3 level, "O level", "A level" and "Another level". And I have 3 subject table for these level. They are "sub_o", "sub_a" and "sub_another" and they have different subjects. I make a select option for "level" table by SQL query.
Code is given below:
<select name="" id="">
<?php
$result = mysql_query("SELECT * FROM vhlabel");
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['label_name']."</option>";
?>
</select>
And there are different subject for different level. I want when I will select "O level", then its subject will be displayed in check box. And when I select another level, another subjects will be displayed in check box.
What you want can easily be achieved with AJAX and by using jQuery the AJAX becomes more easier. So your solution with that can somehow be as below:
<select name="level" id="level">
<?php
$result = mysql_query("SELECT * FROM vhlabel");
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['label_name']."</option>";
?>
</select>
<div id="sub">
</div>
<script>
$('#level').on('change', function() {
var levelChangedTo = $(this).val();
//AJAX request to some server script that will pass the changed level
//And that script would return the HTML that would be appended
//to some other div which would have checkboxes.
$.ajax({
method: "POST",
url: "serverside.php",
data: { selectedLevel: levelChangedTo }
})
.done(function( response ) {
//Here append or replace the HTML according to your needs
jQuery('#sub').append(response);
});
});
</script>
Note: This is just a guideline through which you can achieve your goal.

update data in the div

I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point

Second select box populate from first selectbox in jquery

i want to populate second select box name 'ctype' from the value of first select box. but the problem,still not display the value that i attach...i dont know how..now already 2 weeks i try to solved..but still nothing to display in second select box..
cash.php
on the first select box
<?php $qryselect = mysql_query("select * from cc_merchant"); ?>
<select id="merchant" name="merchant" style="font:25px Arial, Helvetica, sans-serif; font-weight:bold; color:#000000;">
<option value=''>--Choose One--</option>
<?php while($getrow=mysql_fetch_array($qryselect)) {?>
<option value="<?php echo $getrow['merchant_id']; ?>" ><?php echo $getrow['bank_merchant']; ?></option>
<?php } ?>
</select>
second selectbox
<p id="ctype">
<select id="ctype_id" name="ctype_id" style="font:25px Arial, Helvetica, sans-serif; font-weight:bold; color:#000000;">
<option value="">--Choose One--</option>
</select>
</p>
jquery
<script type="text/javascript">
$("#merchant").selectbox({
onChange:function(val,inst){
$.ajax({
type:"GET",
data:{merchant:val},
url:"getctype.php",
success:function(data){
$("#ctype").html(data);
$("#ctype_id").selectbox();
}
});
},
});
</script>
script getctype.php
<?php
session_start();
require_once("dbcon.php");
$target = $_GET['merchant'];
$sql = mysql_query("select card from card_support where merchant_id = '$target'");
$getmerchant = mysql_fetch_assoc($sql);
$card = $getmerchant['card'];
echo $card."\n";
?>
this is the example that i follow...the value from the first select box populate to second select box...
http://www.bulgaria-web-developers.com/projects/javascript/selectbox/index.php
First, you getctype.php is asking the database and return only one card. May be you should iterate on the result in order to return multiple values. Moreover, it is recommended to return JSON data (which will be easyly managed by the Javascript). You can do this work with a piece of code like
<?php
// start the session and load your libs
session_start();
require_once("dbcon.php");
// Ask DB for result and store them in an array
$sql = mysql_query("select card from card_support where merchant_id = '$target'");
$result = array();
while($getmerchant = mysql_fetch_assoc($sql))
$result[] = $getmerchant;
// Send JSON header (no cache)
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// Finally return the array in JSON format
echo json_encode($result);
The data returned by the PHP script will be a JSON response like:
["card1","card2","card3",....]
Secondly, when we look at you AJAX call, the success function is replacing the HTMLElement with the id ctype
$("#ctype").html(data);
The HTMLElement with the id ctype is a <p>, so the content of the <p> is completely replaces with your raw content (the card value), wich is not a . Then, your second line of code:
$("#ctype_id").selectbox();
will not have any effect because the does not exist anymore (replaced by the content return from the AJAX call).
To make it work, you can use this secon piece of code in JS:
// Assume the second select is already a **selectbox**
// Make the first select a selectbox
$("#merchant").selectbox({
onChange:function(val,inst){
// Run the ajax call to refresh the content of the second selectbox
$.ajax({
type: "GET",
data: { merchant: val },
url:"getctype.php",
dataType: 'json',
success: function(data) {
// Remove previous content of your second selectbox
$("#ctype_id").empty();
// Append default option
$("#ctype_id").append($('<option value="">-- Chose one --</option>'));
// Loop on your data (which is an array)
for(var i = 0 ; i < data.length ; i++)
{
$("#ctype_id").append($(document.createElement("option"))
.val(data[i])
.html(data[i]));
}
}
});
}
});
if you use jquery, i should do the following:
$("#merchant").on('change', function() {
$('#ctype_id').empty();
$.get('getctype.php', function(data) {
$(data).appendTo('#ctype_id');
});
});
You php code would be something like this:
echo '<option value="">--Choose One--</option>'
$sql = mysql_query("select card from card_support where merchant_id = '$target'");
$getmerchant = mysql_fetch_assoc($sql);
$card = $getmerchant['card'];
echo '<option value="'.$card.'">'.$card.'</option>';

passing value of selected value of dropdownlist to another in one php file

i have a php file i have three dropdown in one php file like region province district so based on selecting region the provinces should be shown and based on the province the district should be shown so i want to implement these in one php file how to do that i can do it in different php file but i want to do it in one php file and the problem is that i can't pass the first dropdownlist value to the secand using ajax i want this in ajax.
if any one help me that will be highly appreciated.
thanks
This is what i usually do in php/ajax for region - province:
jQuery code:
$('#idRegion').change(function(){
if($(this).val() == ''){
$('#idProvince').attr('disabled', 'true');
}else{
var idRegione = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#idProvince').html(json.html);
}
);
$('#idProvince').removeAttr('disabled');
}
});
PHP code:
function getProvincieByRegionId() {
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();
}
You can use this as a starting point
I don't completely understand what you mean about one PHP file but this is the code I use for dynamically populating sub select boxes. Basically on select box change grab the ID and do Ajax via jQuery to get JSON response of cities and populate dropdown.
I use this code for populating a select box of cities (from one PHP file) based on the country you have selected:
<script type="text/javascript">// <![CDATA[
$(document).ready(function(){
$('#country').change(function(){ //any select change on the dropdown with id country trigger this code $("select[id$=cities] > option").remove(); //first of all clear select items
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "GET",
url: "home/get_cities/"+country_id, //here we are calling our user controller and get_cities method with the country_id
success: function(cities) //we're calling the response json array 'cities'
{
$.each(cities,function(id,city) //here we're doing a foeach loop round each city with id as the key and city as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(id);
opt.text(city);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
});
// ]]>
</script>
You could post the data instead if you wanted to. In the PHP you would do something like this:
function get_cities($country){
$this->load->model('cities_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->cities_model->get_cities($country)));
}
I wrote a post on this here: http://theninthnode.com/2011/01/dropdown-filtering-with-codeigniter-and-ajax/

Categories