dependent dynamic dropdown in php - php

Here I have two dependent drop downs.
First drop down is displaying all accounts(name and id).
<select name="account" id="account" class="input-name">
<?php
$query = "SELECT id,name FROM account";
$results = mysqli_query(con, $query);
while($account = $results ->fetch_assoc()){
?>
<option value="<?php echo $account["id"]; ?>"><?php echo $account["name].'-'.$account["id"];?</option>
<?php } ?>
</select>
In second drop down I need to display selected account users.
<select name="extension" id="extension" class="input-name">
<?php
$query = "SELECT ext FROM user WHERE account=100"; //Query for users for selected account.
$results = mysqli_query($con, $query);
while($user= $results ->fetch_assoc()){
?>
<option value="<?php echo $user["ext"]; ?>"><?php echo $users["ext"];?></option>
<?php } ?>
</select>
How can I filter users according to select company. Need help.

You may reload page after first value was selected and load page with second param. for example
<select onchange="window.location.href='some url with some value?select_value=' + this.value">...options...</select>"
Or if you do not want to reload page you can use AJAX. send request with ajax to server and replace options in second select.
with jquery
$('select.first-select').change(function(){
var value = $(this).val();
$.get('get-account', { val: value }, function(){ ...replace options... })
})

You can do it by using Jquery ajax request. Write an onchange method on first dropdown. On change take the id of selected account and pass it to your query for selecting users.Return all the users and display it to your users dropdown.

Related

jquery get data attributes of select2 inside while loop php

I have been reviewing similar questions related to select2 data attributes, but couldn't find what I'm looking for. I have been taking time on this.
Basically I have a select2 dropdown inside a while loop which fetch values from sql database. I need to add an additional data attribute and when an option is selected, I need to display the selected data attributed in the input field. My code goes as below
<select class="select2-dropdown form-control" tabindex="-1" id="user" name="user">
<option value="">Select User</option>
<?php
$fetchuser = mysqli_query($link,"SELECT * FROM user ORDER BY name ASC") or die(mysql_error());
while($row=mysqli_fetch_assoc($fetchuser))
{
$id = $row["id"];
$name = $row["name"];
$status = $row["status"];
?>
<option value="<?php echo $id; ?>" data-status="<?php echo $status; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input id="status" />
My JS:
<script type=text/javascript>
$('#user').on('select2:selecting', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
</script>
I'm only getting random status (not corresponding to the selected), and some options status is not displayed when selection is changed.
Could anyone suggest where i have made the mistake.
Thank you in advance.
Your code is so weird for me.
Try this:
$('select').on('change', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
I think it will change function that you need to use
$('#user').on('change', function() {
var status= $(this).find(":selected").data("status");
$('#status').val(status);
});

Dynamic dependent select boxes (PHP+JQuery+AJAX)

I have been working on a dependent select boxes form using PHP as the server-side language and JQuery with Ajax. I am having an issue with getting the response text, as it is not displaying as options in the second select box.
P.S. I am new to Ajax and there is no video that can help me with my problem.
HTML&PHP:
<center><form method="post" action="php/functions.php" id="catForm">
<select name="catSelect" class="catSelect" name="category">
<option value='null' default>اختر الفئة:</option>
<?php
$selectCategories = mysqli_query($connectionDB, "SELECT * FROM categories");
while($categoriesDisplay = mysqli_fetch_array($selectCategories)){
echo '<option value="'.$categoriesDisplay['id'].'">'.$categoriesDisplay['category'].'</option>';
}
?>
</select><br/><br/>
<select name="subCatSelect" class="subCatSelect">
<option value="null" default>اختر النوع:</option>
<?php
$catSelectVal = $_POST['catSelect'];
$selectSubCat = mysqli_query($connectionDB, "SELECT * FROM sub_categories WHERE id LIKE '$catSelectVal'");
while($subCatDisplay = mysqli_fetch_array($selectSubCat)){
echo '<option value="'.$subCatDisplay['id'].'">'.$subCatDisplay['subCategory'].'</option>';
}
?>
</select><br/>
<h1></h1>
<input type="submit" value="اختر" class="submitForm" /><br/>
</form></center>
Jquery code:
$(document).ready(function(){
$('.catSelect').change(function(){
var changeURL = $('#catForm').attr("action");
var data = $('.catSelect').val();
$.post(changeURL, {category : data}, function(subCategory){
$('.subCatSelect').append(subCategory);
});
});
});
The code that should work on getting the options for the second select box:
$catSelectVal = $_POST['catSelect'];
$selectSubCat = mysqli_query($connectionDB, "SELECT * FROM sub_categories WHERE id LIKE '$catSelectVal'");
while($subCatDisplay = mysqli_fetch_array($selectSubCat)){
echo '<option value="'.$subCatDisplay['id'].'">'.$subCatDisplay['subCategory'].'</option>';
}
I could be wrong, but I don't think you've sent 'catSelect' in the ajax request.. rather you've sent category with data being the value from 'catSelect'
So when you look for $catSelectVal = $_POST['catSelect']; there won't be anything to find.
Try instead: $catSelectVal = $_POST['category'];
As #RiggsFolly mentioned, if you print_r($_POST); you'll instantly see if this is the case or not.

edit product page with id feature

On a web app i'm making, I have an edit page which is obviously where users edit info on already existing products, it uses PHP/ MySQL. My edit page is ALMOST working exactly how I want it too. I have a drop-down populated from the SQL database, and I can edit the product info via the text-boxes. The only problem I have is that I do not know how to edit the products via the ID which changes as the products are selected.. I instead have to manually set a static value in the PHP code, I was just wondering how I could do this? I'm thinking GET could be used but not entirely sure.. I'll post pictures and code below.. thanks.
The ID changes to the corresponding product ID as I select a product from the dropdown
As you can see I have to type in the ID in the php..
so basically i was trying to get it to change the product to edit as i select them from the dropdown..
hope i wasnt too confusing, thanks!
$conn = new mysqli('', '', '', '')
or die ('Cannot connect to db');
$result = $conn->query("select ID, NAME from PRODUCTS");
?><div align="left"><?
print "<h3>EDIT PRODUCT</h3>";
print "<strong>SELECT PRODUCT:</strong>";
print "<br><br>";
print "<form method='GET' id='frm_product'>";
print "<select name='ID' OnChange='$(\"#frm_product\").submit();'>";
while ($row = $result->fetch_assoc())
{
print "<option value='$row[ID]'>$row[NAME]</option>";
}
print "</select>";
print "</form>";
?>
<form method='POST'>
<h3>PRODUCT:</h3>
<input type='textbox' name='product' value='<?php echo $product['product'] ? >'>
<h3>BARCODE:</h3>
<input type='textbox' name='barcode' value='<?php echo $product['barcode']; ?>'>
<h3>TYPE:</h3>
<select name="type">
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<br><br>
<input type='submit' value='Save Changes' name=submitform>
</form>
<?
if (isset($_POST['submitform']))
{
$namechange = $_POST[product];
$barcodechange = $_POST[barcode];
$typechange = $_POST[type];
$sql = "UPDATE PRODUCTS SET
NAME='$namechange'
,BARCODE='$barcodechange'
,TYPE='$typechange'
WHERE ID='79'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
}
Cant you set:-
$productID = $_GET['ID'];
And then change the 79 on the update script to $productID?
Hopefully I understood the question.
You can do something like this in javascript.
redirect to the product page each time the user selects an option.
<select id="products" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<script>
function myFunction() {
var id = document.getElementById("products").value;
window.location.href = "/linkto/product.php?"+id;
}
</script>
If you don't want to reload the page each time you can use jQuery Ajax and JSON
If I get you right you want to edit the entries in the databse which belong to a special ID, right? As you tried with $_GET you must add this to your sql query aswell:
[...]
$typechange = $_POST['type'];
// end of your old code
// start of new code
$id = $_GET['ID'];
// modified sql query
$sql = "UPDATE PRODUCTS SET NAME='$name', BARCODE='',TYPE='' WHERE ID='$id'";
// rest of your old code
[...]
Note: It´s not recommended to use user input without validating. A user can change the values for any existing ID by just manipulating the $_GET parameter in your url. You should validate the users input before processing.

Dynamics view values in field on select record in Php

I want view a price values in a field when select a record from dropdown list.
This is the dropdown list code with php code inside:
<select name="product_id[]" class="form-control">
<?php
include("connect.php");
$query = "
SELECT *
FROM tbl_product ORDER BY product_desc ASC
";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) {
echo "
<option value=\"$record[product_id]\">$record[product_cod] $record[product_desc]</option>";
}
?>
</select> <input type="text" name="product_price[]" size="6">
In to the specific case: in dropdown list I have 3 records products:
1 milk 3euro
2 wather 1euro
3 caffee 4euro
For example, when select the second record, in the filed price how to put the 4euros values?
Thanks
Well you could try using something like this. My code uses ajax to get the price of the product_id we got from select.
<?php
include("connect.php");
$query = "SELECT * FROM tbl_product ORDER BY product_desc ASC";
$result = mysql_query($query);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select name="product_id[]" class="form-control">
<?php
while ($record = mysql_fetch_array($result))
{
?>
<option value="<?php echo $record['product_id']; ?>"><?php echo $record['product_cod'] . " " . $record['product_desc']; ?></option>
<?php
}
?>
</select> <input type="text" id="input_price" name="product_price[]" size="6" value="">
<script>
$( "select" )
.change(function () {
var val = $( "select option:selected").val();
//$('#input_price').val(val);
$.ajax({
url : 'ajax_getprice.php',
type : 'GET',
data : {
'product_id' : val
},
dataType:'json',
success : function(data) {
$('#input_price').val(data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
})
.change();
</script>
ajax_priceget.php
<?php
$productid = $_GET['product_id']; //you have the product id now
//now write a query to select the price of the product using the product id and echo the price
?>
#Frankie, if the price field is separetly shown somewhere then there are two ways by which you can perform this,
1- Use jquery to get the prices, in order to do it through jquery you need to place the prices of the records in their values and then to use $('.product_id[]').val(); to get the price of the selected record.
2- Second way is to use the ajax for that purpose if you have stored item's prices in the databse then you need to hit the database by sitting at the front end at the onChange's jquery method you need to get ajax response regarding the prices against the product id,s and then to display at any posisiton you want to.

How to change dropdown menu depending on table mysql

Hello all: i have 2 dropdowns list that populate themselves from two different TABLES.
The first TABLE
(ID|Project_Name|isActive).
And the second TABLE is for users
(Project_Id|Name)
I want to show the options from the second dropdown according on what is selected from the first one.
For example in the first TABLE i have 3 Projects:
1:Project1
2:Project2
3:Project3
And on the second TABLE which is for users: The user has an id that depends on the project from first TABLE:
User A works on Project1
User B works on Project1
User C works on Project2
<html>
<body>
<script type="text/javascript">
function changeProject()
{
alert(document.getElementById("ProjOptionId_id").value);
}
</script>
<form method="POST" action="page.php">
<table>
<tr>
<td>
<?php Insertprojects(); ?>
</td>
</tr>
<tr>
<td>
<?php InsertUsers(); ?>
</td>
</tr>
<form>
</body>
</html>
<?php
function Insertprojects()
{
$Search ="SELECT * FROM proj_database";
$query= mysql_query($Search);
echo "<select name=\"ProjOptionId\" id=\"ProjOptionId_id\" onchange=\"changeProject()\">";
$bFirstLoop=0;
while($Row = mysql_fetch_array($query))
echo "<option value=\"$Row[ID]\">$Row[Project_Name]</option>";
if($bFirstLoop==0)
{
$GLOBALS['sProjectId'] = $Row['ID'];
}
$bFirstLoop++;
}
echo "</select>";
}
?>
I made the javascript function to get the index of the dropdown, so i can change the second dropdown depending on the element selected.
How can i do when you select Project1 on first dropdown, to appear in second dropdown the users that works only with Project1 and so on without reloading the page.
I manage to solve this by jQuery:
$(function()
{
$("#projectSelector").change(function()
{
$("#customerSelector").load("getter.php?project_id=" + $("#projectSelector").val());
});
});
Where this is my first dropdown:
<select id="projectSelector" name="projectSelector">
<option selected value="base">--Select an option--</option>
<?php
/*Code to populate from Mysql query
SELECT* FROM......*/
?>
</select>
and the second dropdown that takes the value according on what is selected from first one
<select id="customerSelector">
<option>--Select an Option--</option>
</select>
and the getter.php is an external files that contains a varible to use when the dropdown value changes:
<?php
$sProjectId = $_GET['project_id'];
mysql_query = SELECT * FROM database1 WHERE tablecolum = $sProjectId;
while ($row = mysql_fetch_array($result)
{
echo "<option>".$row['tablecolumn']."</option>";
}

Categories