I have been trying for a while to find out a correct method of pulling information from a database based on the initial text
selected on a html drop down menu.
Here is my code:
<html>
<head>
</head>
<script src="testjs.js"></script>
<?php
$host = "";
$username = "";
$password = "";
$database = "";
mysql_connect($host, $username, $password);
mysql_select_db($database);
?>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<?php
$Query = mysql_query("SELECT * FROM population");
while ($Rows = mysql_fetch_array($Query))
{
$ID = $Rows['ID'];
$Pop = $Rows['Pop'];
$UniqueID = $Rows['uid'];
echo "<option value=\"$UniqueID\">$Pop</option>";
}
?>
</select>
</form>
<br>
<p>DB ID <input type="text" id="ids" name="ID" ></p>
<p>Population <input type="text" id="content" name="contet" ></p>
<p>Unique ID <input type="text" id="uid" name="uid" ></p>
<div id="GetInformation"><b>Person info will be listed here.</b></div>
</body>
</html>
test.js contains:
function showUser(str)
{
if (str=="")
{
document.getElementById("GetInformation").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("GetInformation").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
Get user contains:
<?php
$q=$_GET["q"];
$con = mysql_connect('', '', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DropDown", $con);
$sql="SELECT * FROM population WHERE uid = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
?>
<script type="text/javascript">
var ids = '<?php echo json_encode($ID); ?>';
var content = '<?php echo json_encode($Pop); ?>';
var uid = '<?php echo json_encode($UID); ?>';
</script>
<?php }
mysql_close($con);
?>
try changing
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
?>
<script type="text/javascript">
var ids = '<?php echo json_encode($ID); ?>';
var content = '<?php echo json_encode($Pop); ?>';
var uid = '<?php echo json_encode($UID); ?>';
</script>
<?php }
to
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
echo $ID . ' - ' . $Pop . ' - ' . $UID;
}
this should work. but there are better ways as they give you more access later on in your client side. e.g. send a JSON object back, a quick example would be:
$info = array();
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
$info[] = array( 'id' => $ID, 'pop' => $Pop, 'uid' => $UID );
}
echo json_encode($info);
and your JS would be something like :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("GetInformation").innerHTML += data[i].id + ' - ' + data[i].pop + ' - ' + data[i].uid;
}
}
NOTE: if you are working with a browser that doesn't include the JSON library you need to load http://www.json.org/js.html . Also your AJAX/DOM changes can become much simpler if you want to use jQuery
Related
I'm trying to make a dependable dropdown lists on PHP with AJAX calls. There are 9 columns on the MySQL table. I found a sample code. There were 3 dropdown lists. And I tried to increase them.
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title></title>
<META NAME="DESCRIPTION" CONTENT="">
<META NAME="KEYWORDS" CONTENT="">
<script type="text/javascript">
function ajaxFunction(choice)
{
{
alert(choice.options.length);}
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myObject = JSON.parse(httpxml.responseText);
for(j=document.myForm.state.options.length-1;j>=0;j--)
{
document.myForm.state.remove(j);
}
var state1=myObject.value.state1;
var optn = document.createElement("OPTION");
optn.text = 'Select State';
optn.value = '';
document.myForm.state.options.add(optn);
for (i=0;i<myObject.state.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.state[i];
optn.value = myObject.state[i];
document.myForm.state.options.add(optn);
if(optn.value==state1){
var k= i+1;
document.myForm.state.options[k].selected=true;
}
}
//////////////////////////
for(j=document.myForm.city.options.length-1;j>=0;j--)
{
document.myForm.city.remove(j);
}
var city1=myObject.value.city1;
//alert(city1);
for (i=0;i<myObject.city.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.city[i];
optn.value = myObject.city[i];
document.myForm.city.options.add(optn);
if(optn.value==city1){
document.myForm.city.options[i].selected=true;
}
}
////////////////////
for(j=document.myForm.country.options.length-1;j>=0;j--)
{
document.myForm.country.remove(j);
}
var name1=myObject.value.name1;
var optn = document.createElement("OPTION");
optn.text = 'Select Name';
optn.value = '';
document.myForm.country.options.add(optn);
for (i=0;i<myObject.name.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.name[i];
optn.value = myObject.name[i];
document.myForm.country.options.add(optn);
if(optn.value==name1){
var k= i+1;
document.myForm.name.options[k].selected=true;
}
}
///////////////////////////
document.getElementById("txtHint").style.background='#00f040';
document.getElementById("txtHint").innerHTML='done';
//setTimeout("document.getElementById('txtHint').style.display='none'",3000)
}
}
var url="ajax-dd3ck.php";
var country=myForm.country.value;
if(choice != 's1'){
var state=myForm.state.value;
var city=myForm.city.value;
var name=myForm.name.value;
}else{
var state='';
var city='';
var name='';
}
url=url+"?country="+country;
url=url+"&state="+state;
url=url+"&city="+city;
url=url+"&name="+name;
url=url+"&id="+Math.random();
myForm.st.value=state;
//alert(url);
document.getElementById("txtHint2").innerHTML=url;
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
document.getElementById("txtHint").innerHTML="Please Wait....";
document.getElementById("txtHint").style.background='#f1f1f1';
}
</script>
</head>
<body >
</head>
<body>
<div id="txtHint" style="width : 100px;background-color: #cccc33;">Message area</div>
<br><br>
<form name="myForm" action='ajax-dd3-details.php' method='post'">
<input type=hidden name=st value=0>
<table width=500>
<tr><td >
Select Country<br><select name="country" id="s1" onchange="ajaxFunction(this);">
<option value=''>Select One</option>
<?Php
//require "../include/z_db1.php";
require "config.php";// connection to database
$sql="select distinct country from student5 ";
foreach ($dbo->query($sql) as $row) {
echo "<option value=$row[country]>$row[country]</option>";
}
?>
</select>
</td><td ><select name=state id="s2" onchange="ajaxFunction(this)";>
<option value=''>Select One</option></select></td>
<td ><select name=city id="s3" onchange="ajaxFunction(this);">
<option value=''>Select One</option></select></td>
<td ><select name=sex id="s4" onchange="ajaxFunction(this);">
<option value=''>Select One</option></select></td>
</tr></tr>
<tr><td colspan=3><input type=submit value='Submit'></td></tr>
</form>
</table>
<br><br>
<div id="txtHint2"></div>
</body>
</html>
I edited this php file and added below code. Because I want to add name column from mysql to dropdown:
////////////////////
for(j=document.myForm.name.options.length-1;j>=0;j--)
{
document.myForm.name.remove(j);
}
var name1=myObject.value.name1;
var optn = document.createElement("OPTION");
optn.text = 'Select Name';
optn.value = '';
document.myForm.name.options.add(optn);
for (i=0;i<myObject.name.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.name[i];
optn.value = myObject.name[i];
document.myForm.name.options.add(optn);
if(optn.value==name1){
var k= i+1;
document.myForm.name.options[k].selected=true;
}
}
I also edited the other php file:
<?Php
require "config.php"; // connection details
error_reporting(0);// With this no error reporting will be there
//////////
/////////////////////////////////////////////////////////////////////////////
$country=$_GET['country'];//
//$country='IND'; // To check you can use this
$state1=$_GET['state'];
$city1=$_GET['city'];
$name1=$_GET['name'];
//$state1="Andhra Pradesh";
///////////// Validate the inputs ////////////
// Checking country variable ///
if((strlen($country)) > 0 and (!ctype_alpha($country))){
echo "Data Error";
exit;
}
// Checking state variable (with space ) ///
if ((strlen($state1)) > 0 and ctype_alpha(str_replace(' ', '', $state1)) === false) {
echo "Data Error";
exit;
}
// Checking class variable ///
if((strlen($name1)) > 0 and (!ctype_alpha($name1))){
echo "Data Error";
exit;
}
/////////// end of input validation //////
if(strlen($country) > 0){
$q_country="select distinct(state) from student5 where country = '$country'";
}else{
$q_country="select distinct(state) from student5";
}
//echo $q_country;
$sth = $dbo->prepare($q_country);
$sth->execute();
$state = $sth->fetchAll(PDO::FETCH_COLUMN);
$q_state="select distinct(city) from student5 where ";
if(strlen($country) > 0){
$q_state= $q_state . " country = '$country' ";
}
if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";}
$sth = $dbo->prepare($q_state);
$sth->execute();
$city = $sth->fetchAll(PDO::FETCH_COLUMN);
$q_name="select distinct(name) from student5 where ";
if(strlen($country) > 0){
$q_state= $q_state . " country = '$country' ";
}
if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";}
if(strlen($city1) > 0){$q_city= $q_city . " and city='$city1'";}
$sth = $dbo->prepare($q_city);
$sth->execute();
$name = $sth->fetchAll(PDO::FETCH_COLUMN);
$main = array('state'=>$state,'city'=>$city,'name'=>$name1, 'value'=>array("state1"=>"$state1","city1"=>"$city1", "name"=>"$name1"));
echo json_encode($main);
////////////End of script /////////////////////////////////////////////////////////////////////////////////
?>
I added that code to above:
$q_name="select distinct(name) from student5 where ";
if(strlen($country) > 0){
$q_state= $q_state . " country = '$country' ";
}
if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";}
if(strlen($city1) > 0){$q_city= $q_city . " and city='$city1'";}
$sth = $dbo->prepare($q_city);
$sth->execute();
$name = $sth->fetchAll(PDO::FETCH_COLUMN);
When I open it via LAMP, new dropdown list doesn't work. And I got this error. What can I fix this?
Edit: And here is what i mean with "name"
document.myForm.name.options.length this is giving you error. You have to use the name of select to get options length. So Use like document.myForm.country.options.length
So in your scenario, you have to do like this.
In HTML
<select name=country id='s1' onchange=ajaxFunction(this);>
And in JS
function ajaxFunction(choice) {
alert(choice.options.length);}
I can see a couple of minor errors also which will not help!
<form name="myForm" action='ajax-dd3-details.php' method='post' ">
<input type=hidden name=st value=0>
There is a spurious double quote at the end of the form opening tag, should simply be:
<form name="myForm" action='ajax-dd3-details.php' method='post'>
and you really ought to encase values with quotes in your fields...
<input type='hidden' name='st' value='0' />
Similarly for various other elements within your form, such as:-
<select name=country id='s1' onchange=ajaxFunction('s1');>
should be
<select name='country' id='s1' onchange="ajaxFunction('s1')">
I know others will likely disagree, especially as HTML5 seems more relaxed about this type of thing but it's good practice to adopt and helps figure where things are breaking.
what i'm trying to doing is when user click on php select option.then
it's value should pass to another page as variable.
there is a code i'm
trying.
<table>
<tr><td>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("member")or die(mysql_error());
$result = mysql_query("SELECT id,ugroup FROM ugroups");
?>
<select name='group' id='group' >
<?php
while ($line = mysql_fetch_array($result)) {
echo '<option value=' . $line['ugroup'] . '>' . $line['ugroup'] . '</option>';
}?>
</select>
click
</td></tr>
</table>
this is add_group.php code
<?php
session_start();
ob_start();
include('../limoconfig.php');
if(!isset($_SESSION['adminuserid']) )
{
header('Location:../index.php');
}
else
{
if($_GET)
{
$ugroup = $_GET['ugroup'];
/*$id = $_GET['id'];*/
$acc_status = "update users set ugroup='".$ugroup."' where id=1931";
echo $acc_status;
$rate = db::getInstance()->exec($acc_status);
header('Location:../home.php');
}
}
?>
it's not working.
First of all you need to put your table within
and then you can call ajax on click of your anchor ().
jQuery(document).ready(function($) {
var data='';
$("#group option:selected").each(function() {
if ($(this).attr('value') !== '') {
data=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
type: "POST",
url: "file.php",
data: data,
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
Wrap it in a form tag and create a submit button instead of the link and it can send it in either POST or GET.
The element is a form control and can be used in a form to collect user input.
http://www.w3schools.com/tags/tag_select.asp
you can either do it with ajax or just using html forms.
eg of ajax : Just a simple eg, you can modify according to your need
<html>
<head>
function myAjax(str)
{
if (str=="")
{
document.getElementById("results").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","add_group.php?ugroup="+str,true); // your next page
xmlhttp.send();
}
function myFunction() {
var x = document.getElementById("group").value;
myAjax(x);
}
</script>
</head>
<body>
<table>
<tr><td>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("member")or die(mysql_error());
$result = mysql_query("SELECT id,ugroup FROM ugroups");
?>
<select name='group' id='group' >
<?php
while ($line = mysql_fetch_array($result)) {
echo '<option value=' . $line['ugroup'] . '>' . $line['ugroup'] . '</option>';
}?>
</select>
click
</td></tr>
</table>
<div id="results"> <!-- the echo of add_group.php gets displayed here --> </div>
</body>
</html>
I want to fetch all the records by filtering a role from a dropdown list. This was working perfectly.
(1) But I want to display all the records by default, only when I select the role, all the role users should be filtered.
(2) I want to make my code shorten instead of writing the code two pages, could we fetch all the data from members.php, instead of using memlist.php again.
members.php
<html>
<head>
<script type="text/javascript" src="js/jqueryv1.10.2.js"></script>
<script type="text/javascript">
function showUser(str)
{
document.getElementById("getrole").style.display="block";
if (str =="")
{
document.getElementById("getrole").innerHTML="";
return;
}
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status == 200) { document.getElementById("getrole").innerHTML = xmlhttp.responseText; }
}
xmlhttp.open("GET","memlist.php?role="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo 'Select the role : <select name="users" onchange="showUser(this.value)">';
$sel_role = $db->query('SELECT * FROM role');
$sel_role->execute();
echo '<option selected="selected">Select a role</option>';
while ($row = $sel_role->fetch(PDO::FETCH_ASSOC))
{
$role_id = $row['role_id'];
$role_name = $row['role_name'];
echo '<option value='.$role_id.'>'.$role_name.'</option>';
}
echo '</select>';
echo '<div id="getrole"></div><input type="hidden" value='.$role_id.'>';
?>
</body>
</html>
memlist.php
<?php
require 'init.php';
$uid = $_GET['role'];
$dis_role = $db->prepare('SELECT bu.*, br.* FROM users bu JOIN role br ON bu.role_id = br.role_id WHERE br.id = '.$uid.'');
$dis_role->execute();
echo '<table id="result">
<tr><th><label>USERNAME</label></th>
<th><label>ROLE</label></th>
</tr>';
foreach($dis_role as $dr)
{
echo '<tr>
<td>'.$dr['username'].'</td>
<td>'.$dr['role_name'].'</td>
</tr>';
}
echo '</table>';
?>
I am a newbie on ajax and I try to change a value on my database pending a checkbox. I am using following code:
<script type="text/javascript">
function update(id_submit, check){
check = (check==true ? 1 : 0);
var url = "check_validate.php.php?id_submit="+id_submit+"&chkYesNo="+check;
if(windows.XMLHttpRequest){
req = new XMLHttpRequest();
}
else if(windows.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
req.send(null);
}
</script>
Then I get a other value from my database:
while ($row = mysqli_fetch_array( $result, MYSQL_ASSOC))
{
$check = $row['checkbox'];
$id_submits = $zeile['id_submits'];
?>
<td style='text-align:center;width:120px;'>
<input name="check" type="checkbox" id="check_<?php echo $id_submits; ?>" value="<?php echo $id_submits; ?>" onclick="check(<?php echo $id_submits; ?>, this.checked);"
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
</td><?php
And then I have my "check_validate.php"
$id_submit = $_GET['id_submit'];
$chkYesNo = $_GET['chkYesNo'];
require_once('config.php');
$sql = "UPDATE table1
SET checkbox =$chkYesNo WHERE id_submits = $id_submits";
$result = mysqli_query( $link, $sql );
But nothing happens on my database, what am I doing wrong?
I have a combobox and i want to fill the State and Zip_code Field..its working but it fills each field State "NY11715" and Zip_code "NY11715"...i'm looking to fill State "NY" and Zip_code 11715...please help me resolve this
<select name="LookupCity" id="LookupCity" onchange="showZip(this.value)">
<option value="" <?php if (!(strcmp("", $_GET['City']))) {echo "selected=\"selected\"";} ?>>Select from menu</option>
<?php do { ?>
<option value="<?php echo $row_fmCity['City']?>"<?php if (!(strcmp($row_fmCity['City'], $_GET['City']))) {echo "selected=\"selected\"";} ?>><?php echo $row_fmCity['City']?></option>
<?php
} while ($row_fmCity = mysql_fetch_assoc($fmCity));
$rows = mysql_num_rows($fmCity);
if($rows > 0) {
mysql_data_seek($fmCity, 0);
$row_fmCity = mysql_fetch_assoc($fmCity); } ?> </select>
select</td>
</tr><tr valign="baseline">
<td nowrap="nowrap" align="right">State:</td>
<td><input type="text" name="State" id="State" placeholder="NY" value="<?php echo $_GET['State']; ?>" size="5"/>
<input type="text" name="Zip_Code" id="Zip_Code"placeholder="zip code" value="<?php echo $_GET['Zip']; ?>" size="10" /></td>
Ajax code
function showZip(str)
{
if (str=="")
{
document.getElementById("State").innerHTML="";
document.getElementById("Zip_Code").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Getzip.php?q="+str,true);
xmlhttp.send();
}
PHP Code
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Leadbook", $con);
$sql="SELECT * FROM Zip WHERE City = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$State = $row['State'];
$Zip_Code = $row['Zip Code'];
}
echo $State;
echo $Zip_Code;
mysql_close($con);
?>
1. change your php code, so that both city and zip code are comma seperated.
change this code:
echo $State;
echo $Zip_Code;
to this:
echo $State;
echo ",";
echo $Zip_Code;
2. than update your javascript, so that the return text is splitted into 2 parts and gets to its respected fields.
change this code:
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
to this:
var string = xmlhttp.responseText;
var array = string.split(',');
document.getElementById("State").value=array[0];
document.getElementById("Zip_Code").value=array[1];
this should do what you requested.