I have an an ajax drop down box that if selected adds another field to a form, this works but this new field doesn't get submitted with the form. Any suggestions?
findTest.php called via ajax
<?php
$work = ($_GET['work']);
if ($work == "Work1") {
?>
<tr>
<td>New work1<input name="newWork1" size="20" type="text"/></td>
</tr> <?
} elseif ($work == "Work2") {
?>
<tr>
<td>New work<input name="newWork" size="20" type="text"/></td>
</tr><?
} elseif ($work == "Work3") {
?>
<tr>
<td>No work today</td>
</tr><?
}?>
Test.php
<?php
$page = '';
$answer = null; //clean start.
$Comments = $_POST['Comments'];
$new = $_POST['new'];
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message <?= $_POST['Comments'] ?>
and <?= $_POST['new'] ?> or this should be
work2 <?= $_POST['newWork'] ?></p>
<? } ?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
function getWorkDone(workId) {
var strURL = "findTest.php?work=" + workId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML = req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right">Work Done:</td>
<td><select name="WorkDone" tabindex="14"
onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><p id="workdiv">New Work<input name="newWork" size="20"
type="text"/></td>
</tr>
<tr>
<td width="200" align="right">Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40"
rows="4"><?= $_POST[Comments] ?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit"
class="button" value="Submit">
</td>
</tr>
</tr>
</table></form>
UPDATE: new code.
findTest.php called via ajax
<?php
if (isset($_GET['work'])) {
$work= $_GET['work'];
if ($work == "Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
}?>
And Test.php
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getWorkDone(workId) {
var strURL="findTest.php?work="+workId+"&new1="+"&$new";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML=req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right" >Work Done:</td>
<td><select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="">Select</option>
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr >
<td ></td>
<td ><p id="workdiv">New Work<input name="newWork" size="20" type="text" /></td>
</tr>
<tr>
<td width="200" align="right" >Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40" rows="4" ><?=$_POST[Comments]?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit" class="button" value="Submit">
</td>
</tr>
</tr>
</table>
</form>
UPDATE edit double up and correct $newWork to $newWork1
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";}
?>
This now shows n/a but not the value of newWork1
You have very modified the original question, I can only respond to what was previously.
The important part is also findTest.php
from this script you replace your
document.getElementById('workdiv').innerHTML=req.responseText;
So how does findTest.php know about $_POST['newwork1']
<td>New work1<input name="newWork1" ... value="<?=$_POST['newwork1']?>" /></td>..
This must come via a GET / POST, but in your GET there ist only
strURL="findTest.php?work="+workId;
Only 1 GET variable named $_GET['work'].
and you use this variable (without test)
$work=$_GET['work'];
And then you mixed the request from $_GET to $_POST['newwork1']
so why not use your select value to get it all together.
Test.php
...
<select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Noworktoday">No work today</option>
<option value="Other">Other</option>
</select>
...
findTest.php
if (isset($_GET['work'])) {
//for example : $work == "Work1"
$work=$_GET['work'];
if ($work=="Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
//<tr><td>New Work1<input name="newWork1" type="text" size="20" value="newWork1" /></td></tr>
Update:
You can not see your values because you did'nt echo them
and you have to test all $_POST
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a';
}
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a';
}
....
and so on for all possible values
echo your variables
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message = <? echo $Comments; ?>
and = <? echo $newWork1; ?> or this should be
work2 = <? echo $newWork; ?></p>
<? } ?>
Update:
I can not see the actual code, you need a if (isset ... for all possible variables . In my example I have described only two possibilities. You need also e.g.
if (isset($_POST['newWork2'])) { ...
if (isset($_POST['newOther'])) { ...
and so on !! And make only asimple output.
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
and put it logical together
This is illogical Work2 assigned to newWork !!!
Related
I have a php file and am sending variables from php to ajax file and everything is running great , however when i run javascript in the ajax file
nothing appear like am alerting a msg , nothing is appear , is there any conflict between ajax and javascript ?
This is in the ajax file
<script type="text/javascript" src="js/library.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<?php
session_start();
include("mysqlconnection.php");
if (!isset($_SESSION['username'])) {
echo "<h2 align='center'>Warning: You are not currently signed in </h2>";
die ("<script type = 'text/javascript' language = 'JavaScript'>window.setTimeout(\"location.href='index.php'\", 1000); </script>");
}
$uid=$_SESSION['uid'];
$code = $_GET['user'];
$qty = $_GET['qty'];
$custid = $_GET['custid'];
$warehouseid = $_GET['warehouseid'];
if ($code==''){
$sql1 = "SELECT * FROM itemscopy WHERE uid='$uid'";
$result1=mysql_query($sql1,$con);
if(!$result1)die("Couldn't execute".mysql_error());
?>
<table border="0" width="100%" align="center">
<thead>
<tr>
<th>Code</th>
<th>Code 2</th>
<th>Description</th>
<th>Discount%</th>
<th>Discount Amount</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
<th>After Discount</th>
<th>Warehouse</th>
</tr>
</thead>
<?php
for($counter=0;$row1=mysql_fetch_assoc($result1);$counter++){
$wid=$row1['warehouseid'];
$selwarehouse="SELECT * FROM warehouse
WHERE Id='$wid'";
$runwarehouse=mysql_query($selwarehouse,$con);
if(!$runwarehouse)die("Error");
$rowz=mysql_fetch_assoc($runwarehouse);
if($counter%2==0){
echo ("<tr class='light'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}else{
echo ("<tr class='dark'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}
}
echo "</table>";
?>
</div>
</body>
</html>
<?php
die('');
}
?>
<head>
</head>
<?php
if($warehouseid==''){
die("<h2 align='center'>Please Choose warehouse</h2>");
}
$x=(explode('-',$code));
$code1=$x[0];
$codeid=$x[1];
$code2=$x[2];
$selqty="SELECT * FROM inventory
WHERE itemid='$codeid' AND
warehouseid='$warehouseid'";
$runselqty=mysql_query($selqty,$con);
$rowinventory=mysql_fetch_assoc($runselqty);
if(!$runselqty)die("error");
if(mysql_num_rows($runselqty)==0){
die("<h1 align='center'>This Item Is Not In Your Inventory</h1>");
}
else{
if($rowinventory['qty']<0){
?>
<script type='text/javascript'>
function check(){
var r = confirm("Press a button!");
if(r) {
var urlLink = 'http://www.example.com/warehouse/record.php?codeid=<?php echo $codeid;?>&qty=<?php echo $qty;?>&custid=<?php echo $custid;?>&warehouseid=<?php echo $warehouseid;?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
alert('123');
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
alert('123');
</script>
<?php
// die("<h1 align='center'>The quantity of the item is negative Do you want to continue ?</h1>");
}
else if($rowinventory['qty']-$qty>=0){
// die("<h1 align='center'>The quantity is enough in the inventory You can continue</h1>");
}
else if($rowinventory['qty']-$qty<0){
// die("<h1 align='center'>The available quantity in the inventory is less than the quantity you select</h1>");
}
}
$sqlx = "SELECT * FROM items
WHERE Id='$codeid'";
$resultx=mysql_query($sqlx,$con);
if(!$resultx)die("Couldn't execute".mysql_error());
$row = mysql_fetch_assoc($resultx);
$desc=$row['description'];
$price=$row['price'];
if((!isset($qty))||($qty=='')){
$insert="INSERT INTO itemscopy(code,code2,description,quantity,price,amount,custid,uid,discountper,discountamount,totaldiscount,warehouseid,codeid)Values('$code1','$code2','$desc','1','$price','$price','$custid','$uid','0','0','$price','$warehouseid','$codeid')";
$r=mysql_query($insert,$con);
if(!$r)die("error".mysql_error());
}
else{
$insert="INSERT INTO itemscopy(code,code2,description,quantity,price,amount,custid,uid,discountper,discountamount,totaldiscount,warehouseid,codeid)Values('$code1','$code2','$desc','$qty','$price','$price'*'$qty','$custid','$uid','0','0','$price'*'$qty','$warehouseid','$codeid')";
$r=mysql_query($insert,$con);
if(!$r)die("error".mysql_error());
}
$sql1 = "SELECT * FROM itemscopy WHERE uid='$uid'";
$result1=mysql_query($sql1,$con);
if(!$result1)die("Couldn't execute".mysql_error());
?>
<table border="0" width="100%" align="center">
<thead>
<tr>
<th>Code</th>
<th>Code 2</th>
<th>Description</th>
<th>Discount%</th>
<th>Discount Amount</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
<th>After Discount</th>
<th>Warehouse</th>
</tr>
</thead>
<?php
for($counter=0;$row1=mysql_fetch_assoc($result1);$counter++){
$wid=$row1['warehouseid'];
$selwarehouse="SELECT * FROM warehouse
WHERE Id='$wid'";
$runwarehouse=mysql_query($selwarehouse,$con);
if(!$runwarehouse)die("Error");
$rowz=mysql_fetch_assoc($runwarehouse);
if($counter%2==0){
echo ("<tr class='light'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}else{
echo ("<tr class='dark'>");
echo ("<th>".$row1['code']."</th>");
echo ("<th>".$row1['code2']."</th>");
echo ("<th>".$row1['description']."</th>");
echo ("<th>".$row1['discountper']."</th>");
echo ("<th>".$row1['discountamount']."</th>");
echo ("<th>".$row1['quantity']."</th>");
echo ("<th>".$row1['price']."</th>");
echo ("<th>".$row1['amount']."</th>");
echo ("<th>".$row1['totaldiscount']."</th>");
echo ("<th>".$rowz['name']."</th>");
echo ("<th><a href='edit.php?id=".$row1['Id']."'>edit</a></th>");
echo ("</tr>");
}
}
echo "</table>";
?>
</div>
</body>
</html>
Here is my php code that runs the ajax file where should i put the javascript
<?php
include("header.php");
include("mysqlconnection.php");
if(!isset($_POST['custname'])){
die("<h2 align='center'>YOU ARE NOT ALLOWED TO VISIT THIS PAGE</h2>");
}
?>
<html>
<head>
<script type="text/javascript" src="jquery1.9.1.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquerysearchabledropdown.min.js"></script>
<script>
function showUser(){
var str=document.form.users.value;
var qty=document.form.qty.value;
var custid=document.form.custid.value;
var warehouseid=document.form.warehouse.value;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
alert('123');
}
}
xmlhttp.open("GET","getcode.php?user="+str+"&qty="+qty+"&custid="+custid+"&warehouseid="+warehouseid,true);
xmlhttp.send();
document.form.users.value='';
document.form.users.focus();
}
$(document).ready(function(){
$("#users").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
document.getElementById('goo').click();
}
});
});
$(document).ready(function() {
$("#users2").searchable();
});
function appendSelectOption(str) {
$("#users2").append("<option value=\"" + str + "\">" + str + "</option>");
}
</script>
</head>
<body onload="document.form.users.focus()">
<div id="">
</br></br>
<form name="form" method="post">
<table border="0" align="center">
<tr>
<td align="center"><select id="users2" name="users" width="350" style="width: 230px">
<option value="" selected="selected">Please Select</option>
<?php
$sql1="select code,description,code2,Id from items";
$result1=mysql_query($sql1,$con);
for($counter=0;$row=mysql_fetch_row($result1);$counter++)
print ("<option value = '$row[0]-$row[3]-$row[2]'>$row[0] - $row[1] - $row[2]</option>");
?>
</select>
</td>
<td align="center"><select id="warehouse" name="warehouse" >
<option value="" selected="selected">Please Select</option>
<?php
$sql1="select Id,name from warehouse order by Id Desc";
$result1=mysql_query($sql1,$con);
for($counter=0;$row=mysql_fetch_row($result1);$counter++)
print ("<option value = '$row[0]'>$row[1]</option>");
?>
</select>
</td>
<td>
<input type="text" name="qty" id="qty" size="2"/>
</td>
<td>
<input type="button" name="goo" id="goo" value="GO" onclick="showUser()"/>
</td>
<td>
<input type="hidden" name="custid" id="custid" value="<?php echo $_POST['custname'];?>" size="3"/>
</td>
<td>
<input type="hidden" name="warehouseid" id="warehouseid" value="<?php echo $_POST['warehouse'];?>" size="3"/>
</td>
<td>
<input type="hidden" name="date" id="date" value="<?php echo $_POST['date'];?>"/>
</td>
</tr>
</table>
</form>
</div>
<div id="txtHint"></div>
<script>
$(document).ready(function(){
$('#users').attr("placeholder", "Barcode Search...");
$('#users').focusin(function(){
$(this).attr("placeholder", "");
});
$('#users').focusout(function(){
$(this).attr("placeholder", "Barcode Search...");
});
});
</script>
</body>
</html>
To run a javascript function after your ajax call you should do something like below
$.ajax({
url: "getcode.php?user="+str+"&qty="+qty+"&custid="+custid+"&warehouseid="+warehouseid,
type:"get",
success: function(responseText) {
$("#txtHint").html(responseText);
$("#txtHint").find("script").each(function(i) {
eval($(this).text());
});
}
});
put your javascript function in your success function..
So the function will fire when there is a success ajax call
EDIT
as per your coding you need to do following change in your function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
alert('something') // put some javascript here
}
Let me know if any other help needed
Basically I have a page that displays a seating plan using check boxes. These check boxes can be ticked to represent the seat being booked. I also have a text input where names are entered for the bookings, these forms are then posted to the next page to work out what check boxes are selected and save them in the database. This is some of the code:
title>School Hall</title>
<script>
function confirmReservation() {
var selectedList = getSelectedList('Confirm Reservation');
if (selectedList) {
if (confirm('Do you want to CONFIRM this Reservation : ' + selectedList + '?')) {
document.forms[0].statusA.value=0;
document.forms[0].statusB.value=1;
document.forms[0].previousPage.value='schoolHall';
document.forms[0].action='bookingQueries.php';
document.forms[0].submit();
} else {
clearSelection();
}
}
}
function cancelReservation() {
var selectedList = getSelectedList('cancel Reservation');
if (selectedList) {
if (confirm('Do you want to CANCEL this Reservation : ' + selectedList + '?')) {
document.forms[0].statusA.value=1;
document.forms[0].statusB.value=0;
document.forms[0].previousPage.value='schoolHall';
document.forms[0].action='bookingQueries.php';
document.forms[0].submit();
} else {
clearSelection();
}
}
}
function getSelectedList(actionSelected) {
// get selected list
var obj = document.forms[0].elements;
var selectedList = '';
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked && obj[i].name == 'seats[]') {
selectedList += obj[i].value + ', ';
}
}
// no selection error
if (selectedList == '') {
alert('Please select a seat ');
return false;
} else {
return selectedList;
}
}
function validateForm()
{
var x=document.forms["0"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body topmargin="0" leftmargin="0" rightmargin="0" >
<table>
<tr><td width="100%" align="left" id='table-2'>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="previousPage" value=""/>
<input type="hidden" name="statusA" value=""/>
<input type="hidden" name="statusB" value=""/>
</tr>
<table>
<tr><td width="100%" align=left" id='table-2'>
<INPUT Type="BUTTON" VALUE="Home Page" ONCLICK="window.location.href='/final/homePage.php'" align='lef'>
<INPUT Type="BUTTON" VALUE="Bookings" ONCLICK="window.location.href='/final/schoolHallBookings.php'">
<?php
// Connection
$con = mysql_connect("localhost","root","");
if(!con)
{
die('Could not connect:' . mysql_error());
}
mysql_select_db("systemDatabase",$con); // Connection to DB
echo '<br>';
echo '<font face="Trebuchet MS" color="Black" size="9" >School Hall </font>';
$query = "SELECT * from schoolHall order by rowId, columnId"; // Create Select Query
$result = mysql_query($query); // Retrieve all data from query and hold in $result
$prevRowId = null;
$seatColor = null;
$tableRow = false;
echo "<table align='center' id='table-2'"; // Create table
while (list($rowId, $columnId, $status, $updatedby, $firstName, $lastName) = mysql_fetch_row($result)) // Itterates through fetched data
{
if ($prevRowId != $rowId)
{
if ($rowId != 'A')
{
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table class='center' border='1' cellpadding='15' cellspacing='8' align='center' id='table-2' ><tr>";
}
else
{
$tableRow = false;
}
if ($status == 0)
{
$seatColor = "lightgreen"; // Available
}
else
{
$seatColor = "red"; // Booked
}
echo "\n<td bgcolor='$seatColor' align='center'>";
echo "$rowId$columnId";
if ($status == 0 || ($status == 1)) {
echo "<input type='checkbox' name='seats[]' value='$rowId$columnId' align='center'></checkbox>"; // Create Checkboxes giving value RowId, ColumnId
}
}
echo "</tr></table></td>";
echo "</tr>";
echo "</table>";
// Con close
mysql_close();
?>
<table width='100%' border='0'>
<tr><td align='right'>
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
</td>
<td><td align='left'>
</td>
<td><td align ='right'>
<input type='button' value='Confirm Reservation' onclick='confirmReservation()'/>
</td></tr>
<tr>
<td><td align='left'>
</td>
<td><td align='left'>
</td>
<td align='right'>
<input type='button' value=' Cancel Reservation' onclick='cancelReservation()'>
</td>
</table>
</td></tr>
<tr><td width="100%" align="center">
</td></tr>
<tr><td> </td></tr>
<tr><td width="100%" align="center">
<table border="1" cellspacing="6" cellpadding="4" align="center">
<tr>
<td bgcolor='lightgreen'>Available</td>
<td bgcolor='red'>Unavailable</td>
</tr>
</table>
</td></tr>
<tr><td> </td></tr>
<tr><td width="100%" align="center">
</td></tr>
</table>
</body>
Is there any way i can incorporate validation with my current code? I need the names text checked to make sure there is actually a name entered. This needs to happen before the next page is accessed. Any ideas?
Try first add ids to your text input:
<table width='100%' border='0'>
<tr>
<td align='right'>
First Name: <input type="text" id="fname" name="fname"/>
Last Name: <input type="text" id="lname" name="lname"/>
</td>
<td>
<td align='left'>
function getSelectedList(actionSelected) {
// get selected list
var obj = document.forms[0].elements;
var selectedList = '';
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked && obj[i].name == 'seats[]') {
selectedList += obj[i].value + ', ';
}
}
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
// no selection error
if (selectedList == '') {
alert('Please select a seat ');
return false;
} else if (actionSelected.beginsWith('Confirm') && (fname .value.replace(/^\s+|\s+$/g, '').length == 0 || /[0-9]/.test(fname))) {
alert('Please Enter valid first name.');
return false;
} else if (actionSelected.beginsWith('Confirm') && (lname.value.replace(/^\s+|\s+$/g, '').length == 0 || /[0-9]/.test(lname))) {
alert('Please Enter valid last name.');
return false;
} else {
return selectedList;
}
}
Working example
http://jsfiddle.net/
The below example demonstrates how you can pass a value to the function checkInput and it will determine whether or not it is a valid input - the function uses jQuery but you can do it whthout jQuery too.
Demo HTML:
<form>
<input id="first-name" value="some value" />
<input id="last-name" value="" />
</form>
JS Function (goes with HTML demo):
function checkInput(fieldID){
var isValid = true;
if($("#" + fieldID).val() == ''){
isValid = false;
}
return isValid;
}
$(document).ready(function(){
if(!checkInput("first-name")){
alert("error found with first name");
}
if(!checkInput("last-name")){
alert("error found with last name");
}
});
I have this html form:
<form method="post">
<input type="radio" name="news" id="new" value="nuova" onchange="newstype(this.id);">Nuova News
<input type="radio" name="news" id="mod" value="modifica" onchange="newstype(this.id);">Modifica News
<select name="news" id="modifica" style="display:none" onchange="shownews(this.value)">
<?php
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or die("Impossibile connettersi");
$querylistanews = "SELECT * FROM NEWS ORDER BY id DESC";
$listanews = $connection->query($querylistanews);
print '<option>Seleziona una news...</option>';
while ($newsdamodificare = $listanews->fetch_object()) {
print '<option value="'.$newsdamodificare->id.'">'.$newsdamodificare->data." - ".$newsdamodificare->title.'</option>';
}
$listanews->close();
$connection->close;
?>
</select>
</form>
this javascript:
function newstype(param) {
if(param == 'new') {
document.getElementById('crea').style.display = 'inline';
document.getElementById('modifica').style.display = 'none';
document.getElementById('newsdamodificare').style.display = 'none';
} else {
if(param == 'mod') {
document.getElementById('crea').style.display = 'none';
document.getElementById('modifica').style.display = 'inline';
document.getElementById('newsdamodificare').style.display = 'inline';
}
}
}
function shownews(str) {
if (str=="") {
document.getElementById("newsdamodificare").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // codice per IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // codice per IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","modifica.php?news="+str,true);
xmlhttp.send();
}
and this php:
<head>
<script type="text/javascript" src="../editor/ckeditor.js"></script>
<script type="text/javascript" src="/js/charscounter.js"></script>
</head>
<?php
$news=$_GET["news"];
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or
die('Impossibile connettersi al database: ' . mysql_error());
$newsdaldatabase="SELECT * FROM NEWS WHERE id = '".$news."'";
$result = $connection->query($newsdaldatabase);
$count = mysqli_num_rows($result);
if($count==1){
while($dati = mysqli_fetch_array($result)) {
$id = $dati['id'];
$data = $dati['data'];
$title = $dati['title'];
$body = $dati['body'];
}
} else {
die('Errore del sistema. PiĆ¹ di una news selezionate: ' . mysql_error());
}
mysqli_close($connection);
?>
<div class="normal" id="modifica">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">Modifica news</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="modificanews" method="post" action="italiano.php?modifica=yes">
<input name="idmodificanews" type="text" style="display:none" value="<?php echo $id ?>">
<input name="datanewsmodificata" type="text" maxlength="10" size="8" value="<?php echo $data ?>"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
</td>
<td width="360">
<input name="modificatitolo" type="text" maxlength="50" size="50" value="<?php echo $title ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>50</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
</td>
</tr>
All is working quite well, except one thing:
when I select the news to edit, the content is from the server is correcly posted on the php, but on the HTML the scripts in the php (CKEDITOR and Char Cunter) are not active.
So, on my HTML, were the user will edit the news, i get only a simple textarea instead of the CKEDITOR, etc.
Is there a way to fix that? Can you help me somehow?
Thank you!
EDIT: I solved by myselft the problem. See solution as answer.
For those who have the same question:
I solved my problem in the following way: on javascript add a new row:
document.getElementById("newsdamodificare").action=CKEDITOR.replace('modificatesto');
between this 2 lines:
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
NEW LINE TO INSERT HERE
}
And remove from the php these rows:
<script>
CKEDITOR.replace('modificatesto');
</script>
Hope this helps!
You're trying to select your textarea by it's name, but CKEDITOR.replace('modificatesto'); is looking for an ID.
Try
<textarea id="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
I used Ajax to populate the values of second select tag but I am not able to populate the third select tag which should appear after the selection of the second select tag. Please suggest what's wrong.
index.php
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getclass(clas) {
var strURL="findbooks.php?clas="+clas;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('booksdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send();
}
}
function getbooks(clas,nme) {
var strURL="findprice.php?clas="+clas+"&nme="+nme;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('pricediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send();
}
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Class</td>
<td width="150"><select name="class" onChange="getclass(this.value)">
<option>select class</option>
<?php
for ($i=1;$i<=10;$i++)
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } ?>
</select></td>
</tr>
<tr style="">
<td>Books</td>
<td ><div id="booksdiv"><select name="Books" >
<option>Select books</option>
</select></div></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="pricediv"><select name="price">
<option>Select price</option>
</select></div></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
findbooks.php
<?php
$class=$_GET['clas'];
include "localhost.php";
$query="SELECT * FROM books WHERE class='".$class."'";
$result=mysql_query($query);
?>
<select name="books" onchange="getbooks(<?php $class; ?>,this.value)" >
<option>Select books</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option><?php echo $row['name'];?></option>
<?php
}
?>
</select>
findprice.php
<?php $class=$_GET['clas'];
$name=$_GET['nme'];
include "localhost.php";
$query="SELECT price FROM books WHERE class='$class' AND name='$name'";
$result=mysql_query($query);
?>
<select name="price">
<option>Select Price</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option><?php $row['price'] ?></option>
<?php } ?>
</select>
The solution is to use Jquery LIVEQUERY. Livequery utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements automatically, even after the page has been loaded!
$(document).ready(function() {
//Populate the third 'select' tag 'onchange' of second 'select' tag.
$('secondSelectTagID').livequery('change', function(){
//Add necessary code to populate third dropdown.
});
});
Note: You have to include both jquery.js and jquery.livequery.js for this approach to work.
In findprice.php
<?php
$class=$_GET['clas'];
include "localhost.php";
$query="SELECT * FROM books WHERE class='".$class."'";
$result=mysql_query($query);
?>
<select name="books" onchange="getbooks(<?php echo $class; ?>,this.value)" ><!--Notice the echo here-->
<option>Select books</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['name'];?>"><?php echo $row['name'];?></option><!--Notice the option value here-->
<?php
}
?>
</select>
And in findprice.php
<?php $class=$_GET['clas'];
$name=$_GET['nme'];
include "localhost.php";
$query="SELECT price FROM books WHERE class='$class' AND name='$name'";
$result=mysql_query($query);
?>
<select name="price" onchange="getbooks(<?php echo $class; ?>,<?php echo $name; ?>,this.value)>
<option>Select Price</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option><?php echo $row['price'] ?></option><!--Notice the echo here-->
<?php } ?>
</select>
I want to change the value of city drop-down on change of country drop-down. Well now stuck at on point when I select the value in the country it says he variable $r is undefined.
page : index.php
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
<option value="">Select Country</option>
<option value="1">USA</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
<option>Select City</option>
</select></div></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
page: findcity.php
<?php
$country=$_REQUEST['country'];
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="select city from city where countryid=$country";
$result=mysql_query($query);
?>
<select name="city">
<? while($r=mysql_fetch_array($result)) {
?>
<option value=""><?php echo $r['city'];?></option>
<? } ?>
</select>
here is the script
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
try using mysql_fetch_assoc instead of mysql_fetch_array
you miss to write "php" near <?(write down php here) while($r=mysql_fetch_array($result)) { ". and perform some debugging like check that are you getting the id of country or not than check the query returns the proper result or not or print the query on browser and run that query on Database.
change your code to..
<?php
while($r=mysql_fetch_array($result))
{
echo '<option value="">'.$r['city'].'</option>';
}
?>