I have no idea why my code isn't working. I basically have two dropdowns, the first is populated from an mssql database and I want the second dropdown to update dependant on the selection in the first.
Below is my code which populates a dropdown box:
<?php
session_start();
$serverName = "REDACTED";
$connectionInfo = array( "Database"=>"REDACTED", "UID"=>"REDACTED", "PWD"=>"REDACTED");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if (!isset($_SESSION['nID']))
{
header("Location: Login.php");
die();
}
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['region']."</option>";
}
return $output;
}
?>
I then use this to populate the first dropdown:
<p>Select a Region
<select name ="region" id ="region">
<option value ="">Select Region</option>
<?php echo loadRegion(); ?>
</select></p>
For the second dropdown box I have the following:
<p>Select a Territory
<select name="territory" id="territory">
<option value="">Select Territory</option>
</select></p>
I call my ajax via:
<script>
$(document).ready(function(){
alert("ready");
$('#region').change(function(){
var region_id = $(this).val();
$.ajax({
url:"getter.php",
method:"POST",
data:{regionId:region_id},
dataType:"text",
success:function(data){
$('#territory').html(data);
}
});
});
});
</script>
My getter page reads as follows:
<?php
session_start();
include 'config.php';
$output = '';
$sql = "SELECT distinct id,territory,rid FROM territoriesHaiss where RID = '".$_POST["regionId"]."' order by id";
$result = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$output = '<option value ="">Select Territory</option>';
while($row = sqlsrv_fetch_array($result))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['territory']."</option>";
}
echo $output;
?>
As pointed out by the 2 comments above (thanks again for the help!) the error was in the code that populates the first dropdown. It should have been a lowercase 'ID', like follows:
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['id'])."\">".$row['region']."</option>";
}
return $output;
}
?>
Related
Hi so the here is my question,
I have a Database containing Categories and Subcategories.
I have two dropdown boxes (select). I want them both to be populated by using PHP/MYSQL.
My Categories have been generated:
<select name="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
I want the subcategories to load when the category has changed.
My SQL will look something like this:
SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'
I need to get the value from the categories dropdown and store it as a variable.
In the past I have done something similar in javascript:
var subcat=document.forms["form"]['subcat'].value;
and then changed the value of another dropdown by calling an onChange(); function like:
document.getElementById('subcat').innerHTML='<option value=""></option>';
I hope someone can point me in the right direction! Should I be looking into AJAX, JavaScript or can it all be done with PHP?
Thank you.
add an id on category select box , like this -
<select name="prod_cat" id="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
for subcategory -
<select id='sub_cat' name='sub_cat'></select>
write your script something like this -
<script>
$("#prod_cat").change(function(){
//get category value
var cat_val = $("#prod_cat").val();
// put your ajax url here to fetch subcategory
var url = 'www.example/fetch_subcategory.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub_cat").html(data);
}
});
});
</script>
add code in ajax calling page -'www.example/fetch_subcategory.php'
<?php
$prod_cat = $_POST['cat_val'];
$sql = "SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg =.'<option value="'. $row["sub_cat_name"] .'">'. $row["sub_cat_name"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo $msg;
mysqli_close($conn);
?>
Do something like this, and hope it will work for you.
Hello I have installed jbusinessdirectory component for joomla, and I have module named mod_jbusinessdirectory (this is a search module for business listing) in tmpl/default.php file I have select code: (see below)
<?php if($params->get('showCategories')){ ?>
<div class="select">
<div class="categoryic"></div>
<select name="categorySearch" class="select-styled" id="categories">
<option value="0">category</option>
<?php foreach($categories as $category){?>
<option value="<?php echo $category->id?>" <?php echo $session->get('categorySearch')==$category->id && $preserve?" selected ":"" ?> ><?php echo $category->name?></option>
<?php if(!empty($category->subcategories)){?>
<?php foreach($category->subcategories as $subCat){?>
<option value="<?php echo $subCat->id?>" <?php echo $session->get('categorySearch')==$subCat->id && $preserve?" selected ":"" ?> >-- <?php echo $subCat->name?></option>
<?php }?>
<?php }?>
<?php }?>
</select>
</div>
<?php }?>
From this code I get categories and subcategories like this:
Main category 1
subcategory 1 subcategory 2 subcategory 3
Main category 2
subcategory 1 subcategory 2 subcategory 3
screenshot here: categories and sub categories screenshot
In helper.php I have functions that get categories and subcategories from database
static function getMainCategories(){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__jbusinessdirectory_categories where parent_id=1 and published=1 order by name';
$db->setQuery($query);
return $db->loadObjectList();
}
static function getSubCategories(){
$db = JFactory::getDBO();
$query = ' SELECT c.* FROM #__jbusinessdirectory_categories c
inner join #__jbusinessdirectory_categories cc on c.parent_id = cc.id where c.parent_id!=1 and cc.parent_id = 1 and c.published=1
order by c.name';
$db->setQuery($query,0,1000);
$result = $db->loadObjectList();
return $result;
}
And lastly in modjbusinesdirectory.php file I have the PHP like this:
if($params->get('showCategories')){
$categories = modJBusinessDirectoryHelper::getMainCategories();
if($params->get('showSubCategories')){
$subCategories = modJBusinessDirectoryHelper::getSubCategories();
foreach($categories as $category){
foreach($subCategories as $subCat){
if($category->id == $subCat->parent_id){
if(!isset($category->subcategories)){
$category->subcategories = array();
}
$category->subcategories[] = $subCat;
}
}
}
}
}
categories and subcategories table structure screenshot
here
My question is: How do I make Two select queries instead of one. Where in the first query I get the main categories and in the second query I get the subcategories (eg: if I choose from the first query the main category books and in the second query I choose children it has to show only books with the subcategory children books).
You can use below query for get categories.
function all_cat($id='',$child_of_child='parent')
{
$CI =& get_instance();
if($id="")
{
$query = $CI->db->get_where("__jbusinessdirectory_categories",array('parent_id'=>1));
}
else
{
$query = $CI->db->get_where("__jbusinessdirectory_categories",array('parent_id'=>$id));
}
//echo $CI->db->last_query()."<br>";
$op = '';
if($query->num_rows() > 0)
{
$res = $query->result();
//pr($res);
if($child_of_child == 'child')
{
$op .= '<ul class="sub_cat mrg-top-5" style="display:none;" id="'.$id.'">';
}
else
{
$op .= '<ul class="sub_cat " id="'.$id.'">';
}
foreach($res as $r)
{
$op .= '<li>'.ucwords($r->name).'
</li>';
$op .= all_cat($r->id,$child_of_child='child');
}
return $op .= '</ul>';
}
else
{
return $op;
}
}
It appears that the code already does what you want. You want 2 queries and there are 2. But, I think the result of these 2 queries combines into 1 result and you want to keep it spit into 2 results.
You will have to add new category functions that accept category ID parameters.
<?php
static function getCategoryById($id){
$id = intval( $id );
$db = JFactory::getDBO();
$query = '
SELECT *
FROM #__jbusinessdirectory_categories
WHERE
published=1
AND id= '.$id;
$db->setQuery($query);
return $db->loadObject();
}
static function getChildCategoryList($id){
$id = intval($id);
$db = JFactory::getDBO();
$query = '
SELECT c.*
FROM #__jbusinessdirectory_categories c
INNER JOIN #__jbusinessdirectory_categories cc
ON c.parent_id = cc.id
WHERE c.parent_id!=1
AND cc.id = '.$id.'
AND c.published=1
ORDER BY c.name';
$db->setQuery($query,0,1000);
$result = $db->loadObjectList();
return $result;
}
I am not familiar with Joomla code that retrieves parameters but you can find the ID if you POST it when someone selects a main category.
<?php
if($params->get('showCategories')){
$categoryId = (int) $params->get('mainCategory');
$category = modJBusinessDirectoryHelper::getCategoriesById($categoryId);
$subCategories = modJBusinessDirectoryHelper::getChildCategoryList($categoryId);
}
}
Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.
I have two sets of option value. I created another dropdown that if I choose r it echo <option value $row['nego'] > or n echo <option value $row['rfq'] >. What I want is to pass the value of dropdown without using form. If it possible to do that?
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('rfq_list.php?q=' + str) // or rfq_list.php?q
}
</script>
</head>
<body onload=showUser(str="ALL")>
<select>
<option value="r">rfq</option>
<option value="n">nego</option>
</select>
<?php
if (isset($_POST['n'])) {
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT nego FROM purchase_order GROUP BY shop ORDER BY nego");
$option = '';
while($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['nego'].'">'.$row['nego'].'</option>';
}
}
?>
<?php
if (isset($_POST['r'])) {
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT rfq FROM purchase_order WHERE rfq LIKE '13-___' OR rfq LIKE '1_-___' OR rfq LIKE '2_-___' GROUP BY rfq ORDER BY rfq");
$option = '';
while($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['rfq'].'">'.$row['rfq'].'</option>';
}
}
?>
<select name="users" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
<option value="ALL" selected='ALL'>ALL</option>
<?php echo $option; ?>
</select>
<div id="txtHint"></div>
My select consists of two fields and the text field only picks up one of them. Here is my code:
<script>
function ProdValue(data) {
document.getElementById("ProdName").value = data.value;
}
</script>
<select name="ProdName" id="ProdName" onchange ="ProdValue(this)">
<?php
$sql = "Select * from tblProduct";
if ($result = mysqli_query($conn, $sql));
while ($row = mysqli_fetch_assoc($result))
{
echo "<option value='". $row['Brand']."', '".$row['ProductName']."'>".$row['Brand']." ".$row['ProductName']. '</option>';
}
?>
</select>
How can I get ProductName too?
Since your option value contains brand and productname separated by comma, you could do:
function ProdValue(data) {
var optval = data,
prod_name = optval.split(",")[1];
console.log( prod_name ); //here is your product name
document.getElementById("ProdName").value = optval;
}
use this instead. If both columns are actually defined as NOT NULL, CONCAT() will be quite enough:
<?php
$sql = "Select CONCAT(Brand, ProductName) as CombineColumn from tblProduct";
if ($result = mysqli_query($conn, $sql))
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<option value='". $row['CombineColumn']."'>".$row['CombineColumn']."</option>";
}
}
?>