dropdown with php and ajax - php

For some time I am battling to solve this problem but I am not coming to any conclusion so thought to seek some help here.
The problem is that I am getting a blank dropdown instead I should get list of cities populated from the database. Database connection is fine but I am not getting anything in my dropdown.
This is what I am doing:
<?php
require 'includes/connect.php'; - database connection
$country=$_REQUEST['country']; - get from form (index.php)
$q = "SELECT city FROM city where countryid=".$country;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
if ($result) {
?>
<select name="city">
<option>Select City</option>
$id = 0;
<?php while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value= <?php $id ?> > <?php $src ?></option>
<?php } ?>
</select>
<?php } ?>
ajax script is this:
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{mlhttp=new XMLHttpRequest();}
catch(e) {
try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e){ try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
This is my form code:
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
<option value="">Select Country</option>
<option value="1">New Zealand</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
<option>Select City</option>
</select></div></td>
</tr>
</table>
</form>

I think the problem is where you are outputting the <option> tags.
Try using this block of code between your <select> tags.
<option>Select City</option>
<?php
$id = 0;
while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value="<?php echo htmlspecialchars($id,ENT_QUOTES) ?>"><?php echo htmlspecialchars($src) ?></option>
<?php } ?>
Edit: To clarify, you didn't have any echo statements before the $id and $src variables. I added htmlspecialchars() as a habit to produce properly escaped html.

A few things to try:
If you request findcity.php manually in your browser with a city you know exist in the database, will i return the correct HTML?
Try with FireBug or another javascript debugger, to set a breakpoint in the onreadystatechange function and see if the returned values are as expected. Set the breakpoint at the first line of the function.

<input name="acname" type="text" id="acname" value="" maxlength="9">
Account Name </p>
<select name="src">
<option value="number"> :::: Select ::::</option>
<option value="did">DID</option>
<option value="tfn">TFN</option>
</select>
<span id="errmsg"></span> DID/TFN </p>
<select name="did" onchange='OnChange(this.form1.did);' >
<option value=""> :::: Select ::::</option>
<? $qry1 = mysql_query("SELECT * FROM ".NUMBERS." where Flag='1'") or die(mysql_error()) ;
while($res1 = mysql_fetch_array($qry1)) { ?>
<option value="<?=$res1['Numbers'] ?>"><?=$res1["Numbers"]?></option>
<? } ?>
</select>
SOURCE

Related

Alternative for huge database list

Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.

Having problems getting a $_GET or $_POST to work with ajax

I have this code in my find.php file:
<select name="EmpName" required="required" id='empn'>
<option value="" style="display:none;"></option>
<?php
//get the employee id
$employeeId = $_POST['country'];
//make connection to database, bail if no connection
$connection = odbc_pconnect('db','','');
if (!$connection) { exit("Connection Failed: " . $connection); }
//retrieve usernames and passwords
$sql = "SELECT EName FROM LoginTable WHERE EmployeeID='$employeeId'";
$rs = odbc_exec($connection, $sql);
while(odbc_fetch_row($rs)) {
$rowJobNum = odbc_result($rs, 'EName');
printf("<option value='%s'>%s</option>", $rowJobNum, $rowJobNum);
}
?></select>
I have this code in my index.php file:
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getCity('find.php?country='+this.value)">
<option value="">Select Country</option>
<option value="1">mg05</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
</select></div></td>
</tr>
</table>
</form>
</body>
</html>
Here's the issue... I can't access the selection from the first drop down menu, the selection from the drop down menu is never going through to find.php. For reference, mg05 in the drop down list is an employee ID, I am working off an example here that was originally formatted for cities/states etc.
Here's my big issue, if I go to:
$sql = "SELECT EName FROM LoginTable WHERE EmployeeID = '$employeeId'";
and change it to
$sql = "SELECT EName FROM LoginTable WHERE EmployeeID= 'mg05'";
It works perfectly, and returns the correct result. So... obviously the post of data from index.php to find.php isn't working and I can't figure out why. I have $_GET and $_POST working in other areas of my site, but not this one.
Any insight as to where I may have gone wrong? I've tried using both get and post and nothing has worked.
The problem is that you are expecting the displayed text in the select to be post. This will not occur if the selected option has a value attribute, the value attribute will be used
<select name="country" onChange="getCity('find.php?country='+this.value)">
<option value="">Select Country</option>
<option value="mg05">mg05</option>
<option value="Canada">Canada</option>
</select>

