get sql query displayed rather than query result using AJAX - php

Hello I have been trying to figure out why my code aimed at listing a query result in a table does not work. I took code found on the web and tired to adapt it. My data is stored in pgsql. The html page has a drop down menu that allows selecting an institution name. When I click the submit button to know who belongs to this institution in my database, the php page is loaded and displays the SQL query I want to send to pgsql. I should get the result of the query displayed in a table displayed on the html page instead. The drop down menu works correctly so I do not provide the php code for this one (listinstitutions.php)
A person told me I should use ajaxsubmit() but I do not know where to put this function.
There may be an error in the php file also since the query is displayed rather than being sent to pgsql. Is the json correctly sent?
Your guidance would be very much appreciated.
Thank you.
The html side:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
//////////////////////////////////////
// Displays insitution names in Drop Down Menu
//Getting the selector and running the code when clicked
$('#selinstit').click(function(e){
//Getting the JSON object, after it arrives the code inside
//function(dataI) is run, dataI is the recieved object
$.getJSON('http://localhost/listinstitutions.php',function(dataI){
//loop row by row in the json, key is an index and val the row
var items = []; //array
$.each(dataI, function(key, val) {
//add institution name to <option>
items.push('<option>' + val['Iname'] + '</option>');
});//end each
//concatenate all html
htmlStr=items.join('');
console.log(htmlStr);
//append code
$('option#in').after(htmlStr);
});//end getJSON
});//end cluck
///////////////////////////////
// Displays persons form an institution in a table
$( "$subinst" ).button().click(function( event ) {
console.log($(this)); // for Firebug
$.getJSON('http://localhost/SelectPersonsBasedOnInstitution.php',function(data){ // I make an AJAX call here
console.log($(this)[0].url); // for Firebug check what url I get here
//loop row by row in the json, key is an index and val the row
var items = []; //array
$.each(data, function(key, val) {
//add table rows
items.push('<tr border=1><td>' + val['Pfirstname'] + '</td><td>' + val['Plastname'] + '</td><td><a mailto:=" ' + val['Pemail'] + ' " >' + val['Pemail'] + '</a></td></tr>');
});//end each
//concatenate all html
htmlStr=items.join('');
//append code
$('#instito').after(htmlStr);
});//end getJSON
event.preventDefault();
});
}); //end ready
</script>
</head>
<body>
<form id="myForm" action="SelectPersonsBasedOnInstitution.php" method="post">
Select persons from an institution:
<br>
<tr>
<td>
<select id="selinstit" name="instit">
<option id="in">Select</option>
</select>
</td>
<td>
<input type="submit" id="subinst" value="Submit" />
</td>
</tr>
</form>
<table frame="border" id="instito">
</table>
</body>
</html>
Here is the php code for SelectPersonsBasedOnInstitution.php
<?php
//////////
// part 1: get information from the html form
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
foreach ($_REQUEST as $key => $value){
$$key=$value;
}
// part2: prepare SQL query from input
$sqlquery= sprintf('SELECT "Pfirstname", "Plastname", "Pemail" FROM "PERSON"
LEFT JOIN "INSTITUTION" ON
"PERSON"."Pinstitution"="INSTITUTION"."Iinstitution"
WHERE "Iname" = \'%s\'',$instit);
echo $sqlquery;
/////////
// part3: send query
$dbh = pg_connect("host=localhost dbname=mydb user=**** password=*****");
$sql= $sqlquery;
$result = pg_query($dbh,$sql);
$myarray = pg_fetch_all($result);
$jsontext = json_encode($myarray);
echo($jsontext);
?>

The following line is likely to be the problem (it shouldn't be there):
echo $sqlquery;
Rewrite your code without that line and it should work.
$sqlquery= sprintf('SELECT "Pfirstname", "Plastname", "Pemail" FROM "PERSON" LEFT JOIN "INSTITUTION" ON "PERSON"."Pinstitution"="INSTITUTION"."Iinstitution" WHERE "Iname" = \'%s\'', $instit);
$dbh = pg_connect("host=localhost dbname=mydb user=**** password=*****");
$result = pg_query($dbh, $sqlquery);
$myarray = pg_fetch_all($result);
$jsontext = json_encode($myarray);
echo($jsontext);

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>

How to take textbox value in php if created by js

I am using following code to generate multiple textbox on label click, it works correctly and multiple textbox created with different name. I want to take the value of textbox at php side and run insert query for each textbox. But i don't know how to use it in php. Here is my code plz help.
<html>
<head>
<title>
</title>
<script>
var index = 1;
function insertRow(){
var table=document.getElementById("rep1");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
t1.name = "txtName"+index;
cell1.appendChild(t1);
index++;
}
</script>
</head>
<body>
<label id="btnAdd" style=" width: 10px;" class="button-add" onclick="insertRow();">add</label>
<table id="rep1">
</table>
</body>
</html>
SQL Schema :
T_no(AI) Text_value
PHP CODE:
<?php
if(isset($_POST["submit"]))
{
$t1=$_POST['name'];// i am confused here how to take value and run query for all
?>
Client side Code
You must use Array for multiple name field
<script>
var index = 1;
function insertRow(){
var table=document.getElementById("rep1");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
t1.name = "txtName[]"; //Use array of names not id
cell1.appendChild(t1);
index++;
}
</script>
Please check How to get form input array into PHP array
And You can fetch those array server side using $_POST['txtName']; or any other request method
Server side coding for inserting array into database
<?php
if(isset($_POST["submit"]))
{
$t2=$_POST['txtName'];
$query_parts = array();
$qu = "INSERT INTO try VALUES";
foreach($t2 as $val)
{
$query_parts[] = "('', '" . $val . "')";
}
$qu .= implode(',', $query_parts);
$res=mysqli_query($con,$qu);
if(!$res) { echo("Error description: " . mysqli_error($con)); }
}
?>
The above code will not prevent data from SQl injection.You can use prepared statement for prevent SQL injection in PHP. Link
Use this code. It will helps you.
<?php
print_r($_POST['txtName']); // Here you can get you all values.
?>
<html>
<head>
<title>
</title>
<script>
var index = 1;
function insertRow(){
var table=document.getElementById("rep1");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
t1.name = "txtName[]"; // Use array in textbox name..
cell1.appendChild(t1);
index++;
}
</script>
</head>
<body>
<form method="POST" action="" >
<label id="btnAdd" style=" width: 10px;" class="button-add" onclick="insertRow();">add</label>
<table id="rep1">
</table>
<input type="submit">
</form>
</body>
</html>
For this you have to store total index value also(that should specify how many time you created input field).After that your php code should be like below..
PHP CODE:
<?php
if(isset($_POST["submit"]))
{
$t1=$_POST['txtName'.$index];
?>
Where index variable will your current index value from your loop for length of total input fields

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

Populate input with database data on select change

I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help
you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.
There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.

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