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;
}
?>
Related
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); ?>
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/
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 php script which has series of calculations and FORM RELOADS based on user Selection/Inputs, I need to run these only IF a record ADDITION is done to the table and not on FORM RELOADS, how to run a loop with this condition.
my PARTIAL php script bill-detail.php:
HOPE THIS WOULD SUFFICE:
<html>
<head>
<title>Cash Bill Detail</title>
<script language="javascript">
function reload(form)
{
document.location.href = 'bill-detail.php'
}
function showecr(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","billecr.php?q1=" + str,false);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$con = mysql_connect("localhost","svga","a!##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("svga", $con);
$user = $_SESSION['user'];
//<!--------------VALIDATIONS ------------------->
echo "<form name='form1'>";
echo "ECR: <input type='text' size='10' maxlength='10' name='ecrn' onchange=\"showecr(this.value);\"><br>";
echo "Product Type";
echo "<select name='product' onchange=\"reload(this.form);\">>";
echo "<option value='Gas'>Gas</option>";
echo "<option value='Others'>Others</option>";
echo "</select>";
echo "</form>";
//---As per user inputs copying value to variables---------------------
$hdr=mysql_query("SELECT * FROM BILLHDR_draft WHERE usr='$user'");
$hdr2=mysql_fetch_assoc($hdr);
$numrows=mysql_num_rows($hdr);
if ($numrows>0)
{
$cust_code=$hdr2['Ac_code'];
$product=$hdr2['prod_desc'];
//--Searching BILL DETAILS TABLE as per the user inputs from BILL HEADER Table------
$recs=mysql_query("SELECT * FROM BILLDTLS WHERE Ac_code='$cust_code' AND Prod_desc='$product'");
while ($rec2=mysql_fetch_assoc($recs))
{
mysql_query("INSERT INTO DEMURAGE (DC_No, DC_date, Ac_code, Product_Desc) VALUES ('$rec2[dc]', '$rec2[dcdate]', '$rec2[accode]', '$rec2[product]'");
}
}
mysql_close($con);
?>
You can add a boolean variable before the loop that you can use to track on whether a record has been added already. The following code is largely concept being that you didn't provide much of an example of code yourself, but hopefully you get the idea.
// Set to false initially
$recordAdded = FALSE;
if( $num_rows > 0 && $recordAdded == FALSE )
{
// Code to execute
// Set value to to TRUE after initial successful execution
$recordAdded = TRUE;
}
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>";
?>