Dependent dropdowns not working, 2nd dropdown not loading - javascript

I need help with this one, i dont know why the sub cat wont load. but the first dropdown loads all the queries. i just dont know why it wont work with the 2nd one.
here is my index.php
<?php
include('config.php');
$query_parent = mysql_query("SELECT * FROM zipcodes GROUP BY major_area") or die("Query failed: ".mysql_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['major_area']; ?>"><?php echo $row['major_area']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>
and here is my loadsubcat.php
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$query = mysql_query("SELECT city FROM zipcodes WHERE major_area = {$parent_cat}") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[city]'>$row[city]</option>";
}
?>
please check my codes, and tell me where i did it wrong. it wont load for the 2nd drop down.

Try doing a simple AJAX function:
<script type="text/javascript">
function AjaxCall(ElemVal,PlaceId) {
$.ajax({
url: "loadsubcat.php?parent_cat="+$(ElemVal).val(),
success: function(result) {
$("#"+ PlaceId).html(result);
}
});
}
$(document).ready(function() {
$("#parent_cat").change(function() {
$("#sub-cat-load").html('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
AjaxCall(this,'sub-cat-load');
});
});
</script>
sub_cat container
<label>Sub Category</label>
<!-- NOTICE THIS PART -->
<div id="sub-cat-load"></div>
loadsubcat.php
<?php
include('config.php');
// You may want to sanitize this variable
$parent_cat = $_GET['parent_cat'];
$query = mysql_query("SELECT city FROM zipcodes WHERE major_area = {$parent_cat}") or die(mysql_error()); ?>
<select name="sub_cat" id="sub_cat"><?php
while($row = mysql_fetch_array($query)) { ?>
<option value="<?php echo $row[city]; ?>"><?php echo $row[city]; ?></option><?php
} ?>
</select>

Related

Can't get value of select list with Javascript when it is created using PHP array from database

If I generate a select list using PHP from the results of a database query, for some reason I can't then use Javascript to get the value of the currently selected item. I tested this code with a static list and it works no problem. Here is my code:
<?php
require_once("config.php");
$sql="SELECT * FROM animals ORDER BY name ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_UNIQUE); //each column is addressed by the primary key
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#animal_list").change(function(){
var animalValue = $(this).val();
window.location.href="animal_list.php?id=" + animalValue;
});
});
</script>
</head>
<body>
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?>
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
</body>
</html>
Testing with a static list works. Here is the example:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="fruits.php?id=" + fruitValue;
});
});
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo 'My Fruit <input type="text" id="myfruit" value="' . $_GET['id'] . '" readonly>';
}
else
echo 'My Fruit <input type="text" id="myfruit" value="" readonly>';
?>
</body>
</html>
remove onchange="listChange()" because is not defined and we dont need it.
and use $(this).find('option:selected').val(); for get value of option selected.
$("#animal_list").change(function(){
var animalValue = $(this).find('option:selected').val();
window.location.href="animal_list.php?id=" + animalValue;
});
First off I would clean this mess up.
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?> <!-- missing ; -->
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
Sorry I just can't deal with poorly formatted code, it makes reading it a chore. It just seems like so much wasted effort.
<select id="animal_list" name="animal_list">
<?php foreach($results as $res): ?>
<option value="<?php echo $res['id'];?>"><?php echo $res['name']; ?></option>
<?php endforeach; ?>
</select>
<br/><br/>
<?php
$readonly = '';
$npsw_code = '';
if(isset($_GET['id'])){
$readonly = ' readonly';
$npsw_code = $_GET['id'];
}
?>
<input type="text" id="npsw_code" value="<?php echo $npsw_code; ?>" <?php echo $readonly; ?>>
We'll also ignore this (missing ; ):
<?php echo $res['name'] ?>
Probably a syntax error, but see that's what happens when you cant read the code.
Javascript don't care how the HTML got in the page, only what the HTML looks like. Without knowing what it looks like, all we can do is guess. You can view source and see what it looks like.
Otherwise, put an alert in the on change handler and see what it says.
$("#animal_list").change(function(){
var animalValue = $(this).val();
alert(animalValue);
window.location.href="animal_list.php?id=" + animalValue;
});
Alert has the nice side effect of halting/pausing Javascript execution so it will interrupt the page redirect. This will tell you 2 things,
your event is being fired on change
the value is correct.
Never mind it was a typo. The column in my database was 'code' not 'id'. So it should have read . Sorry for wasting your time.

