Tic Tac Toe logic errors - php

My program here is a simple tic tac toe game and my winners are not being displayed properly the only 4 correct ones are the two diagonals and row ones win and column win.The html/javascript is not the problem its just the php.
<?php
//Players
$X = "Dalton";
$O = "Joe";
$winner = false;
//game board positoins
$r1c1 = !empty($_POST['r1c1'] ) ? $_POST['r1c1'] : '';
$r1c2 = !empty($_POST['r1c2'] ) ? $_POST['r1c2'] : '';
$r1c3 = !empty($_POST['r1c3'] ) ? $_POST['r1c3'] : '';
$r2c1 = !empty($_POST['r2c1'] ) ? $_POST['r2c1'] : '';
$r2c2 = !empty($_POST['r2c2'] ) ? $_POST['r2c2'] : '';
$r2c3 = !empty($_POST['r2c3'] ) ? $_POST['r2c3'] : '';
$r3c1 = !empty($_POST['r3c1'] ) ? $_POST['r3c1'] : '';
$r3c2 = !empty($_POST['r3c2'] ) ? $_POST['r3c2'] : '';
$r3c3 = !empty($_POST['r3c3'] ) ? $_POST['r3c3'] : '';
if($r1c1 == $r1c2 && $r1c2 == $r1c3 ) {
$winner = $r1c1;
} elseif($r2c1 == $r2c2 && $r2c2 == $r2c3 ) {
$winner = $r2c1;
} elseif($r3c1 == $r3c2 && $r3c2 == $r3c3 ) {
$winner = $r3c1;
} elseif($r1c1 == $r2c1 && $r2c1 == $r3c1 ) {
$winner = $r1c1;
} elseif($r1c2 == $r2c2 && $r2c2 == $r3c2 ) {
$winner = $r1c2;
} elseif($r1c3 == $r2c3 && $r2c3 == $r3c3 ) {
$winner = $r1c3;
} elseif($r1c1 == $r2c2 && $r2c2 == $r3c3 ) {
$winner = $r1c1;
} elseif($r1c3 == $r2c2 && $r2c2 == $r3c1 ) {
$winner = $r1c3;
} else {
$winner = 'Draw';
}
?>
<html>
<head>
<title>Tic-Tac-Toe</title>
<!--
The Javascript code below requires access to the internet to run. If you are
running this page on a computer with no Internet access, it will cause errors.
You may delete these lines or modify them if you wish.
The 1st block in the code below is helping you by not allowing any character
except an uppercase 'X' or uppercase 'O'. This is unnessisary, but makes it easier
for you to process on the PHP side.
The 2nd block of code is helping you by making any field that already has has
'X' or 'O' readonly when the page loads. Extra points will be giving to any student
how can replicate this part of the Javascript using only PHP. Simply delete the lines
below if you wish to attempt.
-->
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
// This block of code prevents you from entering anything but X or O
$('input').bind('keyup',function() {
if( $(this).hasClass('button') == false ){
this.value = this.value.toUpperCase();
if(this.value != 'X' && this.value != 'O') {
this.value = '';
}
}
});
// This block of code makes the used spots on the grid readonly once used
$('input').each(function(i){
this.value = this.value.toUpperCase();
if(this.value == 'X' || this.value == 'O') {
$(this).addClass('disabled').attr('readonly', true);
//this.readOnly = true;
}
});
});
</script>
<!-- You may do as you please with this CSS code -->
<style>
body * { padding:0; margin:0; }
.disabled { background: #eeeeee; }
.button { display: block; width:180px; margin: 10px 0; }
#gameboard { border-collapse:collapse; padding:0; margin:0; }
#gameboard tr:nth-child(even) {
border-top:2px solid black;
border-bottom:2px solid black;
}
#gameboard tr td:first-child { border-right:2px solid black; }
#gameboard tr td:last-child { border-left:2px solid black; }
#gameboard input {
font-size:50px;
width:60px;
padding:3px;
text-transform:uppercase;
text-align:center;
}
</style>
</head>
<body>
<!--
Notice that the default values for each box below is set to '', and empty string.
You will have to set them using data from the $_POST, if you don't the game will
reset after every move. Something like this for every box maybe ...
if( !empty($_POST['r1c0']) ) {
$r1c0 = $_POST['r1c0'];
} else {
$r1c0 = '';
}
-->
<form action="" name='game' method='POST'>
<table cellpadding='0' cellspacing='0' id='gameboard'>
<tr>
<td><input type='text' maxlength='1' name='r1c1' value='<?php echo $r1c1; ?>' /></td>
<td><input type='text' maxlength='1' name='r1c2' value='<?php echo $r1c2; ?>' /></td>
<td><input type='text' maxlength='1' name='r1c3' value='<?php echo $r1c3; ?>' /></td>
</tr>
<tr>
<td><input type='text' maxlength='1' name='r2c1' value='<?php echo $r2c1; ?>' /></td>
<td><input type='text' maxlength='1' name='r2c2' value='<?php echo $r2c2; ?>' /></td>
<td><input type='text' maxlength='1' name='r2c3' value='<?php echo $r2c3; ?>' /></td>
</tr>
<tr>
<td><input type='text' maxlength='1' name='r3c1' value='<?php echo $r3c1; ?>' /></td>
<td><input type='text' maxlength='1' name='r3c2' value='<?php echo $r3c2; ?>' /></td>
<td><input type='text' maxlength='1' name='r3c3' value='<?php echo $r3c3; ?>' /></td>
</tr>
</table>
<?php if($winner != '') { ?>
<h3><?php echo "The winner is ".$winner; ?></h3>
<?php } else { ?>
<input class='button' type='submit' value='Finish Move' />
<input class='button' type="reset" value="Reset Game" />
<?php } ?>
</form>
</body>
</html>

