Second select box populate from first selectbox in jquery - php

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>';

Related

PHP AJAX HTML: changing unique table data in foreach loop

I'm new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.
I have a PHTML template which looks like the following:
<?php
$content = "";
// creates data selector
$content .= "
<form id = select_data>
<select id = data_selection>
<option value = data1>Data 1</option>
<option value = data2>Data 2</option>
<option value = data3>Data 3</option>
<option value = data4>Data 4</option>
</select>
<input id = selected_data type=submit />
</form>";
// creates table header
$content .= "
<tr>
<th>Data</th>
</tr>";
$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
$object = // instantiate object by array_id, pseudocode
$object_data = $object->getData('default-data'); // get default data to display
// create table item for each object
$content .= "
<tr>
<td><p>$object_data</p></td>
</tr>";
}
print $content;
?>
This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag.
And then I have some Javascript which looks like the following:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){ // get selected data type
e.preventDefault();
var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected},
success: function(data){
$("p").html(data); // replace all <p> tag content with data
}
});
});
});
</script>
This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:
<?php
$attribute = false;
if (isset($_POST['data_selected'])){
$data = $_POST['data_selected']; // assigns variable out of ajax data
$object = //instantiate object, again pseudocode
$object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
echo $object_data;
}
?>
The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.
I tried to identify each <p> tag with the following:
<td><p id = $array_id>$object_data</p></td>
And then creating a new Javascript variable out of the array ID:
var p_tag_id = <?php echo $array_id; ?>;
And finally making the Ajax success function target element ID's based on var p_tag_id:
$("#" + p_tag_id).html(data);
While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.
How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?
You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.
You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):
var num = data_selected.slice(-1) - 1;
(Subtract 1 because the table rows are zero-indexed)
Then, in the AJAX code block's success function:
$('table tr').each(function(i,v){
if (i == num){
$(v).find('td').find('p').html(data);
}
});
The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob's yer uncle.
I haven't tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.
I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:
<td><p id = $array_id>$object_data</p></td>
Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:
$("p").each(function() {
var array_id = $(this).attr("id");
And finally I made the Ajax success target elements based on their ID:
$("#" + array_id ).html(data);
Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){
e.preventDefault();
var data_selected = $("#data_selection :selected").val();
$("p").each(function() {
var array_id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected, array_id: array_id},
success: function(data){
$("#" + array_id).html(data);
}
});
});
});
});
</script>

Populate form based on selected item php

I have a page with a select list (gets successfully populated from mysql) and a text box. The text box has to be populated with a value from mysql based on the item selected in the list. But the ajax call to php is not working and i can not figure out what the issue is. I am just learning ajax and php, so a novice.. Please help. i am stuck with this for a long time.
<script>
$(document).ready(function() {
$('.selectpicker').on("change", function(){
var selected_data = $(this).find("option:selected").val();
alert(selected_data);
$.ajax ({
type: "POST",
data: { selected_data: selected_data },
url: "getoldcharity.php",
dataType: "json",
success: function(res) {
$('#charity_new').val(data.charity_new);
}
});
});
});
</script>
<form id="assign-fundraiser_form" class="form-horizontal" action="" method="post">
<div class="form-group">
<div class="col-md-3">
<select class="selectpicker form-control" id="fundraiser" name="fundraiser" required>
<option value="" selected disabled>Select a Fundraiser</option>
<?php
include('session.php');
$result1 = mysqli_query($db,"select concat(f_firstname,' ',f_lastname) fundraiser from fundraiser where f_company in (select contractor_name from contractor where company_name = '$_SESSION[login_user]') and f_status = 'Active' order by concat(f_firstname,' ',f_lastname)");
while ($rows = mysqli_fetch_array($result1))
{
echo "<option>" .$rows[fundraiser]. "</option>";
}
?>
</select>
</div>
</div>
<input type="text" name="charity" id="charity_new" />
</form>
<?php
include "session.php";
if (ISSET($_POST['.selectpicker'])) {
$ref = $_POST['.selectpicker'];
$query = $db->query("select f_charity charity_new from fundraiser limit 1");
$row = $query->fetch_assoc();
$charity_new = $row['charity_new'];
$json = array('charity_new' => $charity_new);
echo json_encode($json);
}
$db->close();
?>
There are a few problems that I've spotted from quick glance, so I've separated them below.
PHP
In your AJAX request, you are using data: { selected_data: selected_data } which means the PHP code will be expecting a POSTed key named selected_data but you're looking for .selectpicker. You seem to have mixed up a couple of things, so instead of:
$_POST['.selectpicker']
it should be:
$_POST['selected_data']
JavaScript
As Ravi pointed out in his answer, you also need to change your success function. The parameter passed through to this function is res not data, so instead of:
$('#charity_new').val(data.charity_new);
it should be:
$('#charity_new').val(res.charity_new);
MySQL
It also appears as though your query itself is invalid - you seem to be missing a comma in the column selection.
select f_charity charity_new from fundraiser limit 1
should be:
select f_charity, charity_new from fundraiser limit 1
or, seeing as you're not using the f_charity column in the results anyway:
select charity_new from fundraiser limit 1
You aren't using the value that is being POSTed either, meaning that whatever option is selected in the dropdown makes no difference to the query itself - it will always return the first record in the database.
Other
One other thing to be aware of is you're using a class selector on your change function. This means if you have multiple dropdowns with the same class name in your HTML, they will all be calling the same AJAX function and updating the textbox. I don't know if this is what you're aiming for, but from your code posted, you only have one dropdown in the form. If you only want that one dropdown to be calling the AJAX function, you should use an ID selector instead:
$('#fundraiser').on("change", function() {
// ...
}
I think, it should be
$('#charity_new').val(res.charity_new);
instead of
$('#charity_new').val(data.charity_new);

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

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

One dropdownlist depending on the other

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;
?>

Categories