form action add page search

I have a problem
I hope you understand I write English badly:
I created a search field that contains these two files
index.php
<?php
include('db.php');
$keySesso = $_GET['sesso'];
$keyEta = $_GET['eta'];
$keyRegione = $_GET['regione'];
$keyFoto = $_GET['foto'];
//sesso
if(isset($keySesso)){
if ($keySesso == 2) {
$FemminaE="selected";
}else if ($keySesso == 1){
$MaschioE="selected";
}else if ($keySesso == 26){
$Gay="selected";
}else if ($keySesso == 27){
$Lesbica="selected";
}else if ($keySesso == 29){
$FemminaB="selected";
}else if ($keySesso == 28){
$MaschioB="selected";
}else{
$sessoN="";
}
}
//for total count data
$countSql = "SELECT COUNT(last_activity) FROM _core_members INNER JOIN _core_pfields_content ON _core_members.member_id = _core_pfields_content.member_id $whereSQL $keyRegione $CondizioneEta $CondizioneFoto ";
$tot_result = mysqli_query($conn, $countSql);
$row = mysqli_fetch_row($tot_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
//for first time load data
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM _core_members INNER JOIN _core_pfields_content ON _core_members.member_id = _core_pfields_content.member_id $whereSQL $keyRegione $CondizioneEta $CondizioneFoto ORDER BY last_activity DESC LIMIT $start_from, $limit";
$rs_result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<head>
</head>
<body >
<div class="BloccoBaseBO">
<div class="container" id="BOcontent">
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="tab1">
<form method='GET' id='FormChattaCon' class='FormBase' action=''>
<select id="SelectedSesso" name="sesso">
<option value="" <?php echo $sessoN; ?>>Tutti i generi</option>
<option value="2" <?php echo $FemminaE; ?>>femmine (Etero)</option>
<option value="1" <?php echo $MaschioE; ?>>maschi (Etero)</option>
<option value="26" <?php echo $Gay; ?>>Gay</option>
<option value="27" <?php echo $Lesbica; ?>>Lesbica</option>
<option value="29" <?php echo $FemminaB; ?>>Femmina (Bisex)</option>
<option value="28" <?php echo $MaschioB; ?>>Maschio (Bisex)</option>
</select>
<div class='ConFoto'>Con Foto: <input id="checkBox" name="foto" type="checkbox" onclick="javascript: submitform()" <?php echo $check;?>/> </div>
</form>
<table class="table table-bordered table-striped">
<tbody id="target-content">
<?php
while ($row = mysqli_fetch_assoc($rs_result)) {
echo "<div class='bloccoUserOnlineBO'></div><li class='NomeBloccoB'>$MemberName</li>";
};
?>
</tbody>
</table>
<nav><ul class="pagination">
<?php if(!empty($total_pages)):for($i=0; $i<=$total_pages; $i++):
if($i == 0):?>
<li class='active' id="<?php echo $i;?>"><a href='pagination.php?page=<?php echo $i;?>'><?php echo $i;?></a></li>
<?php else:?>
<li id="<?php echo $i;?>"><a href='pagination.php?page=<?php echo $i;?>'><?php echo $i;?></a></li>
<?php endif;?>
<?php endfor;endif;?>
</ul>
</nav>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $total_records;?>,
itemsOnPage: <?php echo $limit;?>,
cssStyle: 'light-theme',
currentPage : 0,
onPageClick : function(pageNumber) {
jQuery("#target-content").html('loading...');
jQuery("#target-content").load("pagination.php?page=" + pageNumber);
}
});
});
</script>
<!-- tab -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/jquery.scrolling-tabs.js"></script>
<script>
$('.nav-tabs').scrollingTabs();
</script>
<!-- FlexSlider -->
<script src="http://www..it/info-user-global/js/jquery.flexslider-min.js"></script>
<script src="http://www..it/info-user-global/js/main.js"></script>
the second where it is recalled from the pages
pagination.php
<?php
include('db.php');
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM ILFREE_core_members INNER JOIN ILFREE_core_pfields_content ON ILFREE_core_members.member_id = ILFREE_core_pfields_content.member_id $whereSQL $keyRegione $CondizioneEta $CondizioneFoto ORDER BY last_activity DESC LIMIT $start_from, $limit";
$rs_result = mysqli_query($conn, $sql);
?>
<?php
while ($row = mysqli_fetch_assoc($rs_result)) {
echo "<div class='bloccoUserOnlineBO'></div><li class='NomeBloccoB'>$MemberName</li>";
};
?>
The problem is this
When I compile the form, the result appears only on the index.php page
When I push the buttons on the bottom pages linked to the pagination.php page, I reset the form
enter image description here
I can not fix it because the form data will stop at the index page but when I call the pagination.php file through this:
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $total_records;?>,
itemsOnPage: <?php echo $limit;?>,
cssStyle: 'light-theme',
currentPage : 0,
onPageClick : function(pageNumber) {
jQuery("#target-content").html('loading...');
jQuery("#target-content").load("pagination.php?page=" + pageNumber);
}
});
});
</script>
I reset the form
Please help me
I hope I was clear
I also leave you an email, I am willing to pay for help
IlfreeIF#gmail.com
This is exactly what AJAX is for (AJAX can do the same .load() function can, but with more configurability):
http://www.seguetech.com/ajax-technology/
jQuery Ajax POST example with PHP