Adding something like this at the top of your code should make it work. Some of your cells are passing lower case values. You should probably put in some other error checking as Javascript can be manipulated.
foreach ($_POST as $key => $val) {
$_POST[$key] = strtoupper($val);
}

Related

How I can do remember text in input

I have two problems with the following code, i.e.
I would like saved values in input to be remembered, because now it returns the value " Notice : Undefined variable: name_check in".
If the domain length is shorter than 5 characters, it returns an error but only at the first input, and I would like the validation error to be at each of the inputs.
<?php
require_once "connect.php";
$connect = #new mysqli($host, $db_user, $db_password, $db_name);
if(isset($_POST['send']))
{
$all_ok=true;
$id = $_POST['id'];
$domain_name = $_POST['domain_name'];
foreach ($domain_name as $value)
{
if (strlen($value)<5)
{
$all_ok=false;
$_SESSION['e_name']="Wpisana domena jest zbyt króka.";
}
}
$_SESSION['fr_name'] = $value;
if ($all_ok==true)
{
$count = count($id);
for($i=0;$i<$count;$i++) {
$connect->query('UPDATE domains SET domain_name="'.$domain_name[$i].'" WHERE id='.(int)$id[$i].'');
}
$_SESSION['well_done']=true;
echo "udana walidacja";
}
}
?>
<style>
.error
{
color:#cc0000;
margin-top: 5px;
margin-bottom: -5px;
font-size:12px;
}
</style>
<form method="POST" action="">
<table>
<?php
$result = $connect->query("SELECT * FROM domains");
$how_nick = $result->num_rows;
if ($how_nick != 0) {
while($data = $result->fetch_assoc())
{
?>
<tr>
<td>Nazwa Domeny:<br> <input type="text" value="<?php
if (isset($_SESSION['fr_name']))
{
echo $_SESSION['fr_name'];
unset($_SESSION['fr_name']);
}
else
{
echo $data['domain_name'];
}
?>" name="domain_name[]"><br /><?php
if (isset($_SESSION['e_name']))
{
echo '<div class="error">'.$_SESSION['e_name'].'</div>';
unset($_SESSION['e_name']);
}
?></td>
<td><input type="hidden" name="id[]" value="<?php echo $data['id'];?>"/></td>
</tr>
<?php
}}
?>
</table>
<br /><center><input class="button" type="submit" name="send" value="Zapisz"></center>
</form>

