Hoping someone can help. I have dynamic drop-downs that have been working great until I added a new item with a space in it. It's confusing me because my second drop-down has items with spaces and the query runs fine with those but the first drop-down fails. I've tried to find any differences that would cause one to fail but I just can't see it. It's been a mixture of scripts that I found and I'm really new to Javascript and PHP so I'm lost. I hope someone can point me to my error. Here's the code I think you need to see The first script is the one that controls the dropdown that is failing the second one is working:
<script type="text/javascript">
function AjaxFunction()
{
var ddstring = document.getElementById("name");
var ddindex = ddstring.options[ddstring.selectedIndex].value;
if (ddindex != 0){
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 stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.searchform.type.options.length-1;j>=0;j--)
{
document.searchform.type.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.searchform.type.options.add(optn);
}
{
var optn2 = document.createElement("OPTION");
optn2.text = "Select Type";
optn2.value = '%';
document.searchform.type.options.add(optn2,0);
}
{
document.searchform.type.disabled=false;
document.searchform.type.selectedIndex = 0;
var defaultdd = "<?php echo $_SESSION['type'] ?>";
if (defaultdd != ""){
document.getElementById('s2').value = defaultdd;
if (defaultdd != "%"){
AjaxFunction2();
}
}
}
}
}
var url="dd.php";
var cat_id=document.getElementById('name').value;
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
else {
document.searchform.type.selectedIndex = 0;
document.searchform.subcat.selectedIndex = 0;
document.searchform.type.disabled=true;
document.searchform.subcat.disabled=true;
}
}
</script>
<script type="text/javascript">
function AjaxFunction2()
{
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 stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.searchform.subcat.options.length-1;j>=0;j--)
{
document.searchform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.searchform.subcat.options.add(optn);
}
{
var optn2 = document.createElement("OPTION");
optn2.text = "Select Series";
optn2.value = '%';
document.searchform.subcat.options.add(optn2,0);
}
{
document.searchform.subcat.disabled=false;
document.searchform.subcat.selectedIndex = 0;
var defaultdd = "<?php echo $_SESSION['subcat'] ?>";
if (defaultdd != ""){
document.getElementById('s3').value = defaultdd;
}
}
}
}
var url="dd2.php";
var cat_id=document.getElementById('name').value;
var cat_id2=document.getElementById('s2').value;
url=url+"?cat_id="+cat_id;
url=url+"&cat_id2="+cat_id2;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
The Form Elements:
<form name="searchform" method='POST' action='?'>
<table width="534" border="1" cellspacing="10" ID="tdspace">
<tr>
<td>Manufacturer: </td>
<td><select name=name id='name' onchange=AjaxFunction();>
<option value='%'>Select One</option>
<?Php
try {
$dbo = new PDO('mysql:host=localhost;dbname='. $dbname, $username, $password);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sql="SELECT Distinct Manufacturer FROM `tbl_Printers` order by `Manufacturer` asc ";
foreach ($dbo->query($sql) as $row) {
if ($row[Manufacturer] == $_SESSION['name'])
$selected = "selected=\"selected\"";
else
$selected = "";
echo "<option value=$row[Manufacturer] $selected>$row[Manufacturer]</option>";
if( $_SESSION['type'])
{ echo '<script type="text/javascript">AjaxFunction()</script>';
}
}
?>
<?php
if ( $_SESSION['name'] == ""){ $namevalue = 'None Selected';}
else {$namevalue = $_SESSION['name'];}
if ( $_SESSION['type'] == "%"){ $typevalue = 'None Selected';}
else {$typevalue = $_SESSION['type'];}
if ( $_SESSION['subcat'] == "%"){ $subvalue = 'None Selected';}
else {$subvalue = $_SESSION['subcat'];}
?>
</select></td>
<td>Manufacturer:<span style="color:cyan"> <?php echo $namevalue;?></span></td>
</tr>
<tr>
<td>Product Type: </td>
<td><select name=type id='s2' onchange=AjaxFunction2(); disabled=true>
<option value='%' selected>Select Type</option>
</select></td>
<td>Product Type:<span style="color:magenta"> <?php echo $typevalue?></span></td>
</tr>
<tr>
<td>Printer Catagory:</td>
<td><select name=subcat id='s3' disabled=true>
<option value='%' selected>Select Series</option>
</select></td>
<td>Printer Series:<span style="color:yellow"> <?php echo $subvalue;?></span></td>
</tr>
<tr>
<td height="27" colspan="2" ID="centered" style="padding-left:90px"><br /> <input type=submit onclick="s3.disabled=false; s2.disabled=false" class="quick-search-button btn"/></td>
<td>Records Found:<span style="color:black; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4)"> <?php echo $_SESSION['totalrecords'];?></span></td>
</tr>
<tr>
<td height="28" colspan="3" style="text-align:center"><br />
*Manufacturer is Manditory, all other fields optional. </td>
</tr>
</table>
<br />
<br />
<p><div id="finish">
</p></div>
</form>
This is the php page that is supposed to return the results for the first drop-down although the second drop-down form is practically identical and works:
<?Php
#$cat_id=$_GET['cat_id'];
//$cat_id=2;
$dbhost_name = "localhost";
$database = "database";// database name
$username = "username"; // user name
$password = "password"; // password
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$str='';
$sql="SELECT Distinct Type FROM `tbl_Printers` where Manufacturer='$cat_id' order by Type asc";
foreach ($dbo->query($sql) as $row) {
$str=$str . "$row[Type]".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
//$main = array($str);
echo json_encode($str);
//echo $str;
?>
I appreciate any help, I've tried searching and normally I don't ask for help but this one is just to far beyond my understanding.
For the moment I have replaced all of my queires to read like this (There are a lot of them considering the paging...) I don't see this as an answer though just a work around.
"SELECT Distinct Type FROM `tbl_Printers` where Manufacturer Like CONCAT('%', '$cat_id', '%') order by Type asc"
The thanks go to Vigour for pointing me in the correct direction. Unfortunately I can't select a comment as the answer or post an answer for my own question until tomorrow because of my reputation, but thank you so much for finding the issue.
The line of code causing the issue was:
echo "<option value=$row[Manufacturer] $selected>$row[Manufacturer]</option>";
It needed to be changed to this to add the quotes as needed and still select the proper saved item:
echo "<option value='" . $row['Manufacturer']."' ".$selected." >" . $row['Manufacturer'] . "</option>";
Better test it, but I think the JS should replace the empty string with + sign in order to pass it correctly:
Replace:
var cat_id=document.getElementById('name').value;
With:
var cat_id=document.getElementById('name').value.replace('/ /gi','+');
You should add the option values with quotation marks, otherwise the spaced values will not be passed.
<option value="Kyocera Mita" >Kyocera Mita</option>
Related
I have the following js script that triggers onChange of the select box below.
It then retrieves data from a table and returns some input fields populated with the data (using PHP code below). Then saves the data.
This part works fine.
However, if I run the script again, and it populates the selected option from DB and shows as a selected option, but it does not display the populated input fields returned from the PHP code/DB query since I am not triggering the onChange again.
I tried to add 'window.onload = showAgentOne;' under the JS for the onChange function, assuming it would see the value in (str) from the select box, but I am probably missing something as it does not work.
New to JS - I hope this makes sense.
JS:
function showAgentOne(str) {
if (str == "") {
document.getElementById("agent1").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("agent1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user_agent1.php?q=" + str, true);
xmlhttp.send();
}
window.onload = showAgentOne; // trigger function on pageload - not working
HTML:
<select name="narid" onchange="showAgentOne(this.value)" class="form-control">
<option selected="selected" disabled value="">select agent</option>
<?php
$sql = "select last_name, first_name, active, nrds_id from ft_form_2 ORDER BY last_name";
$sql_result = mysqli_query($mysqli,$sql);
while ($row = mysqli_fetch_array($sql_result)) }?>
<option value="<?php echo $row[" nrds_id "]; ?>" <?php if($narid_agent1==$ row[ "nrds_id"]) { echo ' selected '; } ?> >
<?php echo strtoupper($row["last_name"]) . ' > ' . $row["first_name"] . ' ' . $row["last_name"] . ' ['.$active.']'; ?>
</option>
<? } ?>
</select>
<div id="agent1"></div>
PHP (user_agent1.php) ------------------------- $q=$_GET["q"]; $sql="SELECT pay_to_name,nrds_id FROM ft_form_2 WHERE nrds_id = $q"; $result = mysqli_query($mysqli,$sql); while($row = mysqli_fetch_array($result)) { ?>
<input type="text" name="narid_agent1" value="<?php echo $row['nrds_id']; ?>">
<input type="text" name="pay2_agent1" value="<?php echo $row['pay_to_name']; ?>">
<?php } ?>
'window.onload = showAgentOne;' is a good try but it is expecting a str param, otherwise it returns and do nothing. That's why nothing happens.
You will have to try something like
window.onload = function (event) {
let str = 'ADD_YOUR_VALUE_HERE';
showAgentOne(str);
}
But I can't help you with what str should be.
I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)
It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.
I'm developing a website which allow the user to do query on a public database and I would like to allow the user to see the query he has done during the current session and delete one of them he wants to.
here is the code creating $_SESSION['history']:
$_SESSION['history'][] = array(
'Database' => $_SESSION['db'],
'Choice' => $_SESSION['radio'],
'Query' => $_SESSION['query'],
'Résult' => ($asResults),
'Date' => date("d-m-Y"),
'Hour' => date("H:i:s")
);
here is the code displaying the array of the $_SESSION['history']:
<?php
function displayHistory($arQueryArray)
{
if (isset($_SESSION['history']))
{
echo '<table id="history" class="display">';
$iQueryNumber = 0;
echo '<thead><tr>';
echo '<th>n°</th>';
foreach (array_keys($_SESSION['history'][0]) as $field)
{
if ($field != 'Résult' and $field != 'Choice')
{
echo '<th>', $field, '</th>';
}
}
echo '<th></th><th></th>';
echo '</tr></thead>';
echo '<tbody>';
foreach ($_SESSION['history'] as $query)
{
echo '<tr>';
echo '<td>', ($iQueryNumber + 1), '</td>';
foreach ($query as $field => $value)
{
if ($field != 'Résult' and $field != 'Choice' and $field != 'Requête')
{
echo '<td>', $value, '</td>';
}
else if ($field == 'Query')
{
echo '<td>' . $arQueryArray[$query['Choice']] . " " . $query['Query'] . '</td>';
}
}
?>
<td>
<input type="button" class="del_btn" value="X" title="Delete this query" onclick="delQueryInHistory(<?php echo $iQueryNumber; ?>, this);"/>
</td>
<?php
echo '</tr>';
$iQueryNumber += 1;
}
echo '</tbody></table>';
}
else
{
echo "<p>No query</p>";
}
}
?>
Here is the javascript:
var XHR = null;
function getXMLHTTP()
{
var xhr = null;
if(window.XMLHttpRequest)
{ // Firefox
xhr = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // Internet Explorer
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
xhr = null;
}
}
}
else
{ // XMLHttpRequest not supported
alert("YOur browser doesn't support XMLHTTPRequest...");
}
return xhr;
}
//Query suppression function
function delQueryInHistory(queryId, self)
{
XHR = getXMLHTTP();
XHR.open("GET", "controleur/delQueryInHistory.php?queryId=" + queryId, true);
XHR.onreadystatechange = function()
{
if (XHR.readyState == 4)
{
self.parentNode.parentNode.parentNode.removeChild(self.parentNode.parentNode);
}
}
XHR.send();
}
Here is the php called
<?php
session_start();
if(empty($_GET['queryId']) or !is_numeric($_GET['queryId']) or !isset($_GET['queryId']))
{
exit;
}
else
{
unset($_SESSION['history'][intval($_GET['queryId'])]);
}
?>
The problem is that it simply doesn't run and i don't understand why since i have not any error raised! Even if i use a corrupted php file... I have already verified that the path to the php file is OK!
Sorry for my English, and thanks..
** Last UPDATE:** Sorry, I've forgotten to say what specially didn't run: The row is correctly removed but the $_SESSION['history'][queryId] is not removed! But the XmlHttp object has been created! Thanks.
I've found how to fix the issue, maybe it could help
<?php
session_start();
if(empty($_GET['queryId']) or !is_numeric($_GET['queryId']) or !isset($_GET['queryId']))
{
exit;
}
else
{
unset($_SESSION['history'][$_GET['queryId']]);
$_SESSION['history'] = array_values($_SESSION['history']);
}
?>
the unset() function doesn't normalize integer indexes and it broke my code during the display!
I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment
Complete Dynamic drop down in PHP MySQL & AJAX with mysql Insert query works perfectly.
Code to insert date to MySQL table
<?php
require('../conn/include.php');
require('quick.php');
$query="SELECT * FROM category";
$result=mysql_query($query);
$project=$_POST['project'];
$alttext=$_POST['alttext'];
$relation=$_POST['state'];;
if(isset($_FILES['image'])) {
$errors=array();
$allowed_ext=array('jpg','png','jpeg','JPG');
$filename=$_FILES['image']['name'];
$name=stripslashes($filename);
$type=strtolower(end(explode('.',$filename)));
$size=$_FILES['image']['size'];
$file_tmp=$_FILES['image']['tmp_name'];
if(in_array($type,$allowed_ext) ===false) {
$errors[]= "<span class=\"notification n-error\">Extenstion Not Allowed</span>";
}
if($size > 1048576) {
$errors[]= "<span class=\"notification n-error\">File must be less then 2mb</span>";
}if(file_exists('../../images/a/gallery/'.$filename)) {
$errors[]= "<span class=\"notification n-error\">File $filname Already Exists in directory</span>";
}if(empty($errors)) {
if(move_uploaded_file($file_tmp, '../../images/a/gallery/'.$filename)) {
$insert="Insert into `my`.gallery(name,alttext,project,relation)VALUE('$name','$alttext','$project','$relation')";
//echo $insert;
$que=mysql_query($insert);
echo "<span class=\"notification n-success\">File $filname Uploaded Sucessfully</span>";
header('Refresh:3; url:gallery.php');
}
}else {
foreach($errors as $error) {
echo $error,'<br/>';
}
}
}
?>
AJAX Code
<script language="javascript" type="text/javascript">
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 getState(cate_id) {
var strURL="findsect.php?country="+cate_id;
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("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Code for Second Drop Down or findsec.php
<?php
$country=$_GET['country'];
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my');
$query="SELECT * FROM gallery_section WHERE related='$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['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
Thanks to Nick Wilde who helped me.
I'm presuming you mean when the value of the option for the second drop down is multiple words. If that is the case the problem is you are missing quotes; use this instead:
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
as the last three lines of your findsec.php