filling innerhtml of dropdown menu with specific data - php

I have a xmlhttp/php problem. I have one drop-down menu where people are able to select municipality. Then I want to return a list of possible options within that municipality to a secondary drop-down menu.
people first select a municipality (html code below):
<select name="pszplaats" id="gemeente" onchange="fdisplay();loadXMLDoc(this.value)">
<?php while($row=mysql_fetch_array($selectgem)){?>
<option value="<?php echo $row['Gemeente']; ?>"><?php echo $row['Gemeente'];?>
</option>
<?php } ?>
</select>
loadXMLDoc is the function that should send this answer to the (php-)server and retreive a list of names matching those in that municipality.
so far my relevant java/xml/ajax code is this:
function loadXMLDoc() {
var xmlhttp;
gem=document.getElementById("gemeente").value;
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("test").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","http://www.doenwatikkan.nl/jeroen/dynamic.php",true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send();
alert(gem)
}
Alert(gem) shows the selected option, so I know that at least this works.
the php to retreive the right values is this:
$gem=$_POST["pszplaats"];
$gennam=mysql_query("SELECT * FROM psz WHERE Gemeente=$gem");
echo $gennam["$gem"];
now the problem lies in the filling of the secondary drow-down menu
<select name="psznaam" id="test" style="display:none">
<?php while($row=mysql_fetch_array($selectall)){?>
<option value="<?php echo $row['NaamPSZ']; ?>"><?php echo $row['NaamPSZ'];?>
</option>
<?php } ?>
</select>
after the java function is finished the drop-down menu is completely empty. Can anybody tel me how I can actually get the relevant data in that menu?
any help would be much appreciated!

you have not sent gem with the url. try xmlhttp.open("POST","http://www.doenwatikkan.nl/jeroen/dynamic.php?gem="+gem,true);
and in your dynamic.php page pick it up by $_POST["gem"]

Related

making 3 select tag with php and ajax

this is my first day with AJAX, is easier than i imagine , i make one select tag that open another select tag and it work fine
that is the code...
test.php
<?php
require'models/category.php';
$object=new category;
$rows=$object->display_category();
?>
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="choose a category";
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getTest.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a category:</option>
<?php
foreach($rows as $row){
$row['cat_name']=str_replace('-',' ',$row['cat_name']);
echo'<option value="'.$row['cat_id'].'">'.$row['cat_name'].'</option>';
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>category info will be listed here.</b></div>
</body>
</html>
and this is getTest.php
<?php
require'models/connection.php';
$q = $_GET['q'];
$query="select * from category where parent_id='".$q."' ";
$stmt=$db->prepare($query);
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<form action='' method='get'>
<select name='select1'>
<?
foreach ($result as $one){
echo'<option value="'.$one["cat_id"].'">'.$one['cat_name'].'</option>';
}
?>
</select>
</form>
there is one select tag in test.php
and when i choose a certain option
another select tag open, which existing in getTest.php
now i want third select tag,,
when i choose from the second select tag , another one is appear.
i don't know where is that action must done ,, in test.php or in getTest.php
the third select that i want to appear of course is depends on the second select choice,,thanks in advance
I suggest you to change your codes like this, In this way you can use millions of selects without any problem.
I commented my changes on your code to better visibility.
test.php
<?php
require'models/category.php';
$object=new category;
$rows=$object->display_category();
?>
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str,targetId) {//// add targetId here
if (str=="") {
document.getElementById("txtHint").innerHTML="choose a category";
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(targetId).innerHTML=xmlhttp.responseText;// this is my added data
document.getElementById(targetId).style.display = 'block';//update #2
}
}
xmlhttp.open("GET","getTest.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value,select1)"><!-- add ,1 here -->
<option value="">Select a category:</option>
<?php
foreach($rows as $row){
$row['cat_name']=str_replace('-',' ',$row['cat_name']);
echo'<option value="'.$row['cat_id'].'">'.$row['cat_name'].'</option>';
}
?>
</select>
<!-- This section is added completely -->
<br>
<select id='select1' name='select1' onchange="showUser(this.value,select2)" style="display:none">
</select>
</form>
<br>
<br>
<select id='select2' name='select2' style="display:none">
</select>
</form>
<br>
<!-- End of added section -->
<div id="txtHint"><b>query status will be listed here.</b></div> <!-- category info will not listed here -->
</body>
</html>
getTest.php
<?php
require'models/connection.php';
$q = $_GET['q'];
$level = $_GET['level'];
$query="select * from category where parent_id='".$q."' "; ////DANGER! There is a sql injection vulnerability! Don't do this in your main site never ever
$stmt=$db->prepare($query);
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $one){
echo'<option value="'.$one["cat_id"].'">'.$one['cat_name'].'</option>';
}
?>
But there is a vulnerability in your sql query that makes your site in danger of sql injection attacks, changing the query code in getTest.php to this one is a good work. but you must check whole your codes with a pentester of course.
Vulnerable code
$query="select * from category where parent_id='".$q."' ";
$stmt=$db->prepare($query);
$stmt->execute();
must change to this one:
$query="select * from category where parent_id=:id ";
$stmt->execute(['id'=>$q]);
for more details about this problem, read this post: How can I prevent SQL-injection in PHP?
This is pretty same as you done with first one.
First write another function in test.php like you did "showUser" and perform action according to requirement.
Then in getTest.php return html with following.
<select name='select1' onchange="showUser(this.value)">
So make sure you pass the same function in getTest.php in select that you code newly.