Not all checkbox values passed in a form when the very last ones are selected

I am working on a page that deals with a lot of data that the user can select what to pass to another page via a form. I have stumbled upon a big problem: When I want to pass the first items on the list the page does it flawlessly. However when I want to just select the very last items they're not being passed. Example
Can you please tell me what is going on? Thanks!
Code that creates the checkboxes. All 1085 of them:
echo "<form name='frmIns' method = 'POST' action = 'xx.php'>";
if(mysqli_num_rows($tablaO)>0)
{
$i = 0;
$e = 1;
while($registroO=mysqli_fetch_assoc($tablaO))
{
if ($e%2== 0)
{
if($registroO['art_nota'] == 'Inventario' || $registroO['art_nota'] == 'Espera de Devolución' || $registroO['art_nota'] == 'Se va a Inventario') $color = 'e9bd15';
else $color='c5efef';
}else{
if($registroO['art_nota'] == 'Inventario' || $registroO['art_nota'] == 'Espera de Devolución' || $registroO['art_nota'] == 'Se va a Inventario') $color = 'e9bd15';
else $color='fdfdfd';
}
$ValidacionID = $registroO['art_id_verificador'];
if($ISBN13r == null and $libro != null && $articulos == null)
{
$Idverificador = $registroO['art_id_verificador'];
echo '<tr valign="top" class="registro" name="tr/'.$i.'" id="tr/'.$Idverificador.'" style="font-size: 11.5px; text-align: -webkit-center; background-color:#'.$color.'">
<td>'.$e.'</td>
<td>
<input type="checkbox" name="chbArticulo[]" value="'.$Idverificador.'" onChange="cambia(this)" />
<input type="hidden" name="IDEs[]" value="'.$Idverificador.'" />
<input type="hidden" name="IdVerif[]" value="'.$ValidacionID.'" />
</td>';
}else if($ISBN13r != null and $libro == null && $articulos == null){
echo'<tr valign="top" class="registro" style="font-size: 11.5px; text-align: -webkit-center; background-color:#'.$color.'">
<td>'.$e.'</td>
<td></td>';
}else{
$Idverificador = $registroO['art_id_verificador'];
echo '<tr valign="top" class="registro" name="tr/'.$i.'" id="tr/'.$Idverificador.'" style="font-size: 11.5px; text-align: -webkit-center; background-color:#'.$color.'">
<td>'.$e.'</td>
<td>
<input type="checkbox" name="chbArticulo[]" value="'.$Idverificador.'-'.$Idverificador.'" onChange="cambia(this)" />
<input type="hidden" name="IDEs[]" value="'.$Idverificador.'" />
<input type="hidden" name="IdVerif[]" value="'.$ValidacionID.'" />
</td>';
}
echo'<td>'.$registroO['art_id_verificador'].'</td>
<td>'.$registroO['art_id_orden'].'</td>
<td>'.$registroO['art_fecha'].'</td>
<td>'.$registroO['art_N13'].'</td>
<td>'.$registroO['art_destino'].'</td>
<td style="'.($registroO['art_ofna_de'] != "" || $registroO['art_ofna_de'] != null ? "background-color:yellow;" : "").'">'.$registroO['art_ofna_de'].'</td>
<td>'.$registroO['art_ISBN'].'</td>
<td style = "max-width:250px; overflow:ellipsis;">'.$registroO['art_titulo'].'</td>
<td>'.$registroO['art_SKU'].'</td>
<td>'.$registroO['art_cantidad'].'</td>
<td>$'.number_format(($registroO['art_precio_logistica'] > 0 ? $registroO['art_precio_logistica'] : $registroO['art_precio']),2,".",",").'</td>
<td>'.$registroO['art_id_proveedor'].'</td>
<td>'.$registroO['art_nota'].'</td>
<td>'.($registroO['art_guia_ofna_arg'] == '' ? $registroO['art_guia_ofna'] : $registroO['art_guia_ofna_arg']).'</td>
</tr>';
$i=$i+ 1;
$e=$e+ 1;
/*<td>'.$registroO['OfMi_pvp'].'</td>
<td>'.$registroO['OfMi_costUnitario'].'</td>
<td>'.$registroO['OfMi_TotalDeposito'].'</td>
<td>'.$registroO['OfMi_TotalOrden'].'</td>
<td>'.$registroO['OfMi_MarginProf'].'</td>*/
}
}
echo "</form>";

