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'] . "    " .$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)
Related
i have few field of data such as product , amount and barcode.The system just show 1 row of data insert form that contain the 3 field.when i completed insert the first row, then second row of textbox will auto generate, i can do it by microsoft access, can i do so for php ?
<?php $i=0; ?>
<form method="post" action="">
<input type="text" name="<?php echo $i; ?>" />
</form>
<?php
if(isset($_POST[$i])){
$i++;
?>
<form method="post" action="">
<input type="text" name="<?php echo $i; ?>" />
</form>
<?php }?>
it work for the first and second textbox, but how can i continue to create more textbox accordingly?
say your file name is 1.php and you will submit the form to 1a.php
1.php
<html>
<head>
<script>
a=0;
function generate()
{
if(document.getElementById(a).value!="")
{
var new_input=document.getElementById(a).cloneNode(true);
//document.getElementById(a).type="hidden";//uncomment this statement to hide the previous input box.
new_input.id=++a;
new_input.title='product_no:'+(a+1);
new_input.value="";
document.getElementById('input_section').appendChild(new_input);
}
else
{
alert("Give some value first.");
document.getElementById(a).focus();
}
}
</script>
</head>
<body>
<form method="post" action="1a.php">
<span id="input_section">
<input type="text" onFocus="this.name='prod[]'; this.id=a; this.title='product_no:'+(a+1);"/>
</span>
<input type="button" value="Insert&Generate" onClick="try{generate()} catch(e){alert(e)}">
<input type="submit" value="INSERT ALL">
</form>
</body>
</html>
1a.php
<html>
<?php
if(count($_POST)==0)
{
?>
<script>
alert('No record to insert.')
location.href="1.php";
</script>
<?php
}
$con=mysqli_connect(...);// connect to database
foreach($_POST['prod'] as $prod_info)
{
$prod_info_arr=explode(",",$prod_info);
$sql="insert into tab1(product, amount, barcode) values('".$prod_info_arr[0]."', ".$prod_info_arr[1].", '".$prod_info_arr[2]."')";
mysqli_query($sql);
}
?>
</html>
This is what you wanted. Check it.
edit: just added comment on the statement document.getElementById(a).type="hidden"; to make the filled textbox not disappear.
If you want to have dynamic input fields, so that second and third input boxes are displayed only when the first input box is filled, use an AJAX code.
This must be what you want. Since you have not mentioned clearly under what condition the second input field should be displayed, i assumed if 'try' is inserted in the first input field, second input field is shown.
<?php
echo "<script>
function showUser(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('txtHint').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','get.php?q='+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form method='post' action=''>
First input<input type='text' name='name' onclick='showUser(this.value)' /></br>
<div id='txtHint'></div>
</form>
</body>
</html>";
?>
And in get.php file the following code;
<?php
$q = $_GET['q'];
if($q == 'try'){
echo "Second input<input type='text' />";
}
?>
Hope this will help. And change the get.php code according to the condition you want the second input field to be shown.
This code works. After entering try in the first input field again click inside the text field. And then second input field will be shown.
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; ?>
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..
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"]
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:
function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// Използваните браузъри
xmlhttp=new XMLHttpRequest();
}
else
{// Кой ли ползва тези версии..
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","newmsg.php?q="+str,true);
xmlhttp.send();
}
Then the text field :
<div id="sender">
Your message: <input type="text" name="msg" size="30" id="msg" />
<button onclick="doWork(this.msg);">Send</button>
</div>
And finally the php file:
$q=$_GET["q"];
(str)$q;
$db_connect = mysql_connect('localhost', 'root', 'diamond');
if(!$db_connect)
{
die('Не може да се осъществи връзка с базата данни' . mysql_error());
}
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);
And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron
I believe the issue is in your reference to the input text field. Try this instead:
<div id="sender">
Your message: <input type="text" name="msg" size="30" id="msg" />
<button onclick="doWork(document.getElementById('msg').value);">Send</button>
</div>
When you use the following, 'this' refers to the button element, so don't do the following.
<button onclick="doWork(this.msg);">Send</button>
doWork(document.getElementById('msg'));
this there is a button element. It has no msg property i.e. undefined, within string conversion.
Replace
<button onclick="doWork(this.msg);">Send</button>
with
<button onclick="doWork(msg);">Send</button>
this.msg is the same as button.msg, which does not make sense.
Typecast (str) doesn't exist, it's (string). And you have to do this by assignment:
$q = (string) $q;
Actually it's pretty pointless since URL's are strings. So leave that line out.
Also, as the other repliers mentioned, that's not the right way to get the value. If you do it the following way, the button will be accessible with the return key too. With onclick the user is forced to click on the button. Add return false so that the form doesn't get submitted. this points to <form>.
<form onsubmit="alert(this.msg.value); return false">
<p>
<input type="text" name="msg" />
<button type="submit">Send</button>
</p>
</form>