JSON Parse xmlhttp.requestText

I have a form that has a dynamic drop down select that when a value is selected it auto populates two other form fields, short and long description. I am trying to use Ajax to retrieve the short and long desc based on the value of the drop down select. I can receive the xmlhttp.responseText data and display it back on the form page but I am unable to parse the responseText out to the respective form fields.
You can see the responseText displayed above "Add New Record" title. It might be hard to read so here it is again: (I was thinking I might have the wrong format)
{"Stitl":"CHF STAFF","Ltitl":"Chief Of Staff"}
HTML file:
<form id="addForm" method="post" action="units_add.php">
<legend>Add New Record</legend>
<label for="titleOrg" class="control-label">Title Org</label>
<select class="form-control" name="titleOrg" id="titleOrg" onChange="populate(this.value)">
<option value=" "></option>
<?php
while ($rowl1l5s = $l1l5Result->fetch_assoc()) {
echo "<option value=". $rowl1l5s['l1l5']. ">";
echo $rowl1l5s['l1l5'] . "&nbsp&nbsp&nbsp&nbsp" .$rowl1l5s['Ltitl']; ;
echo "</option>";
}?>
</select>
<label for="shortDesc" class="control-label">Short Desc</label>
<input name="shortDesc" class="form-control" id="shortDesc" type="text" readonly="readonly">
<label for="longDesc" class="control-label">Long Desc</label>
<input name="longDesc" class="form-control" id="longDesc" type="text" readonly="readonly">
<button type="submit" class="btn btn-default" id="save"><i class="glyphicon glyphicon-ok glyphicon-white"></i> Save</button>
<a href="FDMAMaint_V10.php"
<button class="btn btn-default" id="cancel"><i class="glyphicon glyphicon-remove"></i> Cancel</button>
</a>
</form>
Then the user selects a value from the dynamic drop down it executes this JS function:
function populate(str)
{
if (str=="")
{
document.getElementById("shortDesc").innerHTML="";
return;
}
// Create an object
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)
{
data = xmlhttp.responseText;
document.getElementById("messages").innerHTML=xmlhttp.responseText;
document.getElementById("shortDesc").value=xmlhttp.responseText.shortDesc
document.getElementById("longDesc").value=xmlhttp.responseText.second;
}
}
xmlhttp.open("GET","getl2l5.php?q="+str,true);
xmlhttp.send();
}
I know that the following code (see below) doesn't work because it's being referenced wrong, plus it hasn't been parsed yet. I was just throwing that in there for reference as to why the form fields are "undefined"
document.getElementById("shortDesc").value=xmlhttp.responseText.shortDesc
document.getElementById("longDesc").value=xmlhttp.responseText.second;
Then the JS function goes out to the getL2L5 PHP script:
<?php
define('DBHOST','**************');
define('DBUSER','********');
define('DBPASS','**********');
define('DBNAME','**********');
//Connect to database
if (!$db = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME)) die("Can't connect to database");
// Retrieve the value from the title org drop down select
$q = $_GET['q'];
// Pull the Ltitl and Stitl based on the drop down value
$sql="SELECT Stitl, Ltitl FROM tl2l5 WHERE l1l5= '".$q."'";
// Execute the query
if (!$result = $db->query($sql))
{
die("There was an error running the query [" .$db->error. "]");
}
$data = array();
// Step through the query result and fetch the values
while ($row = $result->fetch_assoc()) {
$Stitl = $row['Stitl'];
$Ltitl = $row['Ltitl'];
$data = array( 'Stitl' => $Stitl, 'Ltitl' => $Ltitl);
}
echo json_encode($data);
?>
UPDATE:
Thank you #TimSPQR for the JSFiddle. This helped me get on the right track. I realized my issue was of my own doing. I used your JSFiddle to alert the value of var mydata and it displayed this:
then I went to my code to alert my variable and got this:
SOLUTION: Once I marked the html comments as php comments I was able to use JSON.parse on the xmlhttp.responseText and populate the two form fields referencing their correct field titles (ex: data.Stitl)

