I'll get straight to the point.
I have a a list which shows everyone in the db who has confirmed that they'll be attending a match. I want the list to change depending on what group is chosen from a select box.
Here's what I have so far: html & AJAX
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("attendYes").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("attendingYes").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","attending.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a group:</option>
<option value="CMA">CMA</option>
<option value="CM1">CM1</option>
<option value="CP2">CP2</option>
<option value="CBBC">CBBC</option>
</select>
</form>
<br>
<div id="attendYes"><b>Person info will be listed here...</b></div>
</body>
</html>
And here is the 'attending.php' page that the choice is meant to be sent to:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('-----','-----','-----','-----');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"handsomejack_co_forms");
$sql="SELECT * FROM stats WHERE activity='".$q."' AND attend='0' ORDER BY username ASC";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I have changed the sql from ".$q." to a defined choice - like CMA - and it worked, so I know the issue comes from sending q over.
Any ideas as to what could be the problem?
Cheers.
There are two three things i would suggest:
A.)
Change the id of the target div. as you have attendYes and you are using txtHint.
B.) # js
You can try sending the query in the .send() like below.
xmlhttp.open("GET","attending.php",true);
xmlhttp.send("q=" + encodeURIComponent(str));
C.) and # php:
You should not use intval() although i am not very good at php but as per documentation it is something else. so i suggest you to change this:
$q = intval($_GET['q']);
to this:
$q = $_GET['q'];
There's no element like document.getElementById("txtHint"). Update it with correct one:
document.getElementById("attendYes").innerHTML = xmlhttp.responseText;
Why don´t you use Jquerys $.ajax Method instead.
It´s easier to implement and it´s runing in all Major Browsers.
Related
Through some help from w3school, I managed to create a dropdown for out database, which would fetch the data about a certain product fine. That function is doing great, but I want to add an option for users to decide the number of products they want. To assist with that I want a dropdown that simply multiplies the prices gotten from the first database, if that is possible.
The PHP is the following
<?php
$con = mysqli_connect('localhost','root2','1234','LSnet');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$con->query('SET CHARACTER SET utf8');
if(isset($_GET['q']))
$q = intval($_GET['q']);
mysqli_select_db($con,'LSnet');
$sql = "SELECT * FROM Produkter Where id = '".$q."'";
$result = mysqli_query($con,$sql)
or die("Error: ".mysqli_error($con));
echo "<table>
<tr>
<th>Pris</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['ProduktPris'] . ' DKK' . "</td>";
}
echo "</table>";
mysqli_close($con);
?>
and the HTML is the following
<script>
function showUser(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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../../prisdatabase.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<body>
<form>
<select class="pris" name="NetTyper" onchange="showUser(this.value)">
<option value="">Vælg Nettype</option>
<option value="1">KampNet</option>
<option value="2">TræningNet</option>
</select>
</form>
<br>
<div id="txtHint"><b>Vælg Nettype her</b></div>
--
Added short overview of my table in the database.
--
The expected output from say option one would be 595 DKK, which I would like to have the option to multiply if one would need several
I am creating a php search. I select the 2 menus result from the database. The first menu works fine, but the second one no. Can you please help me?
This is my home.php
<?php
require("ConfigPage.php");
$sql="SELECT LocationName
FROM tblplacelocation
Join tblplace ON tblplace.PlaceID=tblplacelocation.PlaceID
Join tbllocation ON tbllocation.LocationID=tblplacelocation.LocationID
where PlaceType='Hotels'" ;
$result = mysql_query($sql,$con);
echo '<form><P style="color:white;">Region</P>
<select name="PlaceID" onchange="showUser(this.value)">
<option value="">Region:</option>';
while($data = mysql_fetch_array($result))
{
$id= $data['PlaceID'];
$lname = $data['LocationName'];
echo "<option value='". $lname. "'>".$lname."</option>";
}
echo "</select></form>";
echo "<div id='txtHint'></div>";
echo "<div id='divImage'></div>";?>
this is the getuser.php
<?php
$q = intval($_GET['q']);
include("ConfigPage.php");
$sql="SELECT PlaceName
FROM tblplacelocation
Join tblplace ON tblplace.PlaceID=tblplacelocation.PlaceID
Join tbllocation ON tbllocation.LocationID=tblplacelocation.LocationID
WHERE LocationName = '".$q."' AND PlaceType='Hotels'";
$result = mysql_query($sql,$con);
echo '<form><P style="color:white;">Place Name</P>
<select name="adminID" onchange="showImages(this.value)">
<option value="">Select a place:</option>';
while($data = mysql_fetch_array($result))
{
$pid= $data['LocationName'];
$pname = $data['PlaceName'];
echo "<option value='". $pid. "'>".$pname."</option>";
}
echo "</select></form>";
mysql_close($con);
?>
and this is the java 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","getuser.php?q="+str,true);
xmlhttp.send();
}
I don't know what's wrong. The first menu displays the result but the second menu contains nothing.
I would suggest you to use Firebug for debugging.
check if you have any javascript errors (maybe syntax error)
check if your ajax request is being send, if yes, check what's inside the response
check if your dom element is being selected correctly ... in firebug you can execute javascript in the console area. check if your document.getElementById selects the correct element by inserting something yourself
if all of this works, check if your select element has empty options. if this is the case, your variables should be empty
if your select element has no options, something with your sql select may be wrong
If you're just experimenting, it's ok, but otherwise let me say that your code looks pretty ugly. This is not the way you should programm things.
You should think about dividing your code by concerns. Check out the Model-View-Controller Pattern and beginner tutorials for any PHP-Framework.
MVC:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
A Framework which is easy to learn:
http://www.yiiframework.com/
My codes were taken from http://www.w3schools.com/php/php_ajax_database.asp, however i modified to better suit me, but it isn't working as it should be.
Afile.php
<head>
<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", "getDescription.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<?php
$comCtrl = new company_controller();
$companyArray = $comCtrl->retrieveAllCompany();
foreach($companyArray as $com) {
echo "<option value ='".$com."' >".$com."</option>";
}//end foreach
?>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
getDescription.php
<?php
require_once('dbManager.php');
$q = intval($_GET['q']);
$dbMgr = new dbManager();
$conn = $dbMgr->getDBConnection();
$query = "select company_address from company where company_name = '$q'";
$result = mysql_query($query);
echo "<table border='1'>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['company_address'] . "</td>";
echo "</tr>";
}
echo "</table>";
$dbMgr->closeDBConnection($conn);
?>
dbManager.php
<?php
//require('/config/config.php');
require(dirname(__FILE__) . '\..\config\config.php');
class dbManager{
function getDBConnection(){
// start connection
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$connect)
{
die( 'Could not connect: '.mysql_error() );
}
// Select the database
if(!mysql_select_db(DB_NAME))
{
die('The database - '. DB_NAME .' does not exist!');
}
return $connect;
}
function closeDBConnection($connect){
// close the connection
mysql_close($connect);
}
}
?>
I was expecting to have the same result as shown on the website.
Instead, when i first run the files, i would see a dropdownlist(ddl) with all the company values, and beneath that ddl is the text "person info will be listed here". When i click on the ddl, i was hoping for the company's address to be populated at the div place of the text, but instead another ddl appeared beneath the first ddl. So now i have a ddl on the first row, another ddl on the second row, and the same text "person info will be listed here". WHat am i missing?
I would recommend you to use mysqli_query() or PDO::query()
This is the required syntax for mysql_query()
mysql_query(query,$conn);
use:
$q = trim($_GET['q']);
I'm sure there's an easy answer to this but I've looked everywhere and can't seem to find an answer. I have a dropdown box at the start of a form for office names being populated from an sql table. Depending on which office the user selects, I want the other fields to be filled out with the corresponding information for that record. I used the w3schools php ajax database page as a my guide but it only shows how to update one id in the page and I need to update the input field for address, city, state, zip, and contact.
Here's the relevant code which isn't working. The Code for to trigger the script for the dropdown:
<select name="users" onchange="showOffice(this.value)" class="field select" tabindex="1" >
The Script on that page:
<script>
function showOffice(str)
{
if (str=="")
{
document.getElementById("practice_name").innerHTML="";
document.getElementById("contact").innerHTML="";
document.getElementById("address").innerHTML="";
document.getElementById("city").innerHTML="";
document.getElementById("state").innerHTML="";
document.getElementById("zip").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("practice_name").innerHTML=xmlhttp.practice_name;
document.getElementById("contact").innerHTML=xmlhttp.contact;
document.getElementById("address").innerHTML=xmlhttp.address;
document.getElementById("city").innerHTML=xmlhttp.city;
document.getElementById("state").innerHTML=xmlhttp.state;
document.getElementById("zip").innerHTML=xmlhttp.zip;
}
}
xmlhttp.open("GET","getoffice.php?q="+str,true);
xmlhttp.send();
}
</script>
And then my getoffice.php code:
<?php
$q=$_GET["q"];
$host="********"; // Host name
$db_username="******"; // Mysql username
$db_password="******"; // Mysql password
// Connect to server and select database.
$con = mysqli_connect("$host", "$db_username", "$db_password");
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"*****");
$sql="SELECT * FROM initial_practice WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
$row=mysql_fetch_array($result);
?>
var practice_name = <? echo $row['practice_name']; ?>
var contact = <? echo $row['contact']; ?>
var address = <? echo $row['address']; ?>
var city = <? echo $row['city']; ?>
var state = <? echo $row['state']; ?>
var zip = <? echo $row['zip']; ?>
<?
mysqli_close($con);
?>
Any help would be greatly appreciated.
Your problem is you aren't using the response text back correctly. This can be fixed in a couple steps. The AJAX request pulls back everything that is printed out from getoffice.php.
First
We're gonna want to change these lines on the on-page script from this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("practice_name").innerHTML=xmlhttp.practice_name;
document.getElementById("contact").innerHTML=xmlhttp.contact;
document.getElementById("address").innerHTML=xmlhttp.address;
document.getElementById("city").innerHTML=xmlhttp.city;
document.getElementById("state").innerHTML=xmlhttp.state;
document.getElementById("zip").innerHTML=xmlhttp.zip;
}
}
To something a bit easier (I tend to separate readyState and status if statements, my delusional belief that it can randomly fail when combined):
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if(xmlhttp.status==200)
{
eval(xmlhttp.responseText);
}
}
};
Now we're simply evaluating all we get back from the request. Also, note that I added a semi-colon to the end of the onreadystatechange function.
Second
Change the following lines in getoffice.php from:
var practice_name = <? echo $row['practice_name']; ?>
var contact = <? echo $row['contact']; ?>
var address = <? echo $row['address']; ?>
var city = <? echo $row['city']; ?>
var state = <? echo $row['state']; ?>
var zip = <? echo $row['zip']; ?>
To:
document.initialpractice.practice_name.value = <?php echo $row['practice_name']; ?>
document.initialpractice.contact.value = <?php echo $row['contact']; ?>;
document.initialpractice.address.value = <?php echo $row['address']; ?>;
document.initialpractice.city.value = <?php echo $row['city']; ?>;
document.initialpractice.state.value = <?php echo $row['state']; ?>;
document.initialpractice.zip.value = <?php echo $row['zip']; ?>;
Now, when we get the response back from the server, the javascript will evaluate the above response appropriately and fill in the fields. At least it should, providing the query doesn't fail.
Also, you can change mysqli_fetch_array() to mysqli_fetch_assoc(), since you only need the associative array.
Note: We could have solved the problem by just adding eval(xmlhttp.responseText); below the readyState/status checks and removing xmlhttp. in front of all the innerHTML variables.
Finally figured it out. For any of you having the same trouble here's a fix.
php code:
$row=mysqli_fetch_assoc($result);
$name = $row['practice_name'];
$contact = $row['contact_name'];
$address = $row['address'];
$city = $row['city'];
$state = $row['state'];
$zip = $row['zip'];
echo $name."#".$contact."#".$address."#".$city."#".$state."#".$zip;
On-page Script:
function showOffice(str)
{
if (str=="")
{
document.getElementById("practice_name").innerHTML="";
document.getElementById("contact").innerHTML="";
document.getElementById("address").innerHTML="";
document.getElementById("city").innerHTML="";
document.getElementById("state").innerHTML="";
document.getElementById("zip").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)
{
if(xmlhttp.status==200)
{
var data = xmlhttp.responseText.split("#");
var name = decodeURIComponent(data[0]);
var contact = decodeURIComponent(data[1]);
var address = decodeURIComponent(data[2]);
var city = decodeURIComponent(data[3]);
var state = decodeURIComponent(data[4]);
var zip = decodeURIComponent(data[5]);
document.initialpractice.practice_name.value = name;
document.initialpractice.contact.value = contact;
document.initialpractice.address.value = address;
document.initialpractice.city.value = city;
document.initialpractice.state.value = state;
document.initialpractice.zip.value = zip;
}
}
};
xmlhttp.open("GET","getoffice.php?q="+str,true);
xmlhttp.send();
}
</script>
i have this code below of javascript:
<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","includes/get_user.php?q="+str,true);
xmlhttp.send();
}
</script>
and the php sql script is given below:
<?php
$testQrys = "SELECT * FROM test where status = 1";
$testdbResults = mysql_query($testQrys);
?>
<select size='5' width='925' style='width: 925px' name='users' onchange='showUser(this.value)' multiple>
<?php while($test = mysql_fetch_array($testdbResults )) { ?>
<option class='h4' value='<?php print($test[9]); ?>'>
<?php print($test[5]);echo" ( ";print($test[9]);echo" )"; ?>
</option>
<?php } ?>
</select>
<div id="txtHint"></div>
and the get_user.php code is:
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','airways');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM test WHERE m_email = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<input type='text' name='staff_no[]' value='".$row['m_staff_no']."'>";
}
mysqli_close($con);
?>
now what i want is when i select one user in the select option it shows the staff no of that user but when i select multiple users it does not show the staff no of other users i select.
please help me with the change in code so i can get the staff no of users like (22344, 44333, 33344, 55443, 11125, 25263) in the text box
waiting for the kind and prompt responses.
Thanks in advance
The error is coming from showUser(this.value). This returns only the first selected element's value. You need to cycle through all options and concatenate them together to make a string that you will be able to send as a parameter.
Change your javascript code to something along those lines. Note that you will need to change your PHP code in order to separate the emails, sanitize them and create a working WHERE m_email IN () query.
You will need to add id="users" to your HTML code first.
var usersList = document.getElementById('users');
var emailString = '';
for (user_counter = 0; user_counter < usersList.options.length; user_counter++) {
if (usersList.options[user_counter].selected) {
emailString += usersList.options[user_counter].value;
}
}
Then send emailString as the parameter to the PHP script. Test it again with log.txt in case you get an error.