There are two dropdown . one loaded with province and other is loaded with district on change the province from dropdown. How to show selected items in both dropdown when error occur or any other reason redirect to test.php page. ?? When i back to this page province dropdown is selected but district not selected..
Test.php
<?php
include "connection.php";
$msg = "";
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg']))
{
$msg = $_REQUEST['msg'];
}
if ( isset($_SESSION['province']) && !empty($_SESSION['province']) )
{
$province = $_SESSION['province'];
}
# Get Province
$sqlProvince = "SELECT * FROM tbl_province";
$resProvince = mysql_query($sqlProvince) or die(mysql_error());
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
function showDistrict(province){
$("#district").html(' '); // city
$.ajax({
url: "js/ajaxDistrict.php",
type: 'POST',
//dataType: 'json',
data: {'province': province},
//dataType: 'json',
cache: false,
success: function(data){
$("#district").html(data);
}
});
}
</script>
</head>
<body>
<?php echo $msg; ?>
<form id="myfrom" action="showTest.php" method="get">
<p>
`enter code here`<label>Province:<small>*</small></label>
<select name="province" id="province" onchange="showDistrict(this.value);" required>
<option value="">-SELECT-</option>
<?php
if(mysql_num_rows($resProvince) > 0)
{
while($rowProvince = mysql_fetch_array($resProvince)){
?>
<option value="<?php echo $rowProvince['Name'];?>"<?php if( $province == $rowProvince['Name'] ) { echo "selected='selected'";} ?>"><?php echo $rowProvince['Name'];?></option>
<?php }
} ?>
</select>
</p>
<p>
<label>Postal City District:<small>*</small></label>
<select name="district" id="district" >
<option value="">-SELECT-</option>
<option value="<?php echo $_SESSION['district']['City_District'];?>"><?php echo $_SESSION['district']['City_District'];?></option>
</select>
</p>
<input name="submit" type="submit" />
</form>
</body>
</html>
ajaxDistrict.php
<?php
include "../connection.php";
$res = "";
$province = $_REQUEST['province'];
$_SESSION['province'] = $province;
$query="SELECT * FROM districts WHERE Province = '".$province."' ";
$result=mysql_query($query) or die(mysql_error());
$str = "";
//$_SESSION['district'] = array();
if(mysql_num_rows($result)>0)
{
while($row = mysql_fetch_array($result))
{
$_SESSION['district']['City_District'] = trim($row['City_District']);
$City_District = trim($row['City_District']);
if($_SESSION['district']['City_District'] == $City_District) { $str = "selected='selected'";}
$res .= "<option value=\"".$City_District."\" ".$str." >".$City_District."</option>";
}
}
else{
$res .= "<option value=''>-SELECT-</option>";
}
echo $res;
?>
You have to keep the value of province and district in session so you can populate it back accordingly or can use cookie for the same.
Call showDistrict function on load of the page in script
`$(document).ready(function(){
showDistrict();
});
`
i think this will work...
Related
I've been trying to do a dynamic drop down menu using php/mysql with ajax. But I'm new to php and ajax so i don't know how to insert the selected option into a mysql table. I created a form where the action leads to a insertsql.php file but its not working.I'm using wamp server. Any help would be greatly appreciated.
index1.php
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "projects");
$pname = '';
$query = "SELECT pname FROM project_details GROUP BY pname ORDER BY pname ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$pname .= '<option value="'.$row["pname"].'">'.$row["pname"].'</option>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>zz
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
<form method = "POST" action = "insertsql.php" >
<select name="pname" id="pname" class="form-control action">
<option value="">Select Project</option>
<?php echo $pname; ?>
</select>
<br />
<select name="user" id="user" class="form-control action">
<option value="">Select User Name</option>
</select>
<br />
<input type="submit" name="update" value="Update">
<p id="dem"></p>
<p id="demo"></p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "pname")
{
result = 'user';
}
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
</script>
fetch.php
<?php
//fetch.php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "projects");
$output = '';
if($_POST["action"] == "pname")
{
$query = "SELECT fname,lname FROM users WHERE pname = '".$_POST["query"]."' GROUP BY fname";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select User</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["fname"].' '.$row["lname"].'">'.$row["fname"]." ".$row["lname"].'</option>';
}
}
echo $output;
}
?>
insertsql.php
<?php
include('sqlconfig.php');
$pname= $_POST['pname'];
$username=$_POST['user'];
$date=$_POST['wdate'];
$hours=$_POST['hours'];
echo "$pname";
echo "<br>$username<br>";
$sql="INSERT INTO worklogging(pname,username,wdate,wkhours) VALUES ('$pname','$username','$date','$hours')";
if(!mysqli_query($con,$sql))
{echo 'not inserted';}
else
{echo 'Inserted';
}
?>
This is the part where the data from the dropdown menu is inserted into the mysql table. Thank you all for the help :)
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>');
}
});
}
I am designing a page that gathers study abroad information from students at my university. Each time you select a country, the drop down will then say array(1) { ["country"]=> string(6) "France" } (or a similar country) before it says "State:". Why is this?
Below is my code minus the UUID and the database connection.
<!DOCTYPE html>
<head>
<link href="Page2.css" rel="stylesheet">
<style>
.error {
color: #FF0000;
}
</style>
<link href="styles.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function go() {
var Count = document.getElementById("sa_yesno").options[document.getElementById("sa_yesno").selectedIndex].value;
if(Count==1) {
document.getElementById("info").style.display = 'none';
}
if(Count==2) {
document.getElementById("info").style.display = '';
}
}
$(document).ready(function(){
$("select#countryName").change(function() {
var country = $("select#countryName option:selected").attr('value');
//alert(country);
$("#state").html("");
$("#city").html("");
if (country.length > 0 ) {
//alert(country.length);
$.ajax({
type: "POST",
url: "fetch_state.php",
data: "country="+country,
cache: false,
success: function(html) {
$("#state").html( html );
}
//not sure about these last two parts
});//end ajax
}//end if
});//end countryName.change
});
</script>
<header>
<h1> University </h1>
<h2> Department </h2>
</header>
</head>
<?php
require 'dbc.php';
require 'uuid.php';
$countriesSQL = "SELECT DISTINCT Country FROM LOCATIONLOOKUP";
$countriesQuery = mysqli_query($conn, $countriesSQL);
while($countries[] = $countriesQuery->fetch_object());
array_pop($countries);
?>
<body>
<table><tr><td>
<div class="StyleDiv" >
<form action="Page3.php" method="post">
<p> Please share any of the information below that you are comfortable sharing about your study abroad experience, if applicable.</p>
<p> 1. Did you study abroad? </p>
<p><select onchange="go()" name="sa_yesno" id="sa_yesno">
<option value="1">No</option>
<option value="2">Yes</option>
</select></p>
<div class="styleDiv" id="info" style="display:none">
<p> 2. When did you study abroad? </p>
<p><select name="sa_term" id="sa_term">
<option value="Fall">Fall Semester</object>
<option value="Spring">Spring Semester</object>
<option value="J-term">J-Term</object>
<option value="Summer">Summer Term</object>
</select></p>
<p> Where did you study abroad?</p>
Country: <select name="countryName" id="countryName">
<option value="">Please Select</option>
<?php foreach($countries as $option) : ?>
<option value="<?php echo $option->Country; ?>"><?php echo $option->Country; ?></option>
<?php endforeach; ?>
</select></br>
<div id="state" class="cascade"></div>
<div id="city" class="cascade"></div>
<br/><br/>
<input type="submit" value="Continue" name="submit" id="submit" ONCLICK="window.location.href='Page3.php?'">
</div>
</form>
<?php
require 'dbc.php';
require 'uuid.php';
$studentID = $_SESSION["studentID"];
$studyid=null;
//can these be assigned values in the select tag above?
$countrySelected= $_POST["countryName"];
$stateSelected= $_POST["drop2"];
$citySelected= $_POST["drop3"];
//Select the locationID from the country, state, city that were specified
$sql2 = "SELECT LocID FROM LOCATIONLOOKUP WHERE Country = '" . $countrySelected . "'
AND StateProvince = '" . $stateSelected . "' AND City = '" . $citySelected . "';";
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query 2: ' . $query;
die($message);
echo "there was an issue";
}
while ($row = mysqli_fetch_assoc($result2)) {
$locationID = $row['LocID'];
}
$stmt = $conn->prepare(" INSERT INTO STUDYABROAD (Term, StudentID, LocID) VALUES ( ?, ?, ?, ?)");
$stmt->bind_param("ssss", $term, $studentID, $locationID);
$stmt->execute();
mysqli_close($conn);
?>
</body>
</html>
EDIT: Here is fetch_state.php
<?php
require 'dbc.php';
var_dump($_POST);
$country = trim(mysqli_escape_string($conn, $_POST["country"]));
$sql = "SELECT DISTINCT StateProvince FROM LOCATIONLOOKUP WHERE Country = '". $country ."' ORDER BY StateProvince";
$count = mysqli_num_rows( mysqli_query($conn, $sql) );
if ($count > 0) {
$query = mysqli_query($conn, $sql);
while($states[] = $query->fetch_object());
array_pop($states);
?>
<label>State:
<select name="state" id="drop2">
<option value="">Please Select</option>
<?php foreach($states as $option) : ?>
<option value="<?php echo $option->StateProvince; ?>"><?php echo $option->StateProvince; ?></option>
<?php endforeach; ?>
</select>
</label>
<?php
}
?>
<script src="jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function(){
$("select#drop2").change(function(){
var state = $("select#drop2 option:selected").attr('value');
// alert(state_id);
if (state.length > 0 ) {
$.ajax({
type: "POST",
url: "fetch_city.php",
data: "state="+state,
cache: false,
success: function(html) {
$("#city").html( html );
}
});
} else {
$("#city").html( "" );
}
});
});
</script>
I want to create a search section in my website where the user has the ablility to choose between 3 types of searching: he can search by name, search by specialization or search by location.
The output will be the first name, last name, and profile picture.
The problem is that I do not know how to write the structure and the queries of this code.
This what i tried to write but it gives me many errors:
notice : Undefined index : district
notice : undefined index : village
notice : undefined index : sql
warning :mysql_fetch_array() expects parameter 1 to be resource ,
null
search.php
<?php
session_start();
if($_SESSION['login'] != 'true'){
header("location:index.php");
}
$login = ($_SESSION['login']);
$userid = ($_SESSION['user_id']);
$login_user = ($_SESSION['username']);
$fname = ($_SESSION['first_name']);
$lname = ($_SESSION['last_name']);
$sessionaddres =($_SESSION['address']);
require_once('for members/scripts/connect.php');
// function for selecting names
function nameQuery(){
$nameData = mysql_query("SELECT * FROM user") or die("could not select database");
while($record = mysql_fetch_array($nameData)){
echo'<option value="' . $record['user_name'] . '">' . $record['user_name'] . '</option>';
}
}
// function for select by specialization
function specializationQuery(){
$specData = mysql_query("SELECT * FROM specialization");
while($recordJob = mysql_fetch_array($specData)){
echo'<option value="' . $recordJob['specialization_name'] . '">' . $recordJob['specialization_name'] . '</option>';
}
}
if(isset($_POST['search']))
{
$Sname =$_POST['name'];
$Sspec = $_POST['specialization'];
$Sgov = $_POST['governorate'];
$Sdist = $_POST['district'];
$Svillage = $_POST['village'];
// query search by name
if($Sname !=0)
$sql = mysql_query("SELECT first_name, last_name, profile_pic FROM user WHERE user_name ='$Sname'")or die(mysql_error());
while($getrow = mysql_fetch_array($sql))
{
$firstname = $getrow['first_name'];
$lastname = $getrow['last_name'];
$profilepic = $getrow['profile_pic'];
var_dump($firstname);
var_dump($lastname);
var_dump($profilepic);
echo "<ul>
<li>
'.$firstname' '' '.$lastname'
</li>
<li>
'.$profilepic'
</li>
</ul>";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>search page</title>
<link href="style/stylesheet.css" rel="stylesheet" type="text/css" />
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#village").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
});
$("select#district").change(function(){
id = $(this).val();
$("select#village").attr("disabled","disabled");
$("select#village").html("<option>wait...</option>");
$.post("select_village.php", {id:id}, function(data){
$("select#village").removeAttr("disabled");
$("select#village").html(data);
});
});
$("form#registerform").submit(function(){
var cat = $("select#governorate option:selected").attr('value');
var type = $("select#district option:selected").attr('value');
var village = $("select#village option:selected").attr('value');
});
});
</script>
</head>
<body>
<div class="container">
<!--<?php require_once('header.php'); ?>-->
<br />
<br />
<br />
<br />
<!-- <?php require_once('leftsideBar2.php'); ?>-->
<div id="search-title">Search section</div>
<div id="search-form">
<?php include "select.class.php"; ?>
<form action="search.php" method="post">
Search By Name:<br />
<select name="name" >
<?php nameQuery(); ?>
<option id="0">-- select By UserName --</option>
</select>
<br/><br/>
Search By Governorate:<br />
<select id="governorate" name = 'governorate'>
<?php echo $opt->ShowGovernorate(); ?>
</select>
<br /><br/>
Search by District:<br />
<select id="district" name="district">
<option value="0">choose...</option>
</select>
<br /><br/>
Search by Cities:<br />
<select id="village" name="village">
<option value="0">choose...</option>
</select>
<br /><br/>
Search By Specialization:<br />
<select name="specialization">
<option id="0" disabled="disabled">-- select Job --</option>
<?php specializationQuery(); ?>
</select>
<input type="submit" name="search" value="Search" />
</form>
</div>
</div>
<?php require_once('footer.php'); ?>
</body>
</html>
You should check that the request variables in $_POST are set properly using isset:
if (isset($_POST["district"])) { $district = $_POST["district"]; }
//etc
I'm not seeing a reference to an index named "sql" in this code, you might want to check "select.class.php" which you included later in your search.php
For the last issue, you should check that all queries are valid; if they are not, mysql_query() will not return a result (mysql_query() returns type resource), then mysql_fetch_array() will not be able to get an array (mysql_fetch_array() expects a resource, but you had null).
i am creating 2 dynamic drop list that the second one is based on the selection of the first but the problem is that the second one do not populate and i do not know where is the error can anyone help me ????
dbconfig.php
<?php
$host = "localhost";
$user = "*****";
$password = "****";
$db = "lam_el_chamel_db";
?>
select.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#governorate option:selected").attr('value');
var type = $("select#district option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#district option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a governorate:<br />
<select id="governorate">
<?php echo $opt->ShowGovernorate(); ?>
</select>
<br /><br />
choose a district:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
select class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "dbconfig.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowGovernorate()
{
$sql = "SELECT * FROM governorate";
$res = mysql_query($sql,$this->conn);
$governorate = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$governorate .= '<option value="' . $row['governorate_id'] . '">' . $row['governorate_name'] . '</option>';
}
return $governorate;
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
}
$opt = new SelectList();
?>
select _type.php
<?php
include "select.class.php";
echo $opt->ShowDistrict();
?>
table structure
governorate :
governorate_id
governorate_name
districts:
district_id,
district_name,
governorate_id.
On select.php Page you used id for select tag is 'id="type"' which would be 'id = "district"' in select tag for choose a district : below text.
choose a district:<br />
<select id="type">
<option value="0">choose...</option>
</select>
By Below
choose a district:<br />
<select id="district">
<option value="0">choose...</option>
</select>
Rename page 'select_type.php' by 'select_district.php' Or do change in $.post ajax query. correct sending request page name by 'select_type.php'.
This should be changed in
from $sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
to $sql = "SELECT * FROM districts WHERE governorate_id=$_POST['governorate']";
also in select.php change
<select id='governorate'> to <select id='governorate' name='governorate'>