How to pass the Now() Function from one page to another in php

I am displaying the timestamp=now() from one page to another. How can I pass this function? As on the second page I want to retrieve the table on the basis of timestamp=now(). I have done this but it's not working. Kindly help me in this.
Coding
<script type="text/javascript" charset="utf-8">
function showCustomer(n)
{
var xmlhttp;
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("display").innerHTML=xmlhttp.responseText;
}
}
alert(n);
xmlhttp.open("POST","display.php?id="+ n,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php $s= 'now()';
echo $s; ?>
<input type="button" value="h" name="s" onclick="showCustomer(<?php $s ?>)">
<div id='display' >
<?php
echo "111";
?>
</div>
I retrieve the data from the database through this coding:
<?php
include('config.php');
$sa="select * from table1 where timestamp=now()";
$result=mysql_query($sa) or die(mysql_error());
echo "<table border='1'>
<tr>
</tr>";?>
<?php
while($row = mysql_fetch_array($result))
{
$row['c1'];
$row['c2'];
$row['c3'];
$row['c4'];
}
I must call this table on button click on next page by also considering the Now() function. Kindly help me.
Assuming your goal is to preserve some timestamp: use sessions for that
session_start();//in every file (in which you want to access sessions) as first statement before any output
//set time
$_SESSION['now'] = date("Y-m-d H:i:s"); //mysql datetime format
//read time
$save_time = $_SESSION['now'];
I think you missed echo in this statement <input type="button" value="h" name="s" onclick="showCustomer(<?php $s ?>)">.
Please! overwrite this line with <input type="button" value="h" name="s" onclick="showCustomer(<?php echo $s ?>)">
There is no php NOW() function it is a mysql function if you want the same values that mysql's NOW() returns
You have to use php's date("Y-m-d H:i:s"); in this format here is the reference date
<?php $s= date("Y-m-d H:i:s");
echo $s; ?>

form onchange AJAX function for PHP database query

I am quite new to AJAX and would appreciate any help. I have been trying to use AJAX onchange of first drop down menu to call a function for PHP to query database and populate matching results to second drop down menu.
My db connect script works fine, and my PHP query accurately pulls the correct info from the database. (when not using posted variable $cityinput) Problem has been with getting the result from PHP to AJAX, and displayed in the second drop down menu.
<?php
require'connect.php';
$cityinput=$_POST['cityinput'];
$query="SELECT mname FROM masseurs WHERE lounge='$cityinput'";
$result=mysql_query($query);
$num=mysql_numrows($result);
echo "<b><center>Database Output</center></b><br><br>";
$i=0;
while ($i < $num) {
$mname=mysql_result($result,$i,"mname");
$mname="<option value=''>"mname"</option>";
$i++;}
if (!mysql_query($query))
{die('Error: ' . mysql_error());}
mysql_close();
?>
<html>
<head>
<script>
function getmasseurs()
{if (str=="")
{document.getElementById("masseurinput").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("masseurinput").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","outputpopulate3.php?$mname="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="book" action="test.php" method="post">
<p align="center">
<select name="cityinput" id="cityinput" onchange="getmasseurs()">
<option value="0" selected>City</option>
<option value="1">Brisbane</option>
<option value="2">Sydney</option>
<option value="3">Melbourne</option>
<option value="4">Adelaide</option>
<option value="5">Perth</option>
</select>
</p>
<p align="center">
<select name="masseurinput" size="1" id="masseurinput"><div id="cityinput"></div>
</select>
</p>
<p align="center">
<input type="submit">
</form></p>
</body>
</html>
This appears wrong: xmlhttp.open("GET","outputpopulate3.php?$mname="+str,true);
Which file is outputpopulate3.php? The top one? If not post the code of that file
Why are you using a variable in it ? $mname. You can't just use PHP code inside of javascript.
If you want to that you should use:
xmlhttp.open("GET","outputpopulate3.php?<? echo $mname; ?>="+str,true);
Also, the 'str' variable in this line is never set..
You can set it like this in a previous line:
str = document.getElementById('masseurinput').value;
But probably it would be easier to just use a fixed variable name..

Insert Cursor Into PHP Drop Down On Page Load

I wonder whether someone may be able to help me please.
Firstly, apologies, I'm sure this is a really simple fix, but I just can't find the answer.
I'm using the script below to create a drop down menu. Once a value has been selected from it, the relevant records are retrieved.
<html>
<head>
<script type="text/javascript">
function ajaxFunction(name)
{
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{// code for IE6, IE5
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("my_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfinds.php?dateoftrip="+name,true);
xmlhttp.send();
}
function getquerystring() {
var form = document.forms['frm1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
</script>
<style type="text/css">
<!--
.style1 {
font-family: Calibri;
font-size: 14px;
}
-->
</style>
</head>
<body onLoad="document.forms.getfinds.name.focus()" >
<form action="getfinds.php" method="get" name="getfinds">
<input name="field" type="hidden" id="field" value="">
<table width="148" border="0">
<tr>
<td width="152"><p class="style1">Select a date from below</p>
<div align="center">
<?php
include("db.php");
$query="SELECT dateoftrip FROM finds GROUP BY dateoftrip ORDER BY dateoftrip DESC";
echo '<select onchange="ajaxFunction(this.value)"><option name="name" value="allrecords">Show All Records</option>';
$result=mysql_query($query);
while($rows=mysql_fetch_array($result)){
echo "<option name='name' value=".$rows['dateoftrip'].">".$rows['dateoftrip']."</option>";
}
echo "</select>";
?>
</div></td>
</tr>
</table>
</form>
<div id="my_div"></div>
</body>
</html>
I'm trying to find a way of inserting the cursor in the drop down menu on page load.
I've tried using the following:<body onLoad="document.forms.getfinds.dropdown.focus()" > but when I run the script I receive the following error: document.forms.getfinds.dropdown is null or not an object.
As I said, I do apologise for the simple question, but I've been looking for a while for the answer.
I just wondered whether someone could perhaps please let me know where I'm going wrong.
Many thanks and regards
Change your select statement to:
echo '<select id="dropdown" name="dropdown" onchange="ajaxFunction(this.value)">
Change your <body> to:
<body onLoad="document.getElementById('dropdown').focus()" >
Take the name="name" attribute out of your <option> tags.
Add the attribute name="dropdown" to your <select> tag.
Then your onLoad will work fine. No need to change it.
<option> tags do not support the name attribute.
Read More:
http://www.w3schools.com/tags/tag_option.asp

Categories