How to validate dynamically generated input box with JavaScript - php

Hi, I have a form which has an ajax function which appends the data when the user enters the code and selects a value from the combo box. Since the data which is appended has dynamic rows I want to validate those input boxes so that a user can only enter a value such as 01, 02, 03....10 and if the user tries to enter a value which is greater than 10 it should display an alert box. So far, I have the script which does that but since the name attribute keeps on changing the validation doesn't seem to work. Can anyone help me out please?
Here is my JavaScript code:
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 getfunit2(makhcode, cmbmon) {
var strURL = "subjsele2.php?makhcode=" + document.nigran.makhcode.value + "&cmbmon=" + document.nigran.cmbmon.value;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('suboth').innerHTML = req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
Here is my PHP code:
<?php
$makhcode=$_GET["makhcode"];
$cmbmon=$_GET["cmbmon"];
$monno1 = "mon$cmbmon";
$con = mysql_connect('localhost', '****', '*****');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$scomp = mysql_query("SELECT * FROM subject WHERE compulsory !='1' ORDER BY ordby")or die(mysql_error());
if(mysql_num_rows($scomp)>0){
echo "<table>";
while($csub = mysql_fetch_assoc($scomp)){
$msubjcode = $csub["code"];
$csubqry = mysql_query("SELECT * FROM nigstat WHERE makhcode='".$makhcode."' AND subcode='".$msubjcode."'") or die(mysql_error());
$fetchmon = mysql_fetch_array($csubqry) ;
$mmonval = $fetchmon["$monno1"];
echo "<tr>";
echo "<td width='200px'><font color='#FF0033'><strong>".$csub[name]."</strong></td><td><input id='s_id' name='s_$csub[code]' type='text' onkeypress=\"return chknum()\" size='1' maxlength='2' value='$mmonval'></td><input type='hidden' name='$mmonval' size='3' maxlength='3'>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
Here is my HTML code:
<table border ="0px" width="100%">
<tr>
<td align="right" width="58px"><label class="" for="element_1"><font size="3px"><b>Code</b></font></label></td><td><input id="makhcode" name="makhcode" onkeyup="showyear('makhsele.php?makh='+this.value); getfunit(); getfunit2();" type="text" maxlength="6" size="6" value=""/></td><td><label class="description" align="right" for="element_1">Month</label></td><td><select id="cmbmon" name="cmbmon" class="" onchange="getfunit(); getfunit2();" style="font-size:14px;">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</td>
</tr>
</table>
<p style="border-bottom: 1px dotted #ccc;"></p>
<div id="makhhint" style=""></div>
<p style="border-bottom: 1px dotted #ccc;"></p><br />
<table border="0px" width="100%" cellspacing="0" cellpadding="0">
<th><div class="form_description"><h2>Compulsory Subjects</h2></div></th>
<th><div class="form_description"><h2>Other Subjects</h2></div></th>
<tr>
<td style="vertical-align: top;">
<div id="subcomp" align="left" align="top" style="background-color: #99FFFF;border: 1px solid black;padding:10px;">
</div>
</td>
<td style="vertical-align: top;">
<div id="suboth" align="left" align="top" style="background-color: #FFFFCC;border: 1px solid black;padding:10px;">
</div>

use this function to validate code
<input type="text" id="fname" onkeyup="validate_code(this)">
function validate_code(that)
{
if(isNaN(that.value)==true || that.value>10)
{
that.value='';
alert('enter a valid value');
}
return true
}
link to example validation example

Related

split Import CSV to mysql database restricted

I have a php script that ask the user to upload a csv, then it display the result before importing and ask the user to map the fields corresponding to the database tables. It work fine.
My problem is that it seems that the server restrict the number of post or insert that can be made. So I can insert like 75 lines. But I have something like 600 lines. How could I split those like maybe in different files or maybe INFILE function.
I'm a little bit loss on that one. Because also, the user can select wich record he wants to be inserted with checkboxes.
<?php
setlocale(LC_ALL,"en_US.UTF-8");
ob_start();
if(!isset($_SESSION))
{
session_start();
}
//variables
$upload_file='';
$err='';
$msg='';
include "config.php";
if(isset($_POST['frm_type'])) // Insert Records
{
if(isset($_POST['frm_type']) && $_POST['frm_type']=='custom')
{
if(count($_POST["chk"])>0)
{
$count_cols=$_POST["h_cols"];
foreach($_POST["chk"] as $index)
{
$query="";
$dyn_query="";
$select_where="";
$date_reg=date('Y-m-d');
//STATIC COLUMN
$query = "cat_id='".$_POST["cat_id".$index]."'";
$query .= ",date_reg='".$date_reg."'";
$query .= ",user_id='".$_SESSION['user_id']."'";
$query .= ",type_client='".$_SESSION['cltype']."'";
$query .= ",birthday_switch='1',";
//DYNAMIC COLUMN
for($s=0; $s<$count_cols;$s++)
{
if(isset($_POST["colum_".$s]) && $_POST["colum_".$s]!='')
{
$value=Add_Slashes($_POST["row_".$s."_".$index]);
$dyn_query[]="".$_POST["colum_".$s]."='".$value."'";
}
if($_POST["colum_".$s]=="full_name")
{
$value=trim($_POST["row_".$s."_".$index]);
if($value!="")
{
$allow=1;
}
else
{
$allow=0;
}
}
}
if($dyn_query)
{
if($allow==1)
{
$query .=implode(',',$dyn_query);
$select_where[]="cat_id='".$_POST["cat_id".$index]."'";
$select_where[]="user_id='".$_SESSION['user_id']."'";
$select_where[]="type_client='".$_SESSION['cltype']."'";
for($t=0; $t<$count_cols;$t++)
{
if(isset($_POST["colum_".$t]) && $_POST["colum_".$t]!='')
{
$value=Add_Slashes($_POST["row_".$t."_".$index]);
$select_where[]="".$_POST["colum_".$t]."='".$value."'";
}
}
$select_where_query=implode(' AND ', $select_where);
$re = mysql_query("Select cat_id From clients Where $select_where_query");
if(mysql_num_rows($re)==0)
{
mysql_query("Insert Into clients Set $query");
$msg = "<span class='error' style=\"color:green;\"><b>Data Successfully Imported Into The Database</b></span>";
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Data Already Existed in Database</b></span>";
}
}
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Please select fields!</b></span>";
}
}
if(file_exists($_SESSION["FILENAME"]))
unlink($_SESSION["FILENAME"]);
}
}
}
if(isset($_POST['submt']))
{
if($_FILES['filename']["name"]=="")
$err = "<span class='error'>".IMPORT_PLEASE."</span>";
elseif(substr(strrev($_FILES['filename']["name"]),0,3)!="vsc")
$err = "<span class='error'>".IMPORT_INVALID."</span>";
else
{
$_SESSION['cltype']=$_POST['cltype'];
set_time_limit(0);
if(file_exists($Upload_Path.$_FILES['filename']["name"]))
$filename = GetRandomString(6).$_FILES['filename']["name"];
else
$filename = $_FILES['filename']["name"];
if(move_uploaded_file($_FILES['filename']["tmp_name"],$Upload_Path.$filename))
{
$upload_file = $Upload_Path.$filename;
$_SESSION["FILENAME"] = $upload_file;
}
else
$err = "<span class='error'>".IMPORT_FAIL."</span>";
set_time_limit(30);
}
}
?>
<script>
function Check_All2(obj,arr)
{
if(obj.checked)
{
var i=document.cfrm.elements.length;
var j;
for(j=0;j<i;j++)
{
if(document.cfrm.elements[j].name==arr)
document.cfrm.elements[j].checked=true;
}
}
else
{
var k=document.cfrm.elements.length;
var l;
for(l=0;l<k;l++)
{
if(document.cfrm.elements[l].name==arr)
document.cfrm.elements[l].checked=false;
}
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('#cfrm').submit(function(event) {
colums = jQuery('select.colum');
var arr = new Array();
var h_status=false;
colums.each(function()
{
var el=jQuery(this).val();
if(el!='')
{
h_status=true;
if(jQuery.inArray(el,arr)>-1)
{
event.preventDefault();
jQuery(this).css("border","2px solid red");
alert("Duplicated Fields!");
jQuery(this).focus();
return false;
}
else
{
arr.push(el);
jQuery(this).css("border","");
}
}
});
chks = jQuery('.chk');
chks.each(function()
{
if (jQuery(this).is(':checked'))
{
h_cols=jQuery('#h_cols').val();
var mand=1;
for(var k=0; k<=h_cols; k++)
{
colum_id='#colum_'+k;
colum_value=jQuery(colum_id).val();
flel_object=jQuery('#row_'+k+'_'+jQuery(this).val());
flel_value=jQuery('#row_'+k+'_'+jQuery(this).val()).val();
if(colum_value=='full_name')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Full Name');
flel_object.focus();
return false;
}
}
else if(colum_value=='aaa')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Email');
flel_object.focus();
return false;
}
}
}
}
});
if(!h_status)
{
event.preventDefault();
alert('Select Any Field To Insert!');
return false;
}
});
});
</script>
<script type="text/javascript" src="ajaxsublistgenerator.js"></script>
<table class="sub" height="20px" width="100%" border="0" cellpadding="0" cellspacing="0" align="center"></table>
<table width="99%" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td>
<fieldset>
<?
if($upload_file=="")
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CSV;?></legend>
<form name="frm" action="" method="post" enctype="multipart/form-data">
<table width="45%" border="0" cellpadding="4" cellspacing="4" align="center">
<?
if($err!="" || $msg!="")
{
?>
<tr><td colspan="2"><?=($err!="") ? $err : $msg?></td></tr>
<?
}
?>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_FILE;?></b></td>
<td width="70%" align="left" valign="middle">
<input name="filename" id="filename" type="file" size="25" />
</td>
</tr>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_SECTION;?></b></td>
<td width="70%" align="left" valign="middle">
<select name="cltype" id="cltype">
<option value="Client">Clients</option>
<option value="prospect">Leads</option>
<option value="Contacts">Contacts</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td align="left" valign="middle">
<input name="submt" type="submit" value="<?=IMPORT_UPLOAD;?>">
</td>
</tr>
</table>
</form>
<script>document.getElementById("filename").focus();</script>
<?
}
else
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CONTENT;?></legend>
<form name="cfrm" id="cfrm" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="frm_type" id="frm_type" value="custom">
<div style="overflow:auto;width:100%;">
<table border="0" cellspacing="4" cellpadding="4" align="center" width="100%">
<tr>
<td width="5%" align="center">
<input onClick="javascript:Check_All2(this,'chk[]')" type="checkbox" checked="checked">
</td>
<td width="10%" align="center"><b><?=IMPORT_CAT;?></b></td>
<?php
$fd_header = fopen ($upload_file, "r");
$buffer_header = fgetcsv($fd_header, 100000, ',');
//print_r(count($buffer_header));
for($r=0; $r<count($buffer_header);$r++)
{
?>
<td width="10%" align="center">
<select class="colum" name="colum_<?php echo $r;?>" id="colum_<?php echo $r;?>">
<option value="">--Select Field--</option>
<option value="full_name">Name</option>
<option value="address">Address</option>
<option value="city">City</option>
<option value="state">Province</option>
<option value="zip">Code Postal</option>
<option value="country">Country</option>
<option value="home_phone">Tel(Home)</option>
<option value="work_phone">Tel(Work)</option>
<option value="cell_phone">Tel(Mobile)</option>
<option value="email">Email</option>
<option value="conjoint">Joint</option>
<option value="notes">Notes</option>
<option value="birthday">Birthday</option>
</select><input type="hidden" id="h_cols" name="h_cols" value="<?php echo count($buffer_header); ?>" />
</td>
<?php } ?>
</tr>
<?
$fd = fopen ($upload_file, "r");
$i=1;
while (!feof ($fd))
{
$buffer_header = fgetcsv($fd, 100000, ',');
?>
<tr>
<td align="center"><input class="chk" type="checkbox" value="<?=$i?>" name="chk[]" checked="checked" /></td>
<td align="left" ><?php $sql_cat_names = mysql_query("select * from clients_cat where user_id='".$_SESSION['user_id']."' order by cat_name") ;?>
<select class="ann_select" name="cat_id<?=$i?>" id="cat_id<?=$i?>">
<?php while($row_cat_names = mysql_fetch_array($sql_cat_names)){?>
<option value="<?=$row_cat_names['id']?>"><?=$row_cat_names['cat_name']?></option>
<?php } ?>
</select>
</td>
<?php
for($v=0; $v<count($buffer_header);$v++)
{
?>
<td align="center">
<input type="text" value="<?=$buffer_header[$v]?>" name="row_<?=$v?>_<?=$i?>" id="row_<?=$v?>_<?=$i?>" />
</td>
<?php } ?>
</tr>
<?php
$i++;
unset($buffer_header);
}
fclose ($fd);
?>
<tr>
<td colspan="7" align="center">
<input name="Submit" id="Submit" type="submit" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
<?php
}
?>
</fieldset>
</td>
</tr>
</table>
You may insert multiple values in an only insert, and reduce the DDBB load.
In your PHP code, you receive the values, and make a foreach to insert each row one by one. What you should have to do is change your one by one insert to a multiple to one insert.
You're doing:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2');
INSERT INTO table (field1, field2) VALUES ( 'value3', value4');
INSERT INTO table (field1, field2) VALUES ( 'value5', value6');
That gives you 3 connection to database, 3 inserts. Your query should be:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2'), ('value3, 'value4'), ('value5', 'value6');
That gives you 1 connection to database, 3 inserts. Same result, less load.
UPDATE
To accomplish it in your code, you must create a string inside of your foreach with the data you want to insert: Validate the fields, create the string, and then insert them into the DDBB with an insert sentence that is out of your foreach. It's going to be a mess if I try to do it without running the script to check everything goes well, so I can only point you in the way to do the job.

Submitting dynamic ajax field

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 !!!

Populate the third select tag using the value of second select tag which has its values from the database using the first select tag

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>

updating drop-down on change of another drop-down using php-ajax

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>';
}
?>