form does not posting the data of filtered field?

i am fetching categories and their sub-categories from the database.
and filtering the sub-categories after selecting the category bu using dropdown.
after selecting when i submit the form, the value of the sub-category is 0, form does not posting the selected value.
<?php
if(isset($_POST) && $_POST['submit'] == "Add")
{
extract($_POST);
$scat_id = $regions['scat_id'];
echo $sqlpa = "INSERT INTO products(mcat_id, scat_id)VALUES('$mcat_id', '$scat_id')";
$resultpa = mysql_query($sqlpa);
}
?>
<script type="text/javascript">
function getregions(mcat_id) {
if (mcat_id=="") {
document.getElementById("region").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("region").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getregions.php?mcat_id="+mcat_id,true);
xmlhttp.send();
}
</script>
<form action="" method="post" name="p_add" id="p_add">
<table>
<tr>
<td>Select Category</td>
<td><select name="mcat_id" id="mcat_id" onchange="getregions(this.value);">
<option value="">Select</option>
<?php
if(!empty($resultm)) {
foreach($resultm as $rm) {
?>
<option value="<?php echo $rm['mcat_id']; ?>"><?php echo $rm['mcat_name'];?> (<?php echo $rm['mcat_id']; ?>)</option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td>Select Sub-Category</td>
<td>
<div id="region">
<select name="scat_id" id="scat_id">
<option value="">Please Select</option>
</select>
</div>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add" /></td>
</tr>
</table>
</form>
-->this page is getregions.php where filtering is done:
<?php
include "../conn.php";
$mcat_id=$_GET['mcat_id'];
$sql = "SELECT * FROM sub_category WHERE mcat_id = '".$mcat_id."'";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
$rec[] = $row ;
}
?>
<select name="scat_id" id="scat_id">
<option value="">Please Select</option>
<?php
foreach($rec as $regions) {
?>
<option value="<?php echo $regions['scat_id'];?>"><?php echo $regions['scat_name'];?></option>
<?php
}
?>
</select>
just before the insert query, i need to write
$scat_id = $_post['scat_id'];
this will get the posted value.

If no value selected from dropdown, allow textbox to add to mysql table using php, mysql, javascript

hi i'm working on triple dropdown for country, state, city using ajax and the reference link is : http://roshanbh.com.np/2008/01/populate-triple-drop-down-list-change-options-value-from-database-using-ajax-and-php.html. It successfully working but i need if a state has no city in db table then a new text box is appear and the entered values is store in php mysql. what coding i'm implement that. please give some ideas.
code:
Ajax:
<script language="javascript" type="text/javascript">
function getXMLHTTP() {
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
function getState(countryId) {
var strURL = "findState.php?country=" + countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML = req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
function getCity(countryId, stateId) {
var strURL = "findCity.php?country=" + countryId + "&state=" + stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML = req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Form:
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getState(this.value)">
<option value="">Select Country</option>
<option value="1">USA</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>State</td>
<td ><div id="statediv"><select name="state" >
<option>Select Country First</option>
</select></div></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
<option>Select State First</option>
</select></div></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
findstate.php
<?php
include('config.php');
$country = intval($_GET['country']);
$query = "SELECT id,statename FROM state WHERE countryid='$country'";
$result = mysql_query($query);
?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['id']?>><?php echo $row['statename']?></option>
<?php } ?>
</select>
findcity.php
<?php
include('config.php');
$countryId = intval($_GET['country']);
$stateId = intval($_GET['state']);
$query = "SELECT id,city FROM city WHERE stateid='$stateId'";
$result = mysql_query($query);
?>
<select name="city">
<option>Select City</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value><?php echo $row['city']?></option>
<?php } ?>
</select>
I want to show if there is no city in any state then a textbox will appear and it's value store to db.
Put this inside findcity.php file
<?php
include('config.php');
$countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$query="SELECT id,city FROM city WHERE stateid='$stateId'";
$result=mysql_query($query);
if(mysql_num_rows($result) == 0) // no cities found
{
echo '<input type="textbox" name="city" />';
}
else // show select box
{
?>
<select name="city">
<option>Select City</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value><?php echo $row['city']?></option>
<?php } ?>
</select>
<?php
}
?>
Your findstate.php becomes this
<?php
include('config.php');
$country=intval($_GET['country']);
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysqli_query($query);
if(mysqli_num_rows($result)==0):?>
<input type="text" name="state" value="" />
<? endif; ?>
<select name="state" onchange="getCity(<?=$country ?>,this.value)">
<option>Select State</option>
<?php while($row=mysqli_fetch_array($result)): ?>
<option value=<?= $row['id']?>><?= $row['statename']?></option>
<?php endwhile; ?>
</select>
Similarly change your findcity.php aswell.
Suggestions
Never use mysql* anymore use mysqli* or PDO as mysql* is depricated. Link

Issue With the Ajax's derived Selection box

<script type="text/javascript" src="jquery-1.js"></script>
<style type="text/css">
div {
height:25px;
}
label {
text-align:left;
width:100px;
display:inline-block;
vertical-align:top;
}
input {
margin-right:5px;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
// $('select').toggle();
$('input').click(function(event) {
$(this).closest('div').children('select').toggle();
});
});
//]]>
</script>
<?php
#mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
$query = "select id,language,code from language WHERE first=1";
$results = mysql_query( $query);
$lang = array();
while ($rows = mysql_fetch_assoc(#$results)){
$lang[$rows['language']] = $rows['code'];
}
?>
<form action="" method="post" name="myForm" id="myForm" >
<?php
foreach($lang as $key=>$value){ ?>
<div>
<label for="lang_<?=$value;?>" >
<input name="language[<?=$value;?>]" id="lang_<?=$value;?>" value="1" type="checkbox">
<?=$key;?>
</label>
<select style="display: none;" name="level[<?=$value;?>]" id="f_level_<?=$value;?>">
<option selected="selected" value="">your level</option>
<option value="Low">Low</option>
<option value="Average">Average</option>
<option value="Fluent">Fluent</option>
<option value="Native">Native</option>
</select>
</div>
<?php } ?>
<input value="submit" name="submit" type="submit">
<!--**********************************************************-->
<br />
<br />
<br />
<script type="text/javascript">
function showCD(str)
{
if (str == "") {
document.getElementById("txtHint").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("newone").innerHTML=xmlhttp.responseText;
$('#newone').append(xmlhttp.responseText);
// document.getElementById('newone').appendChild(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "123.php?q=" + str, true);
xmlhttp.send();
}
</script>
<?php
#mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
$query = "select id,language,code from language WHERE first=0";
$results = mysql_query( $query);
$lang = array();
while ($rows = mysql_fetch_assoc(#$results)){
$lang[$rows['language']] = $rows['code'];
}
?>
<select name="level[]" id="f_level" onchange="showCD(this.value)">
<option selected="selected" value="">language</option>
<?php
$results = mysql_query( $query);
while ($rows = mysql_fetch_assoc(#$results)){
?>
<option value="<?php echo $rows['id'];?>" ><?php echo $rows['language'];?></option>
<?php
}
?>
</select>
<div id="newone"></div>
</form>
---------------
<?php
mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
if($_REQUEST)
{
$id = $_REQUEST['q'];
$query = "select id,language,code from language where id = ".$id;
$results = mysql_query( $query);
$rows = mysql_fetch_assoc($results );
if($rows!='')
{?>
<div>
<label for="lang_<?=$rows['code'];?>" >
<input name="language[<?=$rows['code'];?>]" id="lang_<?=$rows['code'];?>" value="1" type="checkbox">
<?=$rows['language'];?>
</label>
<select style="display: none;" name="level[<?=$rows['code'];?>]" id="f_level_<?=$rows['code'];?>">
<option selected="selected" value="">your level</option>
<option value="Low">Low</option>
<option value="Average">Average</option>
<option value="Fluent">Fluent</option>
<option value="Native">Native</option>
</select>
</div>
<?php
}
return;
}
?>
Unfortunately I can't yet comment everywhere so apologies for adding an answer when a comment would have sufficed.
2 suggestions for you:
1) You are using jQuery but not making use of its excellent AJAX functions. Take a look at them.
2) You are suppressing PHP warnings and errors that may be helpful to you debugging this yourself. Remove the # from the front of several of these function calls and run it again. Maybe you will see the problem yourself.
The only other thing that jumped out at me while scanning this code (since I have no idea what your problem is) is that the derived responce does not include the 'onchange' event that all of your other selects do. Is it a simple oversight?

Categories