how to put dropdown result in textbox field in php

hi guys can anyone help me i have reach to my problem but i can't pass the value from div to input field which need please
page1.php
<!doctype html>
<?php
$conn = mysql_connect('localhost','root','') or die (mysql_error);
$db = mysql_select_db('employee', $conn) or die (mysql_error);
$select = "SELECT * FROM employee ";
$result = mysql_query($select);
$option = '';
while($row = mysql_fetch_assoc($result)){
$option .= '<option value="'.$row['id'].'">'.$row['employee_name'].'</option>';
}
?>
<html>
<head>
<title>Retrieve data from database using Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function getData(q, a){
$.ajax({
url: 'loademployeedata.php?empid='+q, //call storeemdata.php to store form data
success: function(html) {
var ajaxDisplay = document.getElementById(a);
ajaxDisplay.innerHTML = html;
}
});
}
$(document).ready(function(){
$("#tyt").live("change", function() {
$("#ab ").val($(this).find("option:selected").attr("value"));
});
});
</script>
</head>
<body>
<form method="post">
<select id="tyt" onchange="getData(this.value, 'dis')" >
<?php
echo $option;
?>
</select>
<div id="dis" >
</div><input name="" type="text" id="ab" >
</form>
</body>
second connecting page is
<?php
$empid = $_GET['empid'];
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("employee", $connection); // Selecting Database
if (isset($empid)) {
$query = " SELECT * FROM employee WHERE id = '$empid'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$a=$row['employee_salary'];?>
<?php echo $a; ?>
<?php }
}
mysql_close($connection); // Connection Closed
?>
i just need to put the value instead of div means into input field
Try something like this (untested):
<!doctype html>
<?php
$conn = mysql_connect('localhost','root','') or die (mysql_error);
$db = mysql_select_db('employee', $conn) or die (mysql_error);
$select = "SELECT * FROM employee ";
$result = mysql_query($select);
$option = '';
while($row = mysql_fetch_assoc($result)){
$option .= '<option value="'.$row['id'].'">'.$row['employee_name'].'</option>';
}
?>
<html>
<head>
<title>Retrieve data from database using Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("change", "#tyt", function() {
var tmp = $(this).val();
$("#ab").val(tmp);
$.ajax({
url: 'loademployeedata.php',
type: 'post',
data: 'empid='+q, //call storeemdata.php to store form data
success: function(recd) {
$('#a').val(recd);
}
});
});
});
</script>
</head>
<body>
<form method="post">
<select id="tyt" onchange="getData(this.value, 'dis')" >
<?php echo $option; ?>
</select>
<div id="dis"></div>
<input id="ab" type="text">
</form>
</body>

