How to generate dynamic dropdown PHP Javascript mySQL - javascript

I need help with generating dynamic dropdowns using PHP, Javascript and mySQL. I am not good with AJAX and Javascript and hence I'm asking for help here.
I have a table named Hotel, which contains a list of hotel names and categories. They are categorised by locations such as North, South, East and West. I am trying to allow the user to pick the categories they want, then the second dropdown will generate a list of available hotels under that particular category. As mentioned, I am not good with AJAX or JS.
The question has been solved! I have edited my answer to work with the database, assuming basic user root and no password. the table hotel has 3 columns, id, category and name.
booking.php
<div class="form-group">
<label class="control-label col-sm-3" for="PreferredHotel">Preferred Hotel:</label>
<div class="col-sm-3">
<select class="form-control" name="hotelCategory" onchange="fetchHotelNameByArea(this.value)">
<option value="0">Please select area above first</option>
<?php
mysqli_select_db($dbConn, $database_dbConn);
$query_hotelselect = "SELECT * FROM hotel GROUP BY Category";
$hotelselect = mysqli_query($dbConn, $query_hotelselect) or die(mysqli_error($dbConn));
$row_hotelselect = mysqli_fetch_assoc($hotelselect);
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value='" . $row_hotelselect['Category'] . "'> " . $row_hotelselect['Category'] . " </option>";
}
?>
</select>
<?php
echo $row_hotelselect;
?>
</div>
<div class="col-sm-3" id="fetchHotelNameByAreaResult">
<select class="form-control">
<option value="0">Please select area above first</option>
</select>
</div>
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "getter.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue', HotelArea);
xhttp.open('POST', url, true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
</div>
getter.php
<?php
if ($_POST['SearchValue']) {
$searchname = $_POST['SearchValue'];
require_once('Connections/dbConn.php');
mysqli_select_db($dbConn, $database_dbConn);
$query_preferredhotel = "SELECT * FROM hotel WHERE Category = '$searchname'";
$preferredhotel = mysqli_query($dbConn, $query_preferredhotel) or die("Could not select examples");
$row_preferredhotel = mysqli_fetch_assoc($preferredhotel);
echo'<select class="form-control" name="preferredHotel">';
while ($row_preferredhotel = mysqli_fetch_assoc($preferredhotel)) {
echo "<option value='" . $row_preferredhotel['Name'] . "'> " . $row_preferredhotel['Name'] . " </option>";
}
}echo '</select>';
?>
Kinda got stuck here after making the dropdown list appear. I found an article on https://css-tricks.com/dynamic-dropdowns/ but they do not have the example for the database and I was hoping someone could help me with this as I understand I would most likely need AJAX to request for data from the database/server and populate the second dropdown. Im not asking for spoonfeeding, but I really have very little clues about AJAX. Any guidance would be helpful!
EDITED
The issue with only part of the keywords being passed has been solved, thanks to Mark Ng spotting my markup error! I am really thankful for all your help in answering my questions, thank you!

sample concept.
There are 2 select(dropdown), the first will populate the second based on its category.
1st select
<select onchange="fetchHotelNameByArea(this.value)">
<option value="North">North</option>
<option value="South">South</option>
<option value="East">East</option>
<option value="West">West</option>
</select>
2nd select(to be populated by javascript later)
<div id="fetchHotelNameByAreaResult">
<!--For temporary only, this select was purposely placed inside this div id, it will get re-written by javascript when result are generated-->
<select>
<option value="0">Please select area above first</option>
</select>
</div>
JS(Native)
<script>
function fetchHotelNameByArea(HotelArea) {
//above (HotelArea) are actually the value (this.value) in the form which will be what the user select (North, South, East or West)
var xhttp = new XMLHttpRequest();
var url = "./php/find_hotel_name_by_area.php";//<- just a sample url
var data = new FormData();
//below will "assign HotelArea to $_POST['SearchValue']"
data.append('SearchValue',HotelArea);
xhttp.open('POST',url,true);
xhttp.send(data);
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("fetchHotelNameByAreaResult").innerHTML = xhttp.responseText;
}
}
}
</script>
php query (The select will be returned to div id="fetchHotelNameByAreaResult" by javascript
<?php
if($_POST['SearchValue']) {
$searchname = $_POST['SearchValue']
//.... your query
//"SELECT * FROM hotel WHERE Category = '$searchname'";
echo '<select class="blablabla">';
while ($row_hotelselect = mysqli_fetch_assoc($hotelselect)) {
echo "<option value=" . $row_hotelselect['id'] . "> " . $row_hotelselect['Name'] . " </option>";
}
}
echo '</select>';
?>
What is going on?
1. Upon 1st select, the onchange gets fired, calling function fetchHotel...
2. JS send data to server, where a php file will process the request, onreadystate... will detect if response is ready, and innerHTML will re-write whatever is in div id="fetchHotelNameByAreaResult" with the resposeText generated by the php script.
There are other ways to do it via jQuery, etc. But once you get the basic concept, you are ready to move on.
EDIT to address this issue.
Hey there again, the codes above works fine. But however, I realised
that the dropdown list only passes one part of the value inside the
variable (eg. ritz carlton, only passes ritz to the next form). Anyone
aware of any solutions?
There is a html markup error.
echo "<option value=" . $var . ">" . $var . "</option>";
//The above will return <option value=ritz carlton>ritz carlton</option> in html.
//the problem lies with value=ritz carlton as there is a space in between.
//html will think that it is value="ritz" while carlton is not a valid attribute, it will simply ignore it and only set the value as ritz, so only the value ritz was posted.
//In order to get the full string parse, you have to quote them like below.
echo "<option value='". $var ."'>" . $var . "</option>";
// echo "<option value=" . "'" . $var . "'" . "</option>";
// echo "<option value=/" " . $var . " /"</option>";
//a lot more ways to achieve same result.
//These will return <option value="ritz carlton">ritz carlton</option> in html. This will set the value as ritz carlton and the value "ritz carlton" will be posted.
?>

I read your question and understood your problem.
Basic steps :
First create a section behind your first drop down in which hotel name will be fetched according to the category selected in first drop down.
Example :
<div class = "hotelDropDown">
// hotel drop down
</div>
After, create an ajax request that will fetch the category name from first drop down and will send the request to the php file to fetch the hotel name correspinding to the selected category name and make the drop down.
Example :
$.ajax({
url : "hotelfetch.php",// function to create hotel dropdown
data : {categoryName : $('.hotelCategory').val()}
success :
function(data){
//generate dropdown of hotel name
});
});
Make a view file of hotelfetch.php in which you create a dropdown of hotel name according to fetched category name and replace it in the html of the section created below category drop down which I created for you.