How to make an entry in a text box required when one specific radio button is selected?

I have several radio buttons which can be chosen and then the form can be sent without an issue. However a user can easily select the "Other" radio button and submit without giving any context or reason on why they chose it leaving the people receiving the "completed" form guessing what the issue is.
What I want to happen is that if a person selects the "Other" radio button and try and submit without a note/message/comment they will be interrupted with a requirement massage.
The snippet of the form that I want this to happen to is:
<label>
<input name="category" type="radio" value="Other" checked>Other
</label><br><br><br>
Note: <br> <textarea name="comment" rows="10" cols="70" placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly">
I have tried many variations of if statements and the required function given with HTML5 but can not seem to get what I need.
Any help will be appreciated and thanks in advance.
Edit 1:
Here is the full code of my form:
<form action="send_form_email.php?OperationID=<?php print ($OperationID) ?>&title=<?php print ($title) ?>" method="post" onsubmit="return this.users.value != ''">
<table>
<tr>
<td>Name:</td>
<td>
<select required name="users">
<option value=""></option>
<?php
foreach($users as $key => $value){
echo "<option value=\"$key\">$key</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td <?php print $hiddenJobDiv ?>>Job Number:</td>
<td><input type="text" name="jobid" value="<?php echo ($jobid) ?>" <?php echo $disabledInput ?>></td>
</tr>
<tr>
<td <?php print $hiddenPartDiv ?>>Part Number:</td>
<td><input type="text" name="partid" value="<?php echo ($part_id) ?>" <?php echo $disabledInput ?>></td>
</tr>
<?php if ($OperationID == 20){ ?>
<tr>
<td>Machine:</td>
<td><input type="text" name="mach" value="<?php echo ($machCode) ?>" <?php echo $disabledInput ?>></td>
<tr>
<?php } ?>
</table><br>
Error:<br><br><br> <!-- Display of dynamic list. -->
<?php
$html = customErr($OperationID);
foreach ($html as $oneError):?> <!-- foreach used to find the next iteration of the array. -->
<label> <!-- Beginning of the dynamic radio button list. -->
<input name="category"
type="radio"
value="<?php echo $oneError; ?>"> <!-- Dynamic value to be used in Slack API and email. -->
<?php echo $oneError; ?> <!-- Dynamic value as a visual representation for user. -->
</label><br><br><br>
<?endforeach;?> <!-- Stops foreach and goes to next object if avaliable. -->
<label> <!-- A permanent radio button labeled "Other" for (cont.) -->
<input name="category" type="radio" value="Other" checked>Other <!-- all report error forms. -->
</label><br><br><br>
<?php
if (isset($_POST['category'])=="Other" && isset($_POST["comment"])=="")
{
$required[] = ("You must write a note if you choose \'other\'.");
}
return $required;
?>
Note: <?php echo $required ?> <br> <textarea name="comment" rows="10" cols="70"
placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea> <!-- Allows the user to type in a custom message/note. -->
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly"> <!-- A large 'submit' button for touch screen. -->
<input type="submit" name="close" value="Close" class="userFriendly"> <!-- A large 'close' button for touch screens. -->
</form>
Edit 2:
Here is the full code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/main_style.css">
<style>
.error {color: #FF0000;}
table, th, td {border: 1px solid white;}
</style>
</head>
<body>
<script>
function close_window() {
close();
}
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include("includes/classes.php");
include("includes/classes_monitoring.php");
$link = open_v8_db();
$users = get_clocked_in_users();
$OperationID = #$_REQUEST['OperationID'];
$title = "";
$grayedOut = false;
$disabledInput = "";
$hiddenJobDiv = "";
$hiddenPartDiv = "";
$ID = "";
$html = "";
$jobid = #$_REQUEST['JobID'];
$part_id = #$_REQUEST['PartID'];
$machCode = #$_REQUEST['Machine'];
if ($OperationID == 20)
{
$title = "Punching Machine";
$grayedOut = true;
}
elseif ($OperationID == 30)
{
$title = "Folding Machine";
$grayedOut = true;
}
elseif ($OperationID == 40 || $OperationID == 140)
{
$title = "Powder Coating";
$grayedOut = true;
}
elseif ($OperationID == 50 || $OperationID == 150)
{
$title = "Assembly";
$grayedOut = true;
}
elseif ($OperationID == 60 || $OperationID == 160)
{
$title = "Inspection";
$grayedOut = true;
}
elseif ($jobid != "" && $part_id == "")
{
$title = "Job";
$OperationID = 70;
}
else
{
$title = "General";
$OperationID = 80;
$grayedOut = false;
}
if ($greyedOut = true)
{
$disabledInput = "readonly";
}
function customErr($ID)
{
$html = "";
$issueReport_folder = 'document/Production System/';
$issueReporting = $issueReport_folder.'IssueReporting.csv';
$file_handle = fopen($issueReporting, "r");
if ($ID == 20)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Punch")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 30)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Fold")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 40 || $ID == 140)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Powder")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 50 || $ID == 150)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Assembly")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 60 || $ID == 160)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Inspectoin")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 70)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Job")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 80)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "General")
{
$html[] = $line_of_text[1];
}
}
}
fclose($file_handle);
return $html;
}
$jobErr = $partErr = $machErr = "";
$job = $part = $mach = $note = "";
if ($jobid == "")
{
$hiddenJobDiv = "style=\"display:none;";
}
if ($part_id == "")
{
$hiddenPartDiv = "style=\"display:none;";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="reportForm">
<h2>Report <u><?php echo $title; ?></u> Error</h2>
<form action="send_form_email.php?OperationID=<?php print ($OperationID) ?>&title=<?php print ($title) ?>" method="post" onsubmit="return this.users.value != ''">
<table>
<tr>
<td>Name:</td>
<td>
<select required name="users">
<option value=""></option>
<?php
foreach($users as $key => $value){
echo "<option value=\"$key\">$key</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td <?php print $hiddenJobDiv ?>>Job Number:</td>
<td><input type="text" name="jobid" value="<?php echo ($jobid) ?>" <?php echo $disabledInput ?>></td>
</tr>
<tr>
<td <?php print $hiddenPartDiv ?>>Part Number:</td>
<td><input type="text" name="partid" value="<?php echo ($part_id) ?>" <?php echo $disabledInput ?>></td>
</tr>
<?php if ($OperationID == 20){ ?>
<tr>
<td>Machine:</td>
<td><input type="text" name="mach" value="<?php echo ($machCode) ?>" <?php echo $disabledInput ?>></td>
<tr>
<?php } ?>
</table><br>
Error:<br><br><br> <!-- Display of dynamic list. -->
<?php
$html = customErr($OperationID);
foreach ($html as $oneError):?> <!-- foreach used to find the next iteration of the array. -->
<label> <!-- Beginning of the dynamic radio button list. -->
<input name="category"
type="radio"
value="<?php echo $oneError; ?>"> <!-- Dynamic value to be used in Slack API and email. -->
<?php echo $oneError; ?> <!-- Dynamic value as a visual representation for user. -->
</label><br><br><br>
<?endforeach;?> <!-- Stops foreach and goes to next object if avaliable. -->
<label> <!-- A permanent radio button labeled "Other" for (cont.) -->
<input name="category" type="radio" value="Other" checked>Other <!-- all report error forms. -->
</label><br><br><br>
<?php
if (isset($_POST['category'])=="Other" && isset($_POST["comment"])=="")
{
$required[] = ("You must write a note if you choose \'other\'.");
}
return $required;
?>
Note: <?php echo $required ?> <br> <textarea name="comment" rows="10" cols="70"
placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea> <!-- Allows the user to type in a custom message/note. -->
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly"> <!-- A large 'submit' button for touch screen. -->
<input type="submit" name="close" value="Close" class="userFriendly"> <!-- A large 'close' button for touch screens. -->
</form> <!-- End of form. -->
</div>
</body>
</html>
you can't use required method like that. I think your solution is add dynamically textbox when user clicked the option button like that:
Add this javascript function in your file:
<script language="javascript">
function activateNote()
{
var i = 1;
note_div.innerHTML = "Note: <br> <textarea required id='comment' name='comment' rows='10' cols='70' placeholder='More detail... (Is there a way to recreate the error? What happened?)' ></textarea><br><br>"
}
</script>
Change your elements like that, "delete note textarea" than add div element:
<label>
<input onClick="activateNote()" type="radio" name="category" value="Other">Other
</label>
<div id="note_div"></div>
One possible solution is to conditionally add the required HTML5 attribute to the required field when the "Other" radio button is selected.
You can do this with a javascript method attached to your radio button that is (de/)activated on select.

Ajax with PHP and HTML

<input type="button" value="addkid " onClick="show()" />
<div>
<div id="myTableData" style="display:none; width:800px; height:500px; background-color:yellow; margin:0 auto;">
<form action="javascript:insert()" method="get">
<table>
<tr>
<td width="175">NAME</td>
<td width="245"> Gender</td>
<td width="245">Date of Birth</td>
</tr>
<tr>
<td width="175">
<input type="text" name="kid_name" id="kid_name" />
</td>
<td width="245">FEMALE
<input type="radio" name="gender" value="female" id="gender" />MALE
<input type="radio" name="gender" id="gender" value="male" />
</td>
<td width="245">
<?php for ( $i=1; $i<13; $i++ ) { $month=d ate( 'm', mktime(0,0,0,$i,2,2000)); $sel=( $i==d ate( 'n') ? ' selected="selected"' : ''); $options1[]="<option value=\" {$month}\ " {$sel}>{$month}</option>"; } $options_list1=j oin( "", $options1); echo "<select name=\"month\ " id='month' >{$options_list1}</select>"; for ( $j=1; $j<32; $j++ ) { $theday=d ate( 'd', mktime(0,0,0,0,$j,2000)); $sel=( $j==d ate( 'd') ? ' selected="selected"' : ''); $options2[]="<option value=\" {$theday}\ " {$sel}>{$theday}</option>"; } $options_list2=j oin( "\r\n", $options2); echo "<select name=\"day\ " id='day' >{$options_list2}</select>"; for ( $k=1960; $k<2016; $k++ ) { $theyear=d ate( 'Y', mktime(0,0,0,1,1,$k)); $sel1=( $k==d ate( "Y") ? ' selected="selected"' : ''); $options3[]="<option value=\" {$theyear}\ " {$sel1}>{$theyear}</option>"; } $options_list3=j oin( "\r\n", $options3); echo "<select name=\"year\ " id='year' >{$options_list3}</select>"; ?>
</td>
</tr>
</table>
<input type="submit" name="sub" value="add" />
</form>
</div>
</div>
<script>
function show() {
document.getElementById("myTableData").style.display = "block";
}
function createObject() {
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
//value solve an Internet Explorer cache issue
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('content02').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var kid_name = encodeURI(document.getElementById('kid_name').value);
var gender = encodeURI(document.getElementById('gender').value);
var month = encodeURI(document.getElementById('month').value);
var day = encodeURI(document.getElementById('day').value);
var year = encodeURI(document.getElementById('year').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', '4.php?kid_name=' + kid_name + '&gender=' + gender + '&month=' + month + '& day=' + day + '&year=' + year + '&nocache = ' + nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if (http.readyState == 4) {
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('content02').innerHTML = 'Your contact was successfully added!' + response;
}
}
</script>
4.php
<?php
if(isset($_GET['kid_name']) && isset($_GET['gender']) && isset($_GET['year']) && isset($_GET['day']) && isset($_GET['month']) )
{
echo $newFname = $_GET["kid_name"] ;
echo $newLname = $_GET["gender"] ;
echo $newPhone = $_GET["year"] ;
echo $newEmail = $_GET["day"] ;
echo $newAddress = $_GET["month"] ;
//$insertContact_sql = "INSERT INTO `test`.`contacts` (`newFname`, `newLname`, `newPhone`, `newEmail`, `newAddress`, `group`) VALUES ('{$newFname}' , '{$newLname}' , '{$newPhone}' , '{$newEmail}' , '{$newAddress}' , '{$group}')";
//$insertContact= mysql_query($insertContact_sql) or die(mysql_error());
} else
{
echo 'Error! Please fill all fileds!';
}
?>
I am working with php language. There is a addkid button, which, when the user clicks on the button a pop type window shows the form which has NAME , GENDER AND DOB. In the form action javascript:insert(). I am using ajax for the 1st time so I am not able to understand why it's not working. I guess it should redirect me to 4.php and in 4.php it will echo the values?
I have tested your code and seems it works, I just added a div to show the results there...
You can try to add this div you are not already added it...
<div id="content02">
</div>
Here you write the response, like "Your contact was successfully added"....

PHP file not being called from javascript function

I am trying to call a form and php filefrom a javascript function but it does not work. It might have to do with the cookies, it does not call the "frmSubdeptChainDailyHL" form and it does not call the "subdeptclass_reportHL.php" file, here is the code:
function submitClassChainDaily()
{
var store = readCookie('storeAccess');
var clss = readCookie('classAccess');
var subdept = readCookie('subDeptAccess');
var period = readCookie('period');
if (period == null || period == '') {
period = 'CUR';
}
document.frmClassChainDaily.period.value = period;
var storePref = readCookie('storePref');
if (storePref == null || storePref == '') {
if (store == null || store == '') {
storePref = 'ALL';
} else {
storePref = store;
}
}
if ((storePref.length) > 3 && storePref != 'ALL100') {
document.setStore.submit();
} else {
document.frmClassChainDaily.store.value = storePref;
if (clss == null || clss == '') {
clss = 'ALL';
}
document.frmClassChainDaily.clss.value = clss;
if (subdept == null || subdept == '') {
subdept = 'ALL';
}
document.frmClassChainDaily.subdept.value = subdept;
";
if ($_REQUEST['storePref']=='099')
{
echo "document.frmSubdeptChainDailyHL.submit();";
} else {
echo "document.frmSubdeptChainDaily.submit();";
}
echo "
}
}
Here is the form code:
if ($_REQUEST['storeCode'] == '099') {
echo"
<li>
<!-- SubDept Daily Sales - Chain -->
<form name=\"frmSubdeptChainDailyHL\" action=\"subdeptclass_reportHL.php\">
<input type=hidden value=\"\" name=\"store\">
<input type=hidden value=\"\" name=\"subdept\">
<input type=hidden value=\"\" name=\"clss\">
<input type=hidden value=\"\" name=\"period\">
</form>
<a style=\"display: block; text-decoration: none; color: #000\" href=\"javascript: submitSubDeptChainDaily();\">
<h3 class=\"longfield\">
<img src=\"content/images/icons/US_dollar_icon.png\" alt=\"icon\" class=\"icon\"/>
<span>Sales</span>
</h3>
</a>
</li>
You cant directly call to a php function from javascript. Make use of some ajax calls

Categories