Viewing data from database based on selected option in drop down menu - php

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or would I need to delve into the AJAX world? If that's the case, how would I use AJAX and PHP together in the scope of this project?
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option value=$name></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option>$name</option>";
}
echo "</select>";
echo "</fieldset>";
?>
</form>
</div>

This is definitely an AJAX situation. I'm not sure if you're using JQuery on this page, but that would help you a lot.
It would look something like this:
$("#selectCust").change(function(){
var selected = $("#selectCust").val();
$.ajax({
url: "backEnd.php",
data: {
'selected': selected
},
success: function(data) {
$( this ).addClass( "done" );
}
});
});
The database stuff would occur in backEnd.php.

Related

How to fetch value of a drop-down and a text box after btn click?

I have a form wherein I have a drop down which is being populated from the database also I have an input box right beneath it. I want to fetch the value of both the fields via Ajax using jQuery and insert them into the database.
Problem: Value of the text field is getting inserted successfully but the value of drop down is not getting inserted.
I know I will have to fetch the value of the drop down separately and then add it to the data in ajax but I am not able to figure how to do the same.
NOTE: COULD THE DOWN VOTERS BE KIND ENOUGH TO TELL ME WHY I WAS DOWNVOTED SO THAT I COULD IMPROVE UPON THINGS.
sub_category_add.php
<form method="post">
<select id="cat_sub_cat">
<?php
$data=mysqli_query($con,"SELECT * FROM category");
while($row=mysqli_fetch_array($data))
{
echo "<option value=".$row['cid'].">".$row['category']."</option>";
}
?>
</select><br><br>
<h3>Add Sub Categories</h3><br>
<input type="text" name="sub_cat"><br><br>
<input type="submit" name="submit" value="Insert" id="sub_cat_btn">
</form>
Ajax File:
$(document).on('click','#sub_cat_btn', function(event){
event.preventDefault();
$.ajax({
url:"sub_cat_add_back.php",
method:"post",
data:$('form').serialize(),
dataType:"html",
success:function(strMsg){
$("#cat_sub_msg").html(strMsg);
}
})
sub_cat_add_back.php
<?php
include "../includes/config.php";
$name=$_POST['sub_cat'];
$cid=$_POST['cat_sub_cat'];
$data=mysqli_query($con,"INSERT INTO subcategory (name,cid) VALUES ('$name','$cid')");
if($data=="true")
{
echo "Successfully Inserted";
}
else
{
echo "Error";
}
?>
Your problem is that the select tag does not have the Name attribute
<select id="cat_sub_cat" name="cat_sub_cat">
If you want to get values on click instead of form serialize. add id in input
<input type="text" name="sub_cat" id="custom">
$("#cat_sub_cat option:selected");
$("#custom").val();
and if you want to do that with form serialize then add name in your select
<select id="cat_sub_cat" name="your_select_name">

Setting the options in a drop-down menu based on the selected option of another

Bellow I have two drop-down menus. One fetches the list of "Coalitions" and the other the list of "candidates" from the database. What I'm trying to do is to list the candidates in the second drop-down menu, based on the coalition selected in the first. Basically list/set the candidates that are in the same coalition in the second drop-down menu. The problem is that I'm unable to first get the selected item from the "coalition" menu and second use that value to set the second.
here is my code:
<form action ="includes/admin.users.inc.php" method="POST">
<div style = "display: inline-block;">
<!-- the coalitions -->
<select class="form-control" id = "coalition_id" name ="coalition_select" method="POST">
<option value="" selected disabled>Coalitions</option>
<?php
include_once 'includes/dbh.inc.php';
$sql_coalition = mysqli_query($conn, "SELECT coalition FROM candidates");
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"\">" . $row['coalition'] . "</option>";
}
global $coalition_select;
echo $coalition_select = $_POST['coalition_select'];
?>
</select>
</div>
<div style = "display: inline-block;">
<!-- the users -->
<select class="form-control">
<option value="" selected disabled>Candidates</option>
<?php
include_once 'includes/dbh.inc.php';
$sql = mysqli_query($conn, "SELECT username FROM candidates WHERE coalition = '$coalition_select'");
while ($row = $sql->fetch_assoc()) {
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
</div>
</form>
I looked at few examples dealing with a similar situation with no success. The two menus function just fine separately so the issue is not with the connection. Please note that I wish for this action to takes place without any button being pressed.
Thanks
As php is server side code, you can't get the 1st dropdown's selected value in php part (for the 2nd dropdown).
To fill the 2nd dropdown based on 1st dropdown's selection, you need to use ajax.
Do a ajax call on "change" event of 1st dropdown ie Coalitions and ajax url should return you the list of candidates based on ajax parameter ( Coalitions selected value). Once you get the ajax response them you can fill those values in "Candidates" dropdown using JS/Jquery.
Here are the sample code which should fulfill your requirement:
$( "#coalition_id" ).change(function() {
var selected_id = $(this).val();
// path of the file which should return list of candidates (JSON
format ) for "coalition" value passed to this url via GET method
var url = "path/to/candidates_file.php?coalition=" + selected_id;
// ajax call
$.get(, function(json, status){
$('#candidatesselect').empty();
// loop through each value & fill the candidates dropdown
$.each(json, function(i, item) {
$('#candidatesselect').append(
$('', {
value: item.owner,
text: item.username
}, ''));
});
});
});

How to retrieve data from dropdown list to another dropdown list?

I'm not sure how to explain . Its confusing to me as I'm still a newbie in this php world. Hope you guys can help me.
I have a form. In that form there are two dropdown list. The first dropdown list will display all the location that have been save in database. The problem is that how can I, display the id number in the second dropdown list based on the location that have been selected in the first dropdown list .
Can anyone help me ?
Code:
<form action="form.php" method="post" name="order">
<table>
<tr>
<td>Select Location :</td>
<td> <select name="location" id="location">
<option>-- Location --</option>
<?php
$query="SELECT DISTINCT location FROM inventory";
$result=mysql_query($query);
while(list($locationid)=mysql_fetch_row($result)) {
echo "<option value=\"".$location."\">".$location."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Date :</td>
<td><input type="text" nama="date" /></td>
</tr>
<td>Id Number:</td>
<?php
$query="SELECT DISTINCT idno FROM asset WHERE locationid='inventory.location'";
$result=mysql_query($query);
while(list($idno)=mysql_fetch_row($result)) {
echo "<option value=\"".$idno."\">".$idno."</option>";
}
?>
</td>
</tr>
<tr><td>
<input type="button" value="submit" name="submit" /> </td></tr>
</table>
You have 3 main options:
Do it "all at once" with one call to your PHP page to render the HTML for the page and NO postbacks to another page and refresh in the browser, NOR any AJAX call for JSON for the 2nd dropdown. Instead you would "push" all possible values for BOTH dropdowns to the browser and use Javascript to actually narrow the list of displayed values in the 2nd dropdown depending on what you selected in the first
Do it with 2 "calls" to your php page, the first time rendering the page with all values in the 1st dropdown and NO values in the 2nd, then when you selected the value from the 1st dropdown, your page/form/dropdown would trigger a postback (your 2nd call) to your PHP page, which would RE-RENDER the page with the 2nd dropdown ALSO filled, but with only the appropriate (narrowed-down) options.
Do it with 2 calls, but without RE-RENDERING the page and NO POSTBACK. Instead, you would have 2 PHP pages/scripts on the server.
The first script renders the HTML page with the 2 dropdowns and fills the first one with its values.
Upon selection of a choice in the first dropdown, an AJAX request to your 2nd script is trigger. When that page/script is called on the PHP server, it DOES NOT render and send HTML, but instead, only JSON that represents the appropriate (narrowed-down) values for the 2nd drop-down. The AJAX call initiated in the browser is done via Javascript that waits for the JSON to return. When it does, you then process it and "change the values" in the 2nd dropdown.
This can be done with Native Javascript or jQuery. But, it's much, much easier with jQuery.
There are several post on SO about this topic. Please, read these topics first, hope these will help-
Populate one dropdown list based on the selection of other dropdown list
jQuery show/hide drop-down options based on another drop-down option
Finally, you can check the tutorial here to populate dropdown based on dropdown selection...
Tutorial Here |
Demo Here
Credit goes to
The another answer I'm posting here :
(Please try changing content according to your requirement.)
<span class="location_lable">Please select state from Dropdown: </span>
<?php
$row = $wpdb->get_results("SELECT distinct(state_id), state_name from wp_state_city ", ARRAY_N);
echo "<select name='states' id='states'><option value=''>Select State</option>";
foreach($row as $results)
{
echo $fetchData = '<option value="'.$results[0].'">'.$results[1].'</option>';
}
echo "</select>";
?>
<span class="location_lable">Please select city from Dropdown: </span>
<select name="city" id="city"><option value=" ">Select city</option></select>
<script>
$("#states").change(function() {
$("#city").html(' ');
state_v = $(this).val();
param = "get_city_front";
$.ajax({
url: "locationtrack.php",
type: 'POST',
dataType: 'json',
data: {'state_v': state_v, 'param': param},
dataType: 'json',
cache: false,
success: function(data){
$("#city").append(jqxhr.responseText);// need to show success
},
error: function(jqxhr) {
$("#city").append(jqxhr.responseText);
}
});
});
</script>
locationtrack.php
Add query and return result in one variable .
<?php
$query="SELECT DISTINCT idno FROM asset WHERE locationid='inventory.location'";
$result=mysql_query($query);
while(list($idno)=mysql_fetch_row($result)) {
$res .= "<option value=\"".$idno."\">".$idno."</option>";
}
echo $res;
?>

Adding values (by user) to drop down list populated from db

I'm trying to create an "editable" drop down list. I have a drop down list populated from a table "city" in my db, it works perfect but now I want user to be able to add a new value to the list if it doesn't exist there (and I want to save this value, so next time it appears in the drop down list).
Any ideas?
Thank you
<select name="city">
<?php
// connecting to DB
$con= mysqli_connect('localhost','root','1234','e-sage');
// enable hebrew input
mysqli_set_charset($con,'utf8');
// read the city table from DB
$sql = mysqli_query($con,"SELECT CityName FROM city");
while ($row = mysqli_fetch_array($sql)){
// creating temporary variable for each row
$city1=$row["CityName"];
//assigning a value to each option in dropdown list
echo "<option value=\"$city1\"> $city1 </option>";
}
?>
</select>
You can provide a 'other' selection in the dropdown. If user selects that then display a new textbox from which you can insert in the database.
Then try this:
Lets agree that you already got all the cities in array OK?
<select name="city">
<?PHP
foreach($cities as $city)
{
echo '<option value="'.$city.'">'.$city.'</option>';
}
?>
</select>
<form method="post">
<label for="new_city">New city</label>
<input id="new_city" name="new_city" placeholder="Enter new city name" />
<input type="button" id="addCity" value="Insert city" />
</form>
<script>
$(document).on('click','#addCity',function()
{
var new_city=$("#new_city").val();
var e=0;
$("[name='city'] option").each(function(i,item)
{
var check_city=$(item).val();
if(check_city==new_city)
{
e++;
}
else
{
}
});
if(e>0)
{
alert('The same');
}
else
{
/*Submit the form*/
alert('This city is fresh and new');
}
});
</script>
So the script is checking if the value is already assigned to option. If not - allows to submit the form.
Check this one: http://jsfiddle.net/n47N2/1/
use datalist tag
link to w3School tutorial

Drop-down script in multiple menus

CanĀ“t find the mistake. I have three dropdown menus which are connected to a SQL server. When I load the page the first dropdown is already filled. After selecting a value from the first dropdown the page calls the function "reload(form)" from the script and in shows the new index in the second value. Till there it works fine, but when I select a value from the second dropdown in order to call the function "reload2(form)" it refreshs the whole page and the value selected from the first and second dropdown disappears and the dird dropdown doesn't show anything.
Here is the script code:
<script language=JavaScript>
function reload(form)
{
var val=document.form.cliente.options[form.cliente.options.selectedIndex].value;
self.location='indexmm.php?cliente=' + val ;
}
function reload2(form)
{
var val=document.form.cliente.options[form.cliente.options.selectedIndex].value;
var val2=document.form.equipos.options[form.equipos.options.selectedIndex].value;
self.location='indexmm.php?cliente=' + val + '&equipos=' + val2 ;
}
</script>
And here is my php code:
<form method="post" name="form" id="form" action="post.php">
<h1>Cliente:
<?php
echo "<select name='cliente' onchange=\"reload(this.form)\"><option value=''>Seleccione...</option>";
while($busq1 = mysql_fetch_array($consultacliente)) {
if($busq1['IdCln']==#$cliente){echo utf8_encode("<option selected value='$busq[IdCln]'>$busq1[Cliente]</option>"."<BR>");}
else{echo utf8_encode("<option value='$busq1[IdCln]'>$busq1[Cliente]</option>");}
}
echo "</select>"
?>
</h1>
<h1>Equipos:</br></h1>
<?php
echo "<select name='equipos' size='5' style='width:400px' onchange=\"reload2(this.form)\">";
while($busq3 = mysql_fetch_array($consultaequipos)) {
if($busq3['IdGn']==#$refaccioness){
echo utf8_encode("<option selected value='$busq3[IdGn]'>$busq3[Generador]</option>"."<BR>");}
else{echo utf8_encode("<option value='$busq3[IdGn]'>$busq3[Generador]</option>");}
}
echo "</select>"
?>
</h1>
<h1>Refacciones:</br></h1>
<?php
echo "<select name='refacciones' size='20' style='width:400px'>";
while($busq4 = mysql_fetch_array($consultarefac)) {
echo utf8_encode("<option value='$busq4[Descripcion]'>$busq2[Descripcion]</option>");
}
echo "</select>"
?>
The variables $consultarefac, $consultacliente, $consultaequipos are the SQL query.
Any suggestion?
I would recommend NOT reloading the page every time someone changes a dropdown. I would recommend only updating the dropdowns below the current one using AJAX.
Simple AJAX call would be to replace a div surrounding the following dropdown(s) with a snippet of html. The first select will replace the contents of div 'second' (which will include clearing the third dropdown. The second select will replace the contents of div 'third'.
The pages you grab with ajax will return the html snippet for only the appropriate section. The replace functions will use ajax against the appropriate pages to replace the contents of the appropriate div.
<div id="first">
<select name=first onchange="replace1()"></select>
<div id="second">
<select name=second onchange="replace2()"></select>
<div id="third">
<select name=third></select>
</div>
</div>
</div>

Categories