Related

Filtering dropdown based on another dropdown selection

I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns on index.php:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Collector Name'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
Code that runs each time the dropdown is changed in script tags on index.php:
function showUser(str) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('billing_table');
sorttable.makeSortable(newTableObject);
}
}
// ---- Gets value of collector dropdown selection -----
var e = document.getElementById("collector").value;
$.ajax({
type: 'GET',
url: 'index.php',
data: e,
success: function(response) {
console.log(e);
}
});
// ---- Gets value of the current selection in any of the dropdowns ----
xmlhttp.open("GET","dropdown-display.php?q="+str,true);
xmlhttp.send();
document.getElementById('billing_table').style.display = 'none';
}
$(document).ready(function(){
var $select1 = $( '#collector' ),
$select2 = $( '#date' ),
$options = $select2.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $options.filter( '[value="' + this.value + '"]' ) );
}).trigger( 'change' );
});
Query on my index.php page:
$collector = "SELECT [Collector Name]
FROM [vSpecial_Billing]
Group By [Collector Name]";
$billdate = "SELECT [Collector Name], [Date]
FROM [vSpecial_Billing]
Group By [Collector Name], [Date]";
I don't want to send the value to my dropdown-display.php page since my queries that populate the dropdowns are on my index.php page. However, if I put the value variable in the query, then it runs that query on load before a collector selection can be made and my bill date dropdown will then not be populated.
EDIT:
I changed the value in the options for the date dropdown to Collector Name instead of Date
I also added the $(document).ready(function() at the end of the middle block of code
I updated the queries that I am using
It filters correctly now, however, on page load, the bill date is unable to selected. It is not populated with any rows. How can I change this?
Also, when I filter it, it defaults to the last date on the list. How can I get it to default to a hardcoded value such as "Date" and then the user can select from the filtered values?
I wrote up a test case, using some example data, and made sure this works. Its a rough example, but I believe its doing what you need. With a lot less cruft in the works. I'm sorry, but I used full jquery, because I cannot be bothered to do long-hand javascript anymore haha (plus I couldn't really follow what you had going on in there).
There will need to be two files: index.php and index-ajax.php (for clarity)
index.php brief:
// note: these do not need to be in prepared statements (theres no variables inside)
$collect = $db->query("SELECT DISTINCT [Collector Name] FROM [vSpecial_Billing]");
$names = $collect->fetchAll();
$billdate = $db->query("SELECT DISTINCT [Date] FROM [vSpecial_Billing]");
$dates = $billdate->fetchAll();
?>
<form id="testForm" action="">
<select id="collector">
<option value="" selected="selected" disabled="disabled">Collector Name</option>
<?php foreach($names as $name) { ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date">
<option value="" selected="selected" disabled="disabled">Bill Date</option>
<?php foreach($dates as $date) { ?>
<option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
<input type="button" id="clearchoices" name="clearchoices" value="Clear Choices" />
</form>
Some things to note in the above:
You only need to select by DISTINCT. No need to do GROUP BY to get all unique names, or all unique dates.
I put the results of fetchAll into variables, out of habit, but you can move them into the foreach if you wish.
I removed the class defines you had, because a class with spaces in it (in the case of a Collector Name) can be buggy.
The Clear Choices button is just an example of how to reset those selects after they get filtered and filtered beyond what you can select.
This is the javascript portion (it goes in index.php before or after your form, or in the head):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#collector").change(function(e){
$.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
$("#date .choice").hide();
$.each(data, function(key,row) {
// $("#date option[value='"+ row.item +"']").show();
$("#date option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#date").change(function(e){
$.post('index-ajax.php',{filter:'Date',by:$(this).val()},function(data){
$("#collector .choice").hide();
$.each(data, function(key,row) {
// $("#collector option[value='"+ row.item +"']").show();
$("#collector option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#clearchoices").click(function(e){ e.preventDefault();
$("#collector .choice").show(); $("#collector").val('');
$("#date .choice").show(); $("#date").val('');
});
});
</script>
That block needs a lot of explaining, because I took all your long-hand javascript and packed it into jquery.
Each select has its own handler event for when it changes.
Each select does its own post ajax, with a different variable define to filter on.
After the ajax returns, it hides all options in the OTHER select. Then enables all options which are returned by the json data of the ajax call. This could be handled differently, but I wanted to present one way of doing it.
A key thing is setting "JSON" for the return handler of the .post() methods. You'll see why in index-ajax.php.
And now the index-ajax.php:
if (isset($_POST['filter']) and isset($_POST['by'])) {// sanity check
$results = array();
if (!empty($_POST['by'])) {
// these _DO_ need to be in prepared statements!!!
if ($_POST['filter'] == 'Name') { $sql = "SELECT DISTINCT [Date] as item FROM [vSpecial_Billing] WHERE [Collector Name] = ?"; }
if ($_POST['filter'] == 'Date') { $sql = "SELECT DISTINCT [Collector Name] as item FROM [vSpecial_Billing] WHERE [Date] = ?"; }
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['by']));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $results[] = $row; }
}
echo json_encode( $results );
exit;
}
This bit of code is actually pretty straightforward. All it does is determine which filter operation to do, prepares the sql, and then grabs distinct matching rows for output. The key thing though is it outputs as json, so the javascript that called this can handle the data easier!
Now... I had built all this in a test script, and my server hates "fetchAll", so your milage may vary on some of the DB code. I also left out all other form code and db setup handlers and all that. Figuring you have a handle on that.
I hope this helps you out, in some way or other.
EDIT 11/7
I made a slight change because I didn't realize the Collector Names in your db would have characters that would break all of this, oops. Two changes for odd character handling:
The select for collector has its option values wrapped in htmlspecialchars().
The jquery portion for where each select .change event filters, is now filtering by looking for a matching index, using the row.item as a direct variable. Before, it was using it in a value=' row.item ' match, which if the row.item had single quotes (or other bad chars), it would break the whole js event and fail!
Generally when I setup things like this, I use ID's and unique element id tags. That way I am only ever referencing by numbers, and wont run into odd character mash. An example of switching everything to ID's would be involved, and I think you have the gist of whats going on now.

how to change a value of a php variable with ajax or jquery?

so I make a small php app and I try to use ajax.
I have two lists :
<select name="auteur" id="auteur" >
<option value='-1'>Aucun auteur</option>
<?php
require("bd/bd.inc.php");
$resA = listeAuteurs();
while ($rowA = $resA->fetch()) {
echo "<option value='" . $rowA["id"] . "'>" . $rowA["nom"] . "</option>";
}
?>
</select>
And
<select id="livre" name="livre">
<option value="-1">
Aucun livre
</option>
<?php
$idAuteur = NULL;
require("bd/bd.inc.php");
$resL = listeLivres($idAuteur);
while ($rowL = $resL->fetch()) {
echo "<option value='" . $rowL["idLivre"] . "'>" . $rowL["titre"] . "</option>";
}
?>
</select>
In my ajax.js file I get the value of the slected option of the first list with this code :var validauteur = $( "#auteur" ).val();
And what I want is to modify the value of the variable "$idAuteur" in the second list with the value of the selected option of the first list.
Hope you can help.
You can't use AJAX to edit the PHP variable of a page that has already loaded - but you can use AJAX to trigger a JS function (on success) which will edit the second input.
In your AJAX success return, add some JS code to edit the second select box:
$( "#livre" ).html(...);
What you actually want to change it to is upto you.

Second dependent dropdown isn't getting filled with data

I'm trying to make a grade distributions website, and I'm creating 4 dropdowns correlating subject (cs, math, etc.), class (data structures, AI, etc.), professor, and quarter the class was taken. After the quarter dropdown is selected, I want to display a bar graph with the data.
The problem I'm running into is that I can't populate the second dropdown with data Basically, I can successfully pull data from the database for the first dropdown, and if the user selects something then the second dropdown (that was originally hidden using jquery) becomes visible, but it isn't properly pulling data from the database and adding it as options to the second dropdown. An example would be that I can select Computer Science from the first dropdown, then the second dropdown is visible, but it doesn't contain 'intro to programming', 'data structures', etc. in it; instead, it's just blank.
FYI, I'm using these selectpickers: http://silviomoreto.github.io/bootstrap-select/
PHP (error is most likely somewhere in the getClasses function, quite possibly the $_POST section of the code):
<?php
function getSubjects()
{
/* Get mysql connect information from external file and connect*/
require_once 'database.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
/* Get the column containing the subjects from the table */
$query = 'SELECT DISTINCT Subject FROM gradelist ORDER BY Subject';
$result = $connection->query($query);
if(!$result) die ($connection_error);
/* Keep track of the number of rows in the column; necessary for iterating */
$rows = $result->num_rows;
/* selectBar keeps track of the html code for the select Bar*/
$selectBar = '';
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Subject'];
$selectBar .= '<option>' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
}
function getClasses()
{
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
if(isset($_POST['subject']))
{
$query = "SELECT DISTINCT Class FROM gradelist WHERE Subject = $subject";
$result = $connection->query($query);
if(!$result) die ($connection_error);
}
else
{
die($connection_error);
}
$rows = $result->num_rows;
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Class'];
$selectBar .= '<option value = "' . $value . '">' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
} ?>
HTML Portion of the code (again, the error might be with the $_POST part of the code) :
<form class="form-horizontal" method = "post" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "subject" id="subject" class="selectpicker show-tick form-control" data-live-search="true" title ="Subject">
<?php echo getSubjects(); ?>
</select>
</div>
</div>
</form>
<form class="form-horizontal" method = "get" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "class" id="class" class="selectpicker show-tick form-control" data-live-search="true" title ="Class">
<?php if(isset($_POST['subject'])) echo getClasses(); ?>
</select>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#class').selectpicker('hide');
$('#professor').selectpicker('hide');
$('#quarter').selectpicker('hide');
});
$('#subject').on('change', function(){
$('#class').selectpicker('refresh');
$('#class').selectpicker('show');
});
$('#class').on('change', function(){
$('#professor').selectpicker('show');
});
$('#professor').on('change', function(){
$('#quarter').selectpicker('show');
});
$('#quarter').on('change', function(){
showTable();
temp = $('#class').selectpicker('val') + " with " + $('#professor').selectpicker('val') + " during " + $('#quarter').selectpicker('val');
$('#displayName').text(temp);
});
Your PHP is executed with $_POST["subject"] not set, and you never POST the subject the user chose to the page; if you don't make an additional POST request, there's no way for the classes to populate.
One way to do it (without changing any of your files) is like so:
$('#subject').on('change', function(){
$.post({
data: { subject: $(this).val() },
success: function (data) {
var classes = $(data).find("#class");
$("#class").replaceWith(classes);
}
});
});
So when a change event is triggered on the subject selection, we'll POST the selected subject to the current page. The response should be the entire document generated with the class selection filled (since $_POST["subject"] is set).
We then replace the current page's #class select element with the version in the generated data (wrapped in $() to create DOM elements from the stringified HTML, so we can use find()).
Another way might be to have files, getSubjects.php, getClasses.php, and so on, and POST individually to them (you make the first request onload, and subsequent requests onchange). This way, you can just append the generated option elements to the select elements on the page.
ALSO: Please please please sanitize $_POST["subject"] before using it in a database query. A user could easily add a fake option to the select locally with a malicious string for value, and you'd unknowingly query the DB with that. You can use prepared statements for this (mysqli has the prepare() function to prepare a statement before querying). More on that and combating SQL injection here.

redirect to different URL with same form

i am new to PHP and trying to arrive with similar functionality given in URL.
i have a form with four select options, result will be retrived when last option selected.
my current code is :
{
$result = mysql_query($query,$con);
if(!$result)
echo mysql_error();
$option = "";
while($row = mysql_fetch_assoc($result)) {
$option .= '<option value = "'.str_replace(' ', '_', $row['bankname']).'">'.$row['bankname'].'</option>';
}
str_replace(' ', '_', $row['bankname'])
?>
<form method = "POST" action = "">
<select name = "bank" onChange="document.location.href=bank[selectedIndex].value">
<?php echo $option; ?>
</select>
</form>
}
Probably i am asking very high level question, but please help.
Regards,
Anitha
You can send the first time using ajax, and whem the ajax is sucess you can change the submit the form again returning true.
If I got the question right, you are not looking for loading options into select box, but trying to look for a solution where the last select box have values:
<select id = 'finalSelect'>
<option value='http://aaaa.com'>A<option>
<option value='http://bbbb.com'>B<option>
<option value='http://cccc.com'>C<option>
</select>
and based on the user selection your page should redirect to aaaa.com, bbbb.com or cccc.com.
If I am right about your requirement, all you have to do is:
<select id = 'finalSelect' ONCHANGE="location = this.options[this.selectedIndex].value;>
<option value='http://aaaa.com'>A<option>
<option value='http://bbbb.com'>B<option>
<option value='http://cccc.com'>C<option>
</select>

JQuery/PHP Dynamic Dropdown Issue

I've been building a script for dynamic dropdowns using PHP and JQuery and I'm having an issue with some of the data being sent from the form to be queried. Basically the user will choose an option from the first box and from there ever other box is dependent on the previous. The options are pulled from a MySQL database and as these same options are being picked they are sent back to the script to create the next query and so on. I'm having issues with some of the data and I think it's because there are spaces in the options being sent through GET. I've looked over my script many times the past few days and I just can't find a solution.
Here is a live version of my script to test. - That's the url for a live version of the script to check out.
Here is the front-end. A pretty basic form and some javascript to send the information to the back-end script:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#series").change(function() {
$("#range").load("findbackend.php?series=" + $("#series").val());
});
$("#range").change(function() {
$("#digsize").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val());
});
$("#digsize").change(function() {
$("#dignum").load("findbackend.php?series=" + $("#series").val() + "&range=" + $("#range").val() + "&digsize=" + $("#digsize").val());
});
});
</script>
</head>
<body>
<select id="series">
<option selected value="base">Please Select</option>
<option value="FM800">FM800</option>
<option value="F100">F100</option>
</select>
<br>
<select id="range">
<option>Please choose from above</option>
</select>
<br>
<select id="digsize">
<option>Please choose from above</option>
</select>
<br>
<select id="dignum">
<option>Please choose from above</option>
</select>
</body>
</html>
And here is the back-end I've come up up with:
<?php
//\\ MODULAR DEPENDANT DROPDOWNS \\//
//creates DB connection
$dbHost = 'host';
$dbUser = 'user';
$dbPass = 'pass';
$dbDatabase = 'database';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
$series = mysql_real_escape_string($_GET['series']);
isset($_GET['range'])?$range = mysql_real_escape_string($_GET['range']):"";
isset($_GET['digsize'])?$digsize = mysql_real_escape_string($_GET['digsize']):"";
isset($_GET['dignum'])?$dignum = mysql_real_escape_string($_GET['dignum']):"";
//forms the query depending on what data is recieved through GET
if (isset($_GET['dignum'])) {
$query = "SELECT DISTINCT * FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' AND dig_num='$dignum' ORDER BY sio";
} elseif (isset($_GET['digsize'])) {
$query = "SELECT DISTINCT dig_num FROM meters WHERE series='$series' AND sio='$range' AND dig_size='$digsize' ORDER BY sio";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT dig_size FROM meters WHERE series='$series' AND sio='$range' ORDER BY sio";
} else {
$query = "SELECT DISTINCT sio FROM meters WHERE series='$series' ORDER BY sio";
}
//creates a result array from query results
$result = mysql_query($query);
//outputs dropdown options dependent on what GET variables are set
if (isset($_GET['digsize'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'dig_num'} . "'>" . $row{'dig_num'} . "</option>";
}
} elseif (isset($_GET['range'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'dig_size'} . "'>" . $row{'dig_size'} . "</option>";
}
} else {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
}
}
?>
Again, new.foxmeter.com/find.php is a live version of my script to check out.
This is a monospaced snippet of my table that I'm pulling data from: i.imgur.com/IOT9RUF.png
Thanks in advance for any help!
Your instincts were right, the problem is with non-escaped characters (url encoding). For debugging AJAX calls you should use your browser's console (I highly recommend FireBug, but to each his own).
Before you send the parameters via AJAX, you have to encode them using encodeURI(). For example:
$("#series").change(function() {
var val = document.getElementById('series').value;
// $("#series").val() == document.getElementById('series').value
// but the latter is faster!
$("#range").load(encodeURI("findbackend.php?series=" + val));
});
You would also have to adjust your other .change function calls accordingly. Since the data your PHP script will receive has been encoded, you need to decode it using urldecode(). Example:
$series = mysql_real_escape_string(urldecode($_GET['series']));
This should work just fine.
On a side note, you are using a deprecated MySQL API, you should use MySQLi or PDO. Also, your jQuery calls could do with some caching (you create the $("#series") object three separate times).
the easy way to use ajax so you need two php pages and one js at least
the first php will have the first dropdown and then send it`s value to the second php by ajax
it's simply example
first php code like this
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="dropdown.js"></script>
</head>
<body>
<select name="first" id="first">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<div id="second"></div>
</body>
</html>
dropdown2.php code is
<?php
if(isset($_GET['first'])){
$first=$_GET['first'];
echo"
<select name='second' id='secondselect'>
<option value='4'>$first a</option>
<option value='5'>$first b</option>
<option value='6'>$first c</option>
</select>
";
}
?>
and dropdown.js
$(document).ready(function(){
$("#first").change(function(){
str=$("#first").val();
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","dropdown2.php?first="+str,false);
xmlhttp.send();
document.getElementById("second").innerHTML=xmlhttp.responseText;
});
});

Categories