search results with 2 dependent select menus each in PHP and AJAX - php

I created a search function, where each result has 2 dependent select menus, that are populated depending on the search result.
Now when the search results are more than one, the select menus for the first result work just fine. [see link image 1]
image 1
The problem comes on the second result. When I select and option from the first select menu of the 2nd result. Instead of putting the data, on the select menu next to it, the data is placed in the second select menu of the first result.[see link image 2]
image 2
I cant seem to solve this problem. I have searched the forums here and all around the web. Can't seem to find the solution. Can someone please help. i hope i have explained the problem well enough.
My code:
Index.php
<!DOCTYPE html>
<?php
include("search.php");
?>
<html>
<head>
<title>Search and Drop</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="POST">
<input type="search" name="search" autocomplete="off" />
</form>
<?php product(); ?>
</body>
<script type="text/javascript" src="ajax.js"></script>
</html>
search.php
<!DOCTYPE html>
<?php
include("dbcon.php");
?>
<html>
<?php
function product() {
include("dbcon.php");
if (isset($_POST['search']))
{
$str = $_POST['search'];
$keywords = preg_replace("#[^0-9a-z]#i","", $str);
$query = "SELECT * FROM product WHERE product LIKE '%$keywords%'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if ($count > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<option value="$row["pro_id"]">'.$row["product"].'</option>';
containers($row['pro_id']);
}
}else
echo "Nothing";
}
}
function containers($parent_id) {
?>
<select id="containers" onchange="getSizes(this.value)">
<option value="0">Choose</option>
<?php
include ('dbcon.php');
$select = mysqli_query($conn, "SELECT * FROM product, container
WHERE ($parent_id = product.pro_id) AND ($parent_id = container.pro_id)");
?>
<?php
while ($row = mysqli_fetch_assoc($select)) {
?>
<option value="<?php echo $row["con_id"]; ?>"><?php echo $row["container"]; ?></option>
<?php
}
?>
</select>
<select id="sizes" onchange="getQuan(this.value);"></select>
<?php
}
?>
</html>
get_sizes.php
<!DOCTYPE html>
<html>
<?php
include("dbcon.php");
$query = "SELECT * FROM sizes WHERE con_id='".$_POST["con_id"]."'";
$result = $conn->query($query);
?>
<option value="0">Choose</option>
<?php
while ($rs=$result->fetch_assoc()) {
?>
<option value="<?php echo $rs["size_id"]; ?>"><?php echo $rs["sizes"]; ?></option>
<?php
}
?>
</html>
ajax.js
//function to show and hide sizes select menu
$(document).ready(function(){
$('#containers').change(function() {
var value = $(this).val();
if (value == 0) {
$('#sizes').hide();
$('#quantity').hide();
}else {
$('#sizes').show();
}
});
});
//function to pull data from database onto sizes select menu
function getSizes(val) {
$.ajax({
type:"POST",
url:"get_sizes.php",
data:'con_id='+val,
success: function(data){
$("#sizes").html(data);
$("#quantity").html('<option>Choose<option>');
}
});
}

Related

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

how to change AJAX call from another php file to the same page

I created 2 dropdown lists where the second one is populated from database based on the option selected in the first one using Ajax.
It's working fine but I want to change the call in my ajax from url:"get-City.php" to the same page instead of creating get-city.php I want to put all the code in one page.
Here is my index.php
<?php
include('connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="">
<label>Country :</label>
<select name="country" id="country">
<option value=''>------- Select --------</option>
<?php
$query = 'SELECT DISTINCT Country FROM ****';
foreach ($dbDB->query($query) as $row) {
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<label>City :</label>
<select name="city" id="city"><option>------- Select --------</option></select>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#country").change(function() {
var country_name = $(this).val();
if(country_name != "") {
$.ajax({
url:"get-City.php",
data:{selected_country:country_name},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#city").html(resp);
}
});
} else {
$("#city").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
and City.php
<?php
include('connection.php');
if(isset($_POST['selected_country'])) {
$sql = "SELECT DISTINCT City FROM **** WHERE Country = '".$_POST['selected_country']."'ORDER BY City";
$res = $dbDB->prepare($sql);
$res->execute();
$count = count($res->fetchAll());
if($count > 0) {
echo "<option value=''>------- Select --------</option>";
foreach ($dbDB->query($sql) as $row) {
echo '<option value="'.$row["City"].'">'.$row["City"].'</option>'; }
} }
else { header('location: ./'); }
?>
Now I wanted to merge both files on the same page and make the AJAX call on the same page. Here is my updated file
<?php
include('connection.php');
if(isset($_POST['selected_country'])) {
$sql = "SELECT DISTINCT City FROM **** WHERE Country = '".$_POST['selected_country']."'ORDER BY City";
$res = $dbDB->prepare($sql);
$res->execute();
$count = count($res->fetchAll());
if($count > 0) {
echo "<option value=''>------- Select --------</option>";
foreach ($dbDB->query($sql) as $row) {
echo '<option value="'.$row["City"].'">'.$row["City"].'</option>'; }
} }
else { header('location: ./'); }
?>
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="">
<label>Country :</label>
<select name="country" id="country">
<option value=''>------- Select --------</option>
<?php
include('connection.php');
$query = 'SELECT DISTINCT Country FROM **** ORDER BY Country ASC';
foreach ($dbDB->query($query) as $row) {
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<label>City :</label>
<select name="city" id="city"><option>------- Select --------</option></select>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#country").change(function() {
var country_name = $(this).val();
if(country_name != "") {
$.ajax({
data:{selected_country:country_name},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#city").html(resp);
}
});
} else {
$("#city").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Everytime I select a country then second dropdown list is empty. Can you please advise me what I am missing ? Thank you.

Select value from drop down list and second drop down list auto changed

I have one table in my database called as company and inside company table there are 3 columns name Id,Company_Name and location.
I have two drop down list. First drop down list displaying only Company name and according to company name location will change in second drop down list.
I did some code but in second drop down i am getting all location name.
<?php
//$comp=$_POST['Company'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo_db";
//open connection to mysql db
$connection = mysqli_connect($servername,$username,$password,$dbname) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from company";// it displaying all company name in my first drop down list
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (isset($_POST['Company'])) {
$name=$_POST['Company'];
$sql = "select * from company where Company_name=$name";
}
$result_loc = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select onchange='this.form.submit();' name="Company">
<option value="Select your Location1" disabled selected>Select your company</option>
<?php while($row = mysqli_fetch_array($result)):;?>
<option value="<?php echo $row[1];?>"><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<select>
<option value="" disabled selected>Select your location</option>
<?php while($row = mysqli_fetch_array($result_loc)):;?>
<option value="<?php echo $row[2];?>"><?php echo $row[2];?></option>
<?php endwhile;?>
</select>
</body>
</html>
To aid you in chaining SELECT menus using ajax the following might prove useful - you should be able to modify this to suit your db structure and naming conventions. You can run this "as-is" to see the results - hope it will prove useful.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) ){
$action=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
if( $action && $id && !is_nan( $id ) ){
$sql='select * from table where id=?';
/* etc ~ generic sql example only ! */
/* query db*/
/* process recordset and build menu data */
/*
demo response sent back to aajx callback
In reality this would be dynamically generated with
results from the db query above.
*/
for( $i=0; $i < 10; $i++ )echo "<option value='Location-$id-$i'>Location-$id-$i";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
/* Basic Ajax function */
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};
var params=[];
for( var n in p )params.push(n+'='+p[n]);
switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
/* Callback function to populate second menu */
function createmenu(r,o,h){
/*
r=response
o=options ( sent by ajax function )
h=response headers
*/
o.menu.innerHTML=r;
}
function bindEvents(){
/* Get references to the two dropdown menus */
var oSelCompany=document.querySelectorAll('select[name="Company"]')[0];
var oSelLocation=document.querySelectorAll('select[name="Locations"]')[0];
/* Assign an `onchange` event listener */
oSelCompany.onchange=function(e){
var method='post';
var url=location.href;
/* the parameters to send to the PHP script */
var params={
'action':'getmenu',
'id':this.options[ this.options.selectedIndex ].value
};
/* Options to pass to the ajax callback */
var opts={
menu:oSelLocation
};
/* make the ajax request */
ajax.call( this, method, url, params, createmenu, opts );
}.bind( oSelCompany );
}
document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<form method='post'>
<select name='Company'>
<option value=1>One
<option value=2>Two
<option value=3>Three
<option value=4>Four
<option value=5>Five
</select>
<select name='Locations'></select>
</form>
</body>
</html>
I have created a Demo for you. suppose you have company name and company has multiple location Example (id,name,location) :1,TCS,Banglore 2,TCS,Hyderabad
<?php
/*database connection*/
$con = mysqli_connect("localhost","root","root","search");
?>
<script>
function test(name)
{
// new file name f1.php
var strURL = "f1.php?name="+name;
var ax=new XMLHttpRequest();
ax.onreadystatechange = function()
{
if(ax.readyState==4){
document.getElementById("myid").innerHTML = ax.responseText;
}
}
ax.open("GET",strURL, true);
ax.send(null);
}
</script>
<?php
$sql= mysqli_query($con,"select * from company GROUP BY name ");
//print_r($sql);
?>
<select>
<option value="0">select company name</option>
<?php while ( $row = mysqli_fetch_array($sql))
{
?>
<option onclick="test('<?php echo $row["name"]; ?>');" id="<?php echo $i++."der" ;?>"> <?php echo $row["name"]; ?></option>
<?php }
?>
</select>
<div id="myid"></div>
Now Create a new file f1.php where you can run another mysql query to send the name of company you have selected by test function.here is the code
<?php
$con = mysqli_connect("localhost","root","root","search");
if(isset($_GET['name']))
{
$name = $_GET['name'];
}
$sql= mysqli_query($con,"select * from company where name='$name'");
?>
<select name="city">
<option>Select location</option>
<?php while ($row = mysqli_fetch_array($sql))
{ ?>
<option value=<?php echo $row['location']?>><?php echo $row['location']?></option>
<?php } ?>
</select>

php mysqli I do not get information not available

I have 2 tables, group1 and group2.
With 3 columns, 'id',
'status' (0-Available, 1-Not available) and
'description' for the number 0 and 1 (Available and Not available)
When there is a 0 in the column it works well, and it shows the 'description' for that number,but
when all the numbers in the column are 1 it will not output my
else statement, dont know why? It standing still in the if statament.
I do not know how to output more rows
when i have more zeros in the table.
<?php include('config.php'); ?>
<!DOCTYPE>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>
<body>
<form name='search' method="post">
<select name='onoroff'>
<option value='group1' >Group 1</option>
<option value='group2' >Group 2</option>
</select>
</datalist>
<input type='submit' name='run' value="Go"/>
</form>
<?php
//////////////////////////////////////////////
$group = ($_POST['onoroff']);
$q= mysqli_query($dbc, "SELECT * FROM $group WHERE status = 0");
$r= mysqli_fetch_assoc($q);
if (isset($_POST['run'])) {
echo '<p>'.$r['description'].'</p>';
} else { echo '<p>Not available</p>';}
///////////////////////////////////////////////
?>
</body>
</html>
You should put the database query inside the if(isset($_POST['run'])) block. Otherwise, you're trying to use $_POST['onoroff'] even though the user hasn't submitted the form yet.
if (isset($_POST['run'])) {
$group = ($_POST['onoroff']);
$q= mysqli_query($dbc, "SELECT * FROM $group WHERE status = 0");
$r= mysqli_fetch_assoc($q);
echo '<p>'.$r['description'].'</p>';
} else {
echo '<p>Not available</p>';
}
Adding the if statements with the returned value of the status will choose what is displayed depending on their status.
<?php include('config.php'); ?>
<!DOCTYPE>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>
<body>
<form name='search' method="post">
<select name='onoroff'>
<option value='group1' >Group 1</option>
<option value='group2' >Group 2</option>
</select>
</datalist>
<input type='submit' name='run' value="Go"/>
</form>
<?php
//////////////////////////////////////////////
$group = ($_POST['onoroff']);
if (isset($_POST['run']))
{
$q= mysqli_query($dbc, "SELECT * FROM $group");
while ($r = mysqli_fetch_assoc($q))
{
if($r['status'] == 0) {
echo '<p>'.$r['id'].' : '.$r['description'].'</p>';
}
else {
echo '<p>'.$r['id'].' Not available</p>';
}
}
}
else
{
echo '<p>You need to submit to choose a group</p>';
}
///////////////////////////////////////////////
?>
</body>
</html>

Using Ajax, jQuery and PHP in two dropdown lists

I am trying to populate second dropdown list based on first dropdown list selection using Ajax, jQuery, PHP and MySQL. The problem is the options in second dropdown list just appears in one line (all options in one line)!
I was hoping the while loop inside the results.php could handle this but it seems not. How can I fix this issue?
Here is my code:
<html>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM Cars';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a Car
<select id="selectCar">
<option value="select">Please Select From The List</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
}
?>
</select>
</p>
<select>
<option value="select">Please Select From The List</option>
<option id="result"></option>
</select>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCar').change(function()
{
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
In the PHP result I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$resultStr = '';
$query = 'SELECT * FROM models WHERE carID='.$_GET['id'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$resultStr.= '<option value="'.$row['id'].'">'.$row['model'].'</option>';
}
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
You should edit your script into this..
<select id="result">
<option value="select">Please Select From The List</option>
</select>
You are setting $('#result').html(data); in the main file.
result should be the id of the HTML select element, you used it as id for the an option element.
(You are appending the values into the option element, which doesn't create new HTML elements, but they should be inserted into the select element.)

Categories