When I call my php script in another, Select js doesn't work

I have this code which works fine when ran standalone (I am able to search in the drop down list )
<?php
include_once ("db_connection.php");
$conn = testdb_connect ();
$sth = $conn->prepare('SELECT testCase FROM tooldata ');
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
$var=explode('_', $key);
$feature[] = $var[0];
}
}
$feature = array_intersect_key($feature, array_unique(array_map('strtolower', $feature)));
foreach($feature as $newarr)
{
$newFeature[]=$newarr;
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="../select2-3.4.8/select2.css" rel="stylesheet"/>
<script src="../select2-3.4.8/select2.js"></script>
<script>
$(document).ready(function() { $("#feature").select2(); });
</script>
</head>
<body>
<h2>Select feature</h2>
<form method="get" action="feature.php">
<select name="feature" id="feature">
<?php
?>
<option value > Select Feature</option>
<?php
foreach($newFeature as $feat)
{
?>
<option value="<?php echo $feat;?>"><?php echo $feat;?></option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Feature">
</body>
</html>
When I include this script in other php script say main.php and when I run main.php my search in the drop down list does not work and I get this in my net tab - Uncaught TypeError: undefined is not a function for line 7 and 37 which are include("feature_list.php"); and } respectively.
what can be the possible reason for this ?
please guide

Sequential jquery 'pages', third frame gives a reference error

I am quite new to javascript/jquery and having been playing around with the w3schools tutorials and the jquery documentation and made a page which will accept some user input and then via javascript print some output. I assumed i could modify this to work sequentially but when the second page should call the third page I get
ReferenceError: $gp is not defined
[Break On This Error]
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
I would appreciate if anyone has a trick to be able to use the $_get variable in the jquery script.
Code for pages:
first page (test.php):
<html>
<head>
<title>LeidenGlycoPeptide DataBase</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycoprotein').change(function() {
$('#txtField').load('getglycopeptides.php?gp='+$('.glycoprotein').val());
});
});
</script>
<body>
<h1>Welcome to the LeidenGlycoPeptide DataBase</h1>
<?php
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db('leidenGlycoPeptide') or die ();
$query = 'select protein from glycoPeptide';
$result = mysql_query($query);
mysql_close($link);
?>
<form>
<p>Select glycopeptide to search for (interactive dialog)</p>
<?php
echo"<select class=\"glycoprotein\">";
echo"<option value=\"\">select glycoprotein</option>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($line as $col_value) {
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo"</select>";
?>
</form>
<br>
<div id="txtField"></div>
</body>
</html>
Second Page (getglycopeptides.php):
<html>
<head>
<title>glyco</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycotype').change(function() {
//NOTE $q/q are undefined
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
});
});
</script>
<body>
<?php
// The next variable is the one I would like to use inside the jquery
$gp=$_GET["gp"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoType from run,glycoPeptide where run.id = glycoPeptide.id and glycoPeptide.protein like '".$gp."'";
$result = mysql_query($query);
?>
<form>
<?php
echo "<select class=\"glycotype\">";
echo "<option value=\"\">select glycosylation</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</form>
<br>
<div id="txtField2"></div>
</body>
</html>
The third page (getglycosites.php):
<html>
<head>
<title>sites</title>
</head>
<body>
<?php
$gp=$_GET["gp"];
$r=$_GET["r"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoSite from run,glycoPeptide where run.id = glycoPeptide.id and run.glycoType like '".$r."' and glycoPeptide.protein like '".$q."'";
//echo $query;
$result = mysql_query($query);
echo "<select name=\"site\" onchange=\"foo\">";
echo "<option value=\"\">select glycosite</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</body>
</html>
PS: The third page is currently only supposed to show a new select field but once I get this working it will be a part in a large sequential sequence.
Thanks in advance
I was able to 'fix' this by adding the following line (to the jquery script):
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
Making the total script part of the third page:
<script>
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
$(document).ready(function() {
$('.glycotype').change(function() {
$('#txtField2').load('getglycosites.php?q='+gp+'&r='+$('.glycotype').val());
});
});
</script>

Categories