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..
Related
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.
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 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"]
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