I have a problem with my code.
case like this:
I have a dropdown, if selected "personal" it appeared the new dropdown that contains the data that is retrieved from a database query, if selected "public", then the dropdown disappear.
HTML code like this:
<select name="use" class="dropdown" id="sender" onChange='changeSend()'>
<option value=1>Public</option>
<option value=0>Personal</option>
</select>
<div id='send2'></div>
Query like this:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$id = array();
$name = array();
while($data = mysql_fetch_array($query)){
//id from result database query
$id[$i] = $data['id'];
//name from result database query
$name[$i] = $data['name'];
$i++;
}
?>
JavaScript code like this:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$('#send2').html("<select class='dropdown'><option value='-id from result database-'>-name from result database query-</option></select>");
} else {
$('#send2').html('');
}
}
I dont know how to send value/result ($id[0],$name[0],$id[1],$name[1], etc..) to javascript code(value and name in select options).
In javascript you have to make an ajax call to your php file:
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("send2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
And in your php file you have to echo your data in JSON format:
echo json_encode(array('id'=>$id,'name'=>$name));
UPDATE
in your case use the following code:
(not tested)
php code:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$options = array();
while($data = mysql_fetch_array($query)){
$options[$data['id']] = $data['name'];
}
echo json_encode($options);
?>
javascript code:
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){
var response = JSON.parse(xmlhttp.responseText);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
document.getElementById("send2").innerHTML= select;
}
}
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
}
else {
$('#send2').html('');
}
}
USING jQuery
javascript code:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$.get("yourFile.php", function(data){
var response = JSON.parse(data);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
$("#send2").html(select);
});
}
else {
$('#send2').html('');
}
}
The best way would probably be with an ajax call, anyway if you are declaring the script in the same page with the php, you can json encode the array with the options so that you will be able to access it into the javascript, like this:
var optionIds = <php echo json_encode($id); ?>
var optionNames = <php echo json_encode($name); ?>
Related
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.
I have a form where radio types are generated inside a PHP while loop. Depending on which radio is selected, java script queries MySQL to get the correct value and return it to a text box. It works except for onload. OnLoad returns the incorrect value, whatever was first in the while loop iteration. Onchange will return the right value.
How can I get onload to return the right value? I am using "checked" in my radio throughout the while iteration so that one circle is always checked. It doesn't matter to me which radio is checked by default. Using checked in the while iteration always makes the last iteration checked which is OK, but it is displaying the value for the first.
here is my code.
<script type="text/javascript">
function getNextcheck(str)
{
if (str=="")
{
document.getElementById("nextcheck").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("nextcheck").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnextcheck.php?id="+str,true);
xmlhttp.send();
}
window.onload = function() {
document.getElementsByName('ID')[0].onchange();
}
</script>
And the file getnextcheck.php it pulls
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM bankaccount WHERE ID = '$_GET[id]'");
$row = mysql_fetch_array($result);
$nextcheck = $row['next_check'];
if (empty($nextcheck)) { $nextcheck = 0; }
echo "<tr><td>Check Number <input type=\"text\" name=\"checkno\" value=\"".$nextcheck."\" /></td></tr>";
And the radio inside the form.
while($row2 = mysql_fetch_array($result2)) {
$id = $row2['ID'];
echo "<tr><td><input type=\"radio\" name=\"ID\" value=\"".$row2['ID']."\" onchange=\"getNextcheck(this.value)\" checked></td><td>".$row2['name']."</td><td>".$row2['acctnum']."</td>";
}
Thank you for your help.
make only first radio check
<?
$i=0;
while($row2 = mysql_fetch_array($result2)) {
$id = $row2['ID'];
$checked = $i?'':'checked';
echo "<tr><td><input type=\"radio\" name=\"ID\" value=\"".$row2['ID']."\" onchange=\"getNextcheck(this.value)\" {$checked}></td><td>".$row2['name']."</td><td>".$row2['acctnum']."</td>";
$i=1;
}
?>
I keep getting an unexpected character error in the console for the line
var a = JSON.parse(xmlhttp.responseText);
and I'm not sure why. Could this be why my textboxes aren't populating with the parsed data?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").innerHTML=a.first;
document.getElementById("textbox2").innerHTML=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
Your loadTextBox.php file should not contain any HTML because the JSON.parse method expects only JSON:
<?php
header("Content-type: application/json");
$db_username = placeholder;
$db_password = placeholder;
$db_host = placeholder;
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
If your DB login info is in a separate file, then there should be no HTML or BODY tags only the PHP tags.
I am using an Ajax call to a PHP file to get data from MySQL database and populate select options in HTML. The problem is that duplicate items in the options and I don't know why. I tried the query in workbench and it brings back what I need.
PHP file:
<?php
$q=$_GET["q"];
// open db connection code
$query = "select * from r2rtool.materialtype where type = 'FE' and tools like '%".$q."%'";
$result = mysql_query($query);
$option = "";
while($row = mysql_fetch_array($result))
{
$mat = $row["Material"];
$option.="<option value=\"$mat\">".$mat."</option>";
echo $option;
}
// close db connection
?>
Ajax function:
function populatematerial(str)
{
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// 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","phpfile.php?q="+str,true);
xmlhttp.send();
}
while($row = mysql_fetch_assoc($result))
{
$option .= "<option value=\"{$row[Material]}\">{$row[Material]}</option>";
}
echo $option;
All you need to do is to move the echo $option; out of the while loop, like so:
while($row = mysql_fetch_array($result))
{
$mat = $row["Material"];
$option.="<option value=\"$mat\">".$mat."</option>";
}
echo $option;
You should output the HTML after you built it, not while you build it.
use mysql_fetch_assoc instead of mysql_fetch_array because array returns value in numbers and name both format, so it will twice data,
where mysql_fetch_assoc returns array as only name element of array ..
for more understanding
try
<?php
$query = mysql_query("some query ");
$row = mysql_fetch_array($row);
$assoc = mysql_fetch_array($row);
print_r ($row);
echo "<br>";
print_r ($assoc);
echo "<br>";
?>