I've created a dynamic dropdown using JS/PHP/MySQL but it seems I'm having some problems with UTF8 decoding in my PHP. The script is going to be used to make a small application that helps my customers find a product that meets their criteria. We sell panel meters that can accept different ranges of input and many are denoted with a +/- or a value (example: a meter can expect to process a voltage +/- 10V around a specified voltage.) Everything is starting to work great in my script except when some characters are parsed through (+, / , ±, ½, etc.) My database originally used ± to denote plus or minus but I then switched to +/- (three characters) in hopes that it would fix the special character problem but it didn't...
Using console.log I've figured out that my JS is encoding the special characters correctly but once it gets to my PHP it doesn't decode properly.
Everything along the way is set to UTF8
So now I still need to figure out why some things are not parsing right.
You can view a live version of the script at http://new.foxmeter.com/find.php.
This is the important part of my frontend
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#range").load(encodeURI("findbackend.php?type=" + tval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#power").load(encodeURI("findbackend.php?range=" + rval));
console.log(encodeURIComponent(document.getElementById('range').value));
});
$("#power").change(function() {
//var rval = document.getElementById('range').value;
psval = document.getElementById('power').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval + "&power=" + psval));
});
$("#setpoint").change(function() {
//var rval = document.getElementById('range').value;
//var psval = document.getElementById('power').value;
stval = document.getElementById('setpoint').value;
$("#output").load(encodeURI("findbackend.php?range=" + rval + "&power=" + psval + "&setpoint=" + stval));
});
});
</script>
</head>
<body>
<!-- Google Analytics Script -->
<?php include_once("scripts/analyticstracking.php") ?>
<div class="wrapper"> <!-- Sticky Footer Wrapper -->
<div id="panorama"></div>
<div id="header">
<?php include("include/header/banner.php") ?>
<?php include("include/header/nav.php") ?>
<?php include("include/header/quicksearch.php") ?>
</div>
<div id="content">
<div id="findoptions">
<select id="type" class="finddrops">
<option selected value="base">Please Select</option>
<option value="DC Voltage">DC Voltage</option>
<option value="DC Current">DC Current</option>
<option value="AC Voltage">AC Voltage</option>
<option value="AC Current">AC Current</option>
<option value="Strainguage">Strainguage</option>
</select>
<br>
<select id="range" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="power" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="setpoint" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="output" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="blarg" class="finddrops">
<option>Please choose from above</option>
</select>
</div>
<div id="findresults" class="finddrops">
</div>
</div>
</div>
And this is my PHP running on the backend:
<?php
//\\ MODULAR DEPENDANT DROPDOWNS \\//
//creates DB connection
$dbHost = 'host';
$dbUser = 'user';
$dbPass = 'password';
$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
//any order
$type = mysql_real_escape_string(urldecode($_GET['type']));
isset($_GET['range'])?$range = mysql_real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['power'])?$power = mysql_real_escape_string(urldecode($_GET['power'])):"";
isset($_GET['setpoint'])?$setpoint = mysql_real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} else {
$query = "SELECT DISTINCT sio FROM meters WHERE sit LIKE '%$type%' ORDER BY model";
}
//creates a result array from query results
$result = mysql_query($query);
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['power'])) {
echo "<option>Choose Setpoint Options</option>";
while ($row = mysql_fetch_array($result)) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['range'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'pso'} . "'>" . $row{'pso'} . "</option>";
}
} else {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
}
}
//Thanks to Chris Coyier for the wonderful examples on CSS-Tricks
//A Web Application by Zach Klemp
?>
Again, you can view the script here.
Choose DC Voltage in the first dropdown and then a +/- option in the second the see where the problem begins. When you choose Straingauge in the first dropdown and then click '30 mV with 10 V DC excitation' it parses through fine. (And as an aside another problem I have is that choosing the first result without clicking another first doesn't trigger the .change)
Thanks for any and all help getting this to work! I've been trying to figure this out for a bit now and haven't come up with a solution.
Try this in your PHP file :
Replace any echo XXXX; with utf8_decode(XXXX)
It should make it works
$string = ';http%3A%2F%2Fwww.google.com%2F%3Fq%3Dtesting%2Burldecode';
echo urldecode($string); // http://www.google.com/?q=testing+urldecode
For further reading, see the official PHP documentation on urldecode here.
Related
<body>
<H1>4a</H1>
<form action="hw4b.php" method="post">
<?php
$con = mysqli_connect("localhost","[credential]","","[credential]")
or die("Failed to connect to database " . mysqli_error());
?>
<select name="id" value="id">
<script>
for (x=1;x<=101;x++)
{
document.write("<option value="+x+">"+
<?php echo mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE CUSTOMERID == "+x+";")?>
+"</option>");
}
</script>
</select>
<input type="submit" value="SEND IT">
</form>
</body>
So this should put the corresponding LASTNAME into the select, but it just fills every row with "NaN". I'm sure this is some stupid minor error, but I've been staring at it too long.
you should query the results of mysqli_query
do something like this:
<select name="id" value="id">
<?php
$query = mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE WHERE CUSTOMERID >=1 and CUSTOMERID <= 101 ;");
while ($row = mysqli_fetch_array($query))
echo "<option id='".$row['LASTNAME']."'>".$row['LASTNAME']."</option>";
?>
</select>
notes:
no need for javascript usage
please escape the query parameter
id of the option is the value that will be sent to the server, makes more since to send LASTNAME
avoid using a query at a loop
Note that your for cycle is in javascript (between <script> tags), yet you try to fill in some data in php.
Everything in PHP happens on server side, i.e. is interpreted, packed into a http response and returned to the client, where it is unpacked and javascript is executed.
You need to either put both into javascript, or both into php.
<select>
<?php
for ($i = 0; $i < 100; i++){
///make some select here
echo "<option value="$i"> ...output the select </option>"
}
?>
</select>
This way, all options are generated on server side and transferred to client as text
<select>
<option value="0">...</option>
<option value="1">...</option>
...
Other option is to export the database data into javascript, and then access it in javascript.
<script>
//or perhaps better
var myOtherData = <?=json_encode($somePHPData)?>;
</script>
//now you can use for loop with document.write and one of the variables you exported...
You need to be very careful and sure which execution happens on server, and which on client side.
There are several issues I think. You are using a comparison operator in the SELECT statement, it should just be =, not ==. Also, mysqli_query returns a mysqli_result, not a value like "Johnson" for LASTNAME. And, maybe most importantly, it doesn't make sense to do this with javascript since you're writing the values to the document before sending it to the browser anyway.
The code should look something like this (not tested)
<select name="id" value="id">
<?php
$query = 'SELECT LASTNAME, CUSTOMERID FROM CUSTOMERS WHERE CUSTOMERID >= 1 AND CUSTOMERID <= 101 ORDER BY CUSTOMERID ASC';
$result = mysqli_query($con, $query);
if (!$result) {
echo 'some error handling';
} else {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['CUSTOMERID'] . '">' . $row['LASTNAME'] . '</option>';
}
}
?>
</select>
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.
After selecting an option from first dropdown list then another dropdown list appear according to selected option. When an option is selected from the second one then the selected one's value is sent to input element that is at the top of the page as hidden. It also calls function "bolumGonder" which submits form that includes input element to same page with GET method. Then according to GET variable retrieve some data from database.
PHP
<?php
session_start();
if (isset($_GET['bolumtani']) && !empty($_GET['bolumtani'])) {
include_once 'alinabilendersler.php';
}
?>
HTML
<script>
function bolumGonder() {
var seciliBolum = $(".insaat").val();
if ( seciliBolum.length > 0 ) {
$("#bolumtani").val(seciliBolum);
document.bolumtaniform.submit();
}
}
</script>
<form name="bolumtaniform" action="program.php" method="GET">
<input name="bolumtani" id="bolumtani" type="text" style="display:none" />
</form>
<div id="orta_div">
<select class="fakulte_sec" onclick = "bolumAc()">
<option selected>Fakülte</option>
<option value="insaat">İnşaat Fakültesi</option>
<option value="mimarlik">Mimarlık Fakültesi</option>
<option>Makina Fakültesi</option>
<option>Uçak ve Uzay Bilimleri Fakültesi</option>
</select>
<select class="insaat" style="display:none" onchange="bolumGonder()">
<option value="" selected>Bölüm</option>
<option value="ins">İnşaat Mühendisliği %30</option>
<option value="inse">İnşaat Mühendisliği %100</option>
<option>Çevre Mühendisliği %30</option>
<option>Çevre Mühendisliği %100</option>
</select>
<select class="mimarlik" style="display:none">
<option>Mimarlık %30</option>
<option>İnşaat Mühendisliği %100</option>
<option>Çevre Mühendisliği %30</option>
<option>Çevre Mühendisliği %100</option>
</select>
<div class="uygun_dersler_ana_div" style="width:100%; color: white; height: 1500px;position: absolute ;overflow: hidden"><?php if (isset($_GET['bolumtani']) && !empty($_GET['bolumtani'])) {$sonuc = bolum($_GET['bolumtani']);} else {}?></div>
</div>
Gettin data from MySQL
<?php
##Database Bağlantısı##
$host = 'host';
$user = 'username';
$pass = 'password';
$db = 'databasename';
$baglan = mysql_connect($host, $user, $pass);
mysql_select_db($db);
mysql_query("SET NAMES 'utf8' ");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_turkish_ci' ");
## Her Ders İçin Ayrı Tablo Oluştur ##
function bolum($degisken) {
# Ders Kodlarını Al # # Gets Class Name From Another Website, Asign them into an array ##
$ch = curl_init("someURL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
#$dom->loadHTML($cl);
$xpath = new DOMXpath($dom);
$derskodlari = $xpath->query("//option[position() >1]");
$todbderskodlariarr = array();
foreach ($derskodlari as $derskodu) {
$todbderskodlariarr[] = $derskodu;
}
$todbderskodu = array();
foreach ($todbderskodlariarr as $todbderskoduarr) {
$todbderskodu[] = $todbderskoduarr->nodeValue;
}
## This is just an exception. ##
$todbderskodu[81] = "MODD";
for ($a = 0; $a < count($todbderskodu); $a++) {
#$todbderskodu[$a] = mysql_query("SELECt crnler, derskodu, gun, bina, dersadi FROM $todbderskodu[$a] WHERE dersialabilen LIKE '%" . $bolum . "%'");
}
$a = 0;
while ($a < count($todbderskodu)) {
while ($row = mysql_fetch_array($todbderskodu[$a], MYSQL_NUM)) {
$class = substr($row[1], 0, 3);
echo '<div class="' . $class . '" id="' . $row[0] . '">' . $row[4] . $row[0] . ' |' . $row[2] . '</div>';
}
echo '<br>';
$a = $a + 1;
}
}
?>
Upto now everything works perfect. Script creates divs that have class AKM,ALM,ATA,UCK.. etc. I want to put all divs that have same class into classname_main_div. How can i do that?
use the class of the looped divs and append to the other div like:
$(".looped-divs").appendTo(".container-div");
Hope that helps
cheers!
PD: remember to scape the GET variables to avoid SQL injection
Hi I am trying to create a set of drop down boxes that will use an array of data from the values that you pick and then runs through a loop to post them to the screen at the moment the data that i want to use will just be local but i want to edit this later so that it will loop through the data from my database and post that to the screen. i have looked at other questions on this subject and just wondering how i would change it for my code i have looked at this link questions on stack overflow that I have looked at i have just got a couple questions that im wondering if anybody has seen this before or if they have seen any examples i have also looked at for loops and i understand the concept
my questions to you are:
1) how would I post the values from my drop down boxes into a php array
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
3)Would I need to use a second language like javascript or can it be done just in php
My drop down box code is
<div id="Content">
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="%">any...</option>
</select>
<br /><br />
Choose a principle:<br />
<select id="principle">
<option value="%">any...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<!-- end of the Options -->
below is the select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM subject";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM section WHERE subject_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description'] . '</option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT * FROM principle WHERE section_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'] . '</option>';
}
return $principle;
}
}
$opt = new SelectList();
?>
1) how would I post the values from my drop down boxes into a php array
In the form tag add method="POST". Reference in PHP with $_POST array. Make sure to validate and escape the data before writing to your DB.
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
If you don't have millions of categories, you are better off sending them all as a JSON array and using Javascript. Something like:
<script>
var categories = <?php echo json_encode($opt->ShowCategory()); ?>;
</script>
json_encode may require some options to be set, depening on your character set. More info here: http://php.net/manual/en/function.json-encode.php
Making a new request each time someone changes a dropdown box will drive them crazy, I know I hate that. If you have used jQuery before, this is very easy. This isn't that difficult without it.
3)Would I need to use a second language like javascript or can it be done just in php
For the sake of your users, use Javascript.
code for showCategory()
...
$categories = new array();
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$categories[$row['subject_id']] = $row['description'];
}
$validCategories = $this->getValidCategories() // get the valid categories
foreach($categories as $index=>$cat){
// only choose the categories that are valid
if(array_search($cat,$validCategories) !== FALSE)
$category.= '<option value="'.$index.'">'.$cat.'</option>';
}
return $category;
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;
});
});