JavaScript function not executing

I need an extra set of eyes here. I've been over this numerous times with no success. The issue is the getFilename function, which as the name suggests, is supposed to get the file name of the uploaded file. No matter what I do, it doesn't seem to work, so I must be missing something.
<?php
$data = $_GET["data"];
if($data)
{
echo '
<head>
<style>
.atklf
{
color: Red;
background: #292929;
border: 1px solid Red
}
</style>
</head>
<iframe name="fuh1" style="display: none;"></iframe>
<form
action="attklstformupldproc.php"
method="post"
target="fuh1"
enctype="multipart/form-data">
<table border="2" cellpadding="3" frame="void" style="color: red; width:100%;">
<tr>
<td>Priority:</td>
<td>Pirate: <span id="Pirreq"></span></td>
<td>Level:</td>
<td>Known Fleet Level:</td>
<td>X:</td>
<td>Y:</td>
</tr>
<tr>
<td>
<select id="Priority" class="atklf" name="Priority">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</td>
<td><input id="Pirate" class="atklf" name="Pirate" type="text" size="17" /></td>
<td><input id="Level" class="atklf" name="Level" type="text" size="4" /></td>
<td><input id="Fleet_Level" class="atklf" name="Fleet_Level" type="text" size="4" /></td>
<td><input id="XCoord" class="atklf" name="XCoord" type="text" size="5" /></td>
<td><input id="YCoord" class="atklf" name="YCoord" type="text" size="5" /></td>
</tr>
<tr>
<td>Outpost Level:</td>
<td>Known Wall Level:</td>
<td>Known Turret Level:</td>
<td colspan="2">Turret Types:</td>
<td>Group: <span id="Grpreq"></span></td>
</tr>
<tr>
<td><input id="Outpost_Level" class="atklf" name="Outpost_Level" type="text" size="4" /></td>
<td><input id="Knwn_wall_lvl" class="atklf" name="Knwn_wall_lvl" type="text" size="4" /></td>
<td><input id="Knwn_turr_lvl" class="atklf" name="Knwn_turr_lvl" type="text" size="4" /></td>
<td colspan="2" rowspan="2"><textarea id="Turret_Types" class="atklf" name="Turret_Types" rows="5" cols="16"></textarea></td>
<td rowspan="2">
<select id="Group" class="atklf" name="Group">
<option value="null">Pick a group</option>
<option value="General">General</option>
<option value="Sector 23">Sector 23</option>
<option value="Max Chaos">Max Chaos</option>
</select>
</td>
</tr>
<tr>
<td>Base Picture:</td>
<td colspan="2"><input id="Base_Picture" name="uploaded_bp" class="atklf" type="file" /></td>
</tr>
<tr>
<td colspan="6">Notes:</td>
</tr>
<tr>
<td rowspan="1" colspan="6"><textarea id="Notes" class="atklf" name="Notes" rows="7" cols="60"></textarea></td>
</tr>
<tr>
<td align="center"><input id="hlfsubmit" class="atklf" name="submit" value="Submit" type="submit" style="width: 90px;" onClick="assignVars()" /></td>
</tr>
<input type="button" class="atklf" value="Reset debug" onClick="resetDebug()"/>
<input type="button" class="normal" value="Get File name" onClick="getFilename1()"/>
</table>
</form>
<script type="text/javascript">
function resetDebug() {
document.getElementById("debug1").innerHTML = "";
}
function formFieldvalue(id) {
return document.getElementById(id).value;
}
function getFilename1() {
document.getElementById("debug1").innerHTML = formFieldvalue("Base_Picture");
}
Pri = "1";
Pir = "null";
Grp = "null";
function assignVars () {
Pri = document.getElementById("Priority").options[document.getElementById("Priority").selectedIndex].value;
Pir = encodeURIComponent(formFieldvalue("Pirate"));
if (formFieldvalue("Level")) {
Lvl = encodeURIComponent(formFieldvalue("Level"));
}
else {
Lvl = encodeURIComponent("?");
}
if (formFieldvalue("Fleet_Level")) {
Flv = encodeURIComponent(formFieldvalue("Fleet_Level"));
}
else {
Flv = encodeURIComponent("?");
}
if (formFieldvalue("XCoord")) {
XCd = encodeURIComponent(formFieldvalue("XCoord"));
}
else {
XCd = encodeURIComponent("?");
}
if (formFieldvalue("YCoord")) {
YCd = encodeURIComponent(formFieldvalue("YCoord"));
}
else {
YCd = encodeURIComponent("?");
}
if (formFieldvalue("Notes")) {
Nts = encodeURIComponent(formFieldvalue("Notes"));
}
else {
Nts = encodeURIComponent("?");
}
if (formFieldvalue("Outpost_Level")) {
Opl = encodeURIComponent(formFieldvalue("Outpost_Level"));
}
else {
Opl = encodeURIComponent("?");
}
if (formFieldvalue("Knwn_wall_lvl")) {
Kwl = encodeURIComponent(formFieldvalue("Knwn_wall_lvl"));
}
else {
Kwl = encodeURIComponent("?");
}
if (formFieldvalue("Knwn_turr_lvl")) {
Ktl = encodeURIComponent(formFieldvalue("Knwn_turr_lvl"));
}
else {
Ktl = encodeURIComponent("?");
}
if (formFieldvalue("Turret_Types")) {
Tty = encodeURIComponent(formFieldvalue("Turret_Types"));
}
else {
Tty = encodeURIComponent("?");
}
Grp = encodeURIComponent(formFieldvalue("Group"));
insertAttacktablerow();
}
if ( window.addEventListener ) {
window.addEventListener( "load", insertAttacktablerow, false );
}
else if ( window.attachEvent ) {
window.attachEvent( "onload", insertAttacktablerow );
}
function insertAttacktablerow() {
if (Pir != "null" && Grp != "null") {
document.getElementById("Pirreq").innerHTML = "";
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) {
//updateAttacktable();
document.getElementById("debug1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/attacklist/attklstformproc.php?Pri=" + Pri + "&Pir=" + Pir + "&Lvl=" + Lvl + "&Flv=" + Flv + "&XCd=" + XCd + "&YCd=" + YCd + "&Nts=" + Nts + "&Opl=" + Opl + "&Kwl=" + Kwl + "&Ktl=" + Ktl + "&Tty=" + Tty + "&Grp=" + Grp + "&data=' . $data . '",true);
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlhttp.send();
document.forms[0].reset();
}
else if (Pir == "null") {
document.getElementById("Pirreq").innerHTML = "(<b>required</b>)";
document.getElementById("Pirreq").style.color = "red";
}
else if (Grp == "null") {
document.getElementById("Grpreq").innerHTML = "(<b>required</b>)";
document.getElementById("Grpreq").style.color = "red";
}
}
</script>
<span id="debug1"></span>';
}
else
{
echo 'Restricted access.';
}
OK, so I removed my last answer because I finally took the time to execute your code. As you have it, it works for me.
Here's what I suggest you do. Remove your HTML and JavaScript and place them in a stand alone html file and load it in your browser. Add the necessary tags to make it complete. (Also, you're missing a "body" tag, not that this is the source of your problem.)
Then test it. If it works, then your problem is coming from somewhere else not in the code you provided. Do you have header and footer code somewhere?
If it doesn't work, start removing HTML and JavaScript in portions until it does work. Use this to isolate the cause of your bug.
Good luck.

Categories