AJAX posted variable behaving unexpectedly - php

So I have an AJAX process that submits a variable from a select option in a HTML form, and then builds another select menu from that. Essentially what is supposed to happen is that, for example, if the user selects the month of Feburary, the variable sent to the PHP script will be '02' and then the new dropdown box will have 29 options. The problem is that, despite my script telling me that 02 has been sent, the days are all out of whack. The days don't seem to correlate to the months, however despite the days being wrong, they're always consistently wrong. For example, while Feburary doesn't print 29 days, it will always consistently print the '30' days option, no matter whether it's 30, or 8000.
Here is my javascript file:
$(document).ready(function() { //Makes sure page is loaded.
/* === LINKS ===
Controls the links (site behaviour) via JQuery (as
defined by the Assignment CRA).
*/
$('#home').html('Home');
$('#signup').html('Sign Up');
$('#activities').html('Upcoming Activities');
$('#feedback').html('Student Feedback');
$('#contact').html('Contact');
/* === STAFF INFORMATION TOGGLE ===
Displays or hides information about
staff members on click.
*/
/*
$('#spongeimage').click(function() {
$("#spongeinfo").slideToggle("slow");
});*/
$(".staff").click(function() {
//alert("ALERT");
$(".staffinfo", this).slideToggle("slow");
});
$('#year').change(function() {
$("#month").slideToggle("slow");
});
$('#month').change(function() {
var month_var = $("#month").val();
var dataString = 'name1='+ month_var;
//Start
$.ajax({
type: "POST",
url: "./javascript/month_post.php",
data: dataString,
dataType: "text",
success: function(data) {
//alert(dataString);
$("#day").html(data);
$("#okay").html(dataString);
}
});
//End
$("#day").slideToggle("slow");
});
/* === 'FIRST NAME' FORM FOCUS
Focuses the cursor on the 'first name'
field when the Student Feedback page
is loaded.
*/
$('input[name="firstname"]').focus();
/* === HOVER EFFECTS ===
The effects that occur after hovering over
an item on the link bar (1.0) and one of
the two buttons on the Student Feedback
page (1.1).
*/
//(1.0)
$("li a").hover(function(){
$(this).css({"color": "#000000", "background-color": "#5590ff"});
}, function(){
$(this).css({"color": "#333", "background-color": "#FFFFFF"});
});
//(1.1)
$("formbutton").hover(function(){
$(this).css({"color": "#000000", "background-color": "#5590ff"});
}, function(){
$(this).css({"color": "#333", "background-color": "#FFFFFF"});
});
});
Here is my PHP file:
<?php
echo $name;
if(isset($_POST["name1"]))
{
$name = $_POST["name1"];
//echo $name;
// Here, you can also perform some database query operations with above values.
//echo "Welcome ". $name ."!"; // Success Message
$counter = 1;
//echo "<select name='gday'>";
if($name == 02)
{
$monthdays = 29;
}
if($name == 06 || $name == 09 || $name == 04 || $name == 11)
{
$monthdays = 30;
}
else
{
$monthdays = 31;
}
while ($counter <= $monthdays)
{
echo "<option value='hi'>".$counter."</option>";
$counter++;
}
//echo "</select>";
}
?>
And here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<title>KIT411 - Homepage</title>
<link rel="stylesheet" href="./CSS/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./javascript/script.js"></script>
</head>
<body>
<!-- TITLES -->
<div class="titles">
‌ <!-- Blank character, to ensure the titles div extends to the top of the page. -->
<h1 class="title">KIT411</h1> <!-- Unit name. -->
<h2 class="subtitle">Sign Up</h2> <!-- Page name. -->
</div>
<div class="right">
<?php
include('login.php');
?>
</div>
<!-- PAGE LINKS
Links are controlled by JQuery, which is why
there are no <a></a> tags. -->
<?php
include('PHP/linkbar.php');
?>
<div class="center">
<div class="inline">
<?php
include('./db-connection/register.php');
?>
<div id="okay">TEST </div>
<form method="post" action="">
Username:<br>
<input type="text" name="usr" value="<?php echo $user; ?>"><br>
Password:<br>
<input type="password" name="pass" value="<?php echo $password; ?>"><br>
Retype Password:<br>
<input type="password" name="pass2" value="<?php echo $passwordTwo; ?>"><br>
Name:<br>
<input type="text" name="name" value="<?php echo $name; ?>"><br>
DOB:<br>
<select id="day" name="dobDay">
<?php
$counter = 1;
while($counter <= 31)
{
?>
<option value="<?php echo $counter; ?>"><?php echo $counter; ?></option>
<?php
$counter++;
}
?>
</select>
<select id="month" name="dobMonth">
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="year" name="dobYear">
<?php
$counter = 1100;
while($counter <= 2016)
{
?>
<option class="yearClass" value="<?php echo $counter; ?>"><?php echo $counter; ?></option>
<?php
$counter++;
}
?>
</select>
<br>
Email:<br>
<input type="text" name="email" value="<?php echo $email; ?>"><br>
<input type="submit" name="submit" value="Sign Up">
</form>
</div>
</div>
<?php
include('PHP/footer.php');
?>
</body>
</html>
Any help would be greatly appreciated, and sorry if there's any swearwords in my code. Sometimes I do it for a bit of fun while testing and forget to remove them. Anyway, any help is progress.

The problem is in the PHP code, when you try to set up the number of days. You have one if and one if ... else, but doesn't behave as you expect.
You have first this if
if($name == 02)
{
$monthdays = 29;
}
And after this one:
if($name == 06 || $name == 09 || $name == 04 || $name == 11)
{
$monthdays = 30;
}
else
{
$monthdays = 31;
}
This last one will set up the number of days to 30 or 31, because it only have two choices. Here you could use an elseif control structure. http://php.net/manual/en/control-structures.elseif.php
if ($name == 02)
{
$monthdays = 29;
}
else if ($name == 06 || $name == 09 || $name == 04 || $name == 11)
{
$monthdays = 30;
}
else
{
$monthdays = 31;
}

Related

Focus on HTML Select dropdown option after GET request

So I am making a programme and I am submitting a form to itself. This programme is a very basic calculator as I am new to HTML and PHP. I am trying to make it so that when you submit the form, the Select dropdown will remain on the most recently used operator.
For example, if I make the calculator do '5 + 5', then I want the submitted form to keep the operator dropdown on '+'.
Here is my code:
<?php
// grab the form values from $_HTTP_GET_VARS hash extract($_GET);
// first compute the output, but only if data has been input if(isset($calc) && $operator == "multiply") { // $calc exists as a variable
$prod = $x * $y; } elseif (isset($calc) && $operator == "plus") {
$operator = $plus;
$prod = $x + $y; } elseif (isset($calc) && $operator == "minus") {
$operator = "minus";
$prod = $x - $y; } elseif (isset($calc) && $operator == "divide") {
$sign = "/";
$prod = $x / $y; } else { // set defaults
$x=0;
$y=0;
$prod=0; } ?>
<html> <head>
<title>PHP Calculator Example</title> </head>
<body>
<h3>PHP Calculator (Version 1)</h3>
<p>Multiply two numbers and output the result</p>
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
<label for="x">x = </label>
<input type="text" name="x" id="x" size="5" value="<?php print $x; ?>"/>
<select name="operator" id="operator">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">*</option>
</select>
<label for="y">y = </label>
<input type="text" name="y" id="y" size="5" value="<?php print $y; ?>"/>
<input type="submit" name="calc" value="Calculate"/>
</form>
<!-- print the result -->
<?php if(isset($calc)) {
print "<p>x $sign y = $prod</p>";
} ?>
</body> </html>
In order to remain on option selected in the select element
The option has to have an attribute "selected"
<select name="operator" id="operator">
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "plus"){echo "selected";} ?> value="plus">+</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "minus"){echo "selected";} ?> value="minus">-</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "divide"){echo "selected";} ?> value="divide">/</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "multiply"){echo "selected";} ?> value="multiply">*</option>
</select>
Hope that it will help you.
A possible solution employing javascript would be this
<?php
if(isset($_GET['operator'])) {
?>
<script>document.getElementById("operator").value = '<?=$_GET['operator']?>';</script>
<?php
}
?>

Insert boolean + results to mysqlDB

Writing a section of a long form to add data to MySQL database and in this form
a boolean checkbox that allows a section to show or hide and I need to insert this boolean to database with the other data
Later I need to get this data from database and show it in front end....
So it will say
Yes (section is true and showing) + the rest of data in the section
My problem is in boolean checkbox to insert it as "YES allowed" to retrieve it later and say "Yes it's Allowed + data" .. I know it's easy but I'm at point of complete confusion
<label>Pets Allowed:</label>
<input class="form-pine" type="checkbox" name="pets" id="petscheck" value="<?php if(isset($result->dogs_permit)){ echo $result->dogs_permit; } ?>" onchange="valueChanged()"><br>
<script type="text/javascript">
function valueChanged() {
if (document.getElementById('petscheck').checked) {
document.getElementById("petsshowhide").style.display = 'block';
} else {
document.getElementById("petsshowhide").style.display = 'none';
}
}
</script>
<div class="col-pine-2" id="petsshowhide" style="display:none;">
<label>Pets fees:</label>
<select class="form-pine" name="dogs-fees">
<option value="">Select Option</option>
<option value="Inclusive"<?php if(isset($result->dogs_fees) && $result->dogs_fees == '0'){ echo 'selected'; } ?>>Inclusive</option>
<option value="Additional Charge"<?php if(isset($result->dogs_fees) && $result->dogs_fees == '1'){ echo 'selected'; } ?>>Additional Charge</option>
</select>
<label>pets Fees:</label>
<input class="form-pine" type="number" name="pets-price" value="<?php if(isset($result->dogs_price)){ echo $result->dogs_price; } ?>">
<label>currency:</label>
<select class="form-pine" name="dogs-curr">
<option value="">Select currency</option>
<option value="USD"<?php if(isset($result->dogs_curr) && $result->dogs_curr == 'USD'){ echo 'selected'; } ?>>USD</option>
<option value="EUR"<?php if(isset($result->dogs_curr) && $result->dogs_curr == 'EUR'){ echo 'selected'; } ?>>EUR</option>
</select>
</div>
function add
if(isset($_POST['submitpineapple'])){
global $wpdb;
$table_pine = $wpdb->prefix . 'ppf_admin';
$dogs_permit = $_POST['pets'];
$dogs_fees = $_POST['dogs-fees'];
$dogs_price = $_POST['pets-price'];
$dogs_curr = $_POST['dogs-curr'];
if(isset($_POST['adds_pineapple'])){
$pid = $_POST['adds_pineapple'];
$sql = "INSERT INTO $table_pine (dogs_permit, dogs_fees, dogs_price, dogs_curr) VALUES ($dogs_permit, '$dogs_fees', $dogs_price, '$dogs_curr')";
if($wpdb->query($sql)){
echo'<div class="success-msg">Save Successfully</div>';
}else{
echo'<div class="errorcss">Something went wrong!</div>';
}
You can store pets as 1 if it is selected or 0 if it is not selected in the table. Or in a parent table.
You will have $_POST['pets'] available when it is selected. You can check for this with isset($_POST['pets']) and get 1 or 0 with $dogs_permit=isset($_POST['pets'])? 1 : 0;

check validation between to dates and time

I have this if statement
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(document).on('submit', '#rentform', function () {
var data = $(this).serialize()
$.ajax({
type: 'POST',
url: 'newrent.php',
data: data,
success:(
function (data){$(".result").html(data)}
)
});
return false;
});
} )
$(document).ready(function () {
$('#rent').change(function(){
var x =($('#rent option:selected').data('sireal'))
$('#itemsn').val(x);
});
} )
</script>
<form method="post" id="rentform" action="" novalidate="novalidate">
<label for="item">REnter Name</label>
<select name="rnt_name" id="name_rent">
<option selected disabled>SELECT Renter Name</option>
<?php foreach ($nameq as $res) : ?>
<option value="<?= $res['user_name']?>"><?= $res['user_name'] ?></option>
<?php endforeach; ?>
</select>
<br/>
<br/>
<label for="item">Cameras</label>
<select name="item" id="rent">
<option selected disabled>SELECT ITEM</option>
<?php foreach ($rentq as $row) : ?>
<option value="<?= $row['item_brand']?>" data-sireal="<?= $row['s_n'] ?>"><?= $row['item_brand'] ?></option>
<?php endforeach; ?>
</select><br/>
<br/>
<input type="hidden" name="sn" id="itemsn" value="">
<label name="from_date">RENT FROM</label>
<input type="date" name="from_date"><br/>
<label name="from_hour">RENT FROM Hour</label>
<input type="time" name="from_hour"><br/>
<label name="to_date">RENT TO</label>
<input type="date" name="to_date"><br/>
<label name="to_hour">RENT FROM Hour</label>
<input type="time" name="to_hour"><br/>
<input type="submit" name="submit" value="Send Rent">
</form>
<div class="result">
</div>
if($_POST){
$name = $_POST['rnt_name'];
$item = $_POST['item'];
$fdate = $_POST['from_date'];
$fhour = $_POST['from_hour'];
$tdate = $_POST['to_date'];
$thour = $_POST['to_hour'];
$sn = $_POST['sn'];
$csheck = "SELECT * FROM rent";
$ckq = mysqli_query($link,$csheck);
foreach ($ckq as $res) {}
$count = "SELECT item_brand = '$item',s_n = '$sn',COUNT(*)
FROM item
WHERE status = 1 AND item_brand = '$item' AND s_n = '$sn'";
$cnt = mysqli_query($link,$count);
foreach ($cnt as $itm);
$itmq = "SELECT rent_item = '$item',COUNT(*)
FROM rent ";
$itemres = mysqli_query($link,$itmq);
foreach ($itemres as $missitm){};
if(($fdate >= $res['rent_from_d'] && $res['rent_to_d'] >= $tdate && $missitm['COUNT(*)'] >= $itm['COUNT(*)'] ) || ($fdate > $res['rent_from_d'] && $res['rent_to_d'] > $tdate && $fdate > $res['rent_from_d'] || $fdate <= $res['rent_to_d'] && $fhour <= $res['rent_to_t'] && $missitm['COUNT(*)'] >= $itm['COUNT(*)'] ) ) {
echo 'no good Item Rented To '.$res['renter'] ;
}else{
$newrent = "INSERT INTO rent (renter,rent_item,rent_from_d,rent_from_t,rent_to_d,rent_to_t)
VALUES ('$name','$item','$fdate','$fhour','$tdate','$thour')";
mysqli_query($link,$newrent);
echo 'pass';
}
this is what I get in my database after form submit
rent_id renter rent_item sn rent_from_d rent_from_t rent_to_d rent_to_t
115 dror x70 1234 2018-11-29 10:00 2018-11-29 14:00
What I am trying to do is create a rent system. My problem is how to validate if items are selected between two dates and time. Every time new rent is created, the status of the specific item that has been chosen set to 0, so that the system will no longer available.
Thanks in advance.

How to edit files from database?

i have made a register form that keeps all of the created users in the database. Now, i want to put button (link, whatever) next to each of the created user, and when i click on the button, new login form to be shown, after i fill all of the required fields and press on update button, the edited user to be shown in database. Any help? Thanks in advance.
Code:
register form:
<?php
$errors = [];
$missing = [];
?>
<html>
<head>
<meta charset="utf-8">
<title>Facebook login</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php if(isset($_POST['send']) && count($missing) == 0){
echo "Thank you for register on our site! You profile details are listed bellow:";
?>
<p>Your name: <?php echo $_POST['name']; ?></p>
<p>Lastname name: <?php echo $_POST['lastName']; ?></p>
<?php
}else{
?>
<h1>Registration</h1>
<form method="post" action="register_user.php">
<?php if ($errors || $missing) : ?>
<p class="warning"> Please fill all of the empty items
</p>
<?php endif; ?>
<p>
<label for="username">Username
<?php
if ($missing && in_array('username', $missing)) : ?>
<span class="warning"> Please enter your first name</span>
<?php endif; ?>
</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="password">Enter your password
<?php
if ($missing && in_array('password', $missing)) : ?>
<span class="warning"> Please enter your password</span>
<?php endif; ?>
</label>
<input type="password" name="password" id="password">
<p>
<label for="re-password">Re-Enter your password
<?php
if ($missing && in_array('re-password', $missing)) : ?>
<span class="warning"> Please re-enter your password</span>
<?php endif; ?>
</label>
<input type="re-password" name="re-password" id="re-password">
</p>
<p>
<label for="name">First Name
<?php
if ($missing && in_array('name', $missing)) : ?>
<span class="warning"> Please enter your first name</span>
<?php endif; ?>
</label>
<input type="text" name="name" id="firstName">
</p>
<p>
<label for="lastName">Last Name
<?php
if ($missing && in_array('lastName', $missing)) : ?>
<span class="warning"> Please enter your last name</span>
<?php endif; ?>
</label>
<input type="name" name="lastName" id="lastName">
</p>
<p>
<label for="email">Enter your email adress
<?php
if ($missing && in_array('email', $missing)) : ?>
<span class="warning"> Please enter your email adress</span>
<?php endif; ?>
</label>
<input type="email" name="email" id="email">
</p>
<h3>Birthday</h3>
<p>
<label for="Select Month"> Select Month
<?php
if ($missing && in_array('month', $missing)) : ?>
<span class="warning"> Please select month</span>
<?php endif; ?>
</label>
<select name="month" id="month" >
<option value="Month"> Month </option>
<option value="Jan"> January </option>
<option value="Feb"> February </option>
<option value="Mar"> March </option>
<option value="Apr"> April </option>
<option value="May"> May </option>
<option value="June"> June </option>
<option value="July"> July </option>
<option value="Aug"> August </option>
<option value="September"> September </option>
<option value="Oct"> October </option>
<option value="Nov"> November </option>
<option value="Dec"> December </option>
</select>
</p>
<p>
<label for="Select Day"> Select Day
<?php
if ($missing && in_array('day', $missing)) : ?>
<span class="warning"> Please select Day</span>
<?php endif; ?>
</label>
<select name="day" id="day" >
<option value="Day"> Day </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>
<option value="13"> 13 </option>
<option value="14"> 14 </option>
<option value="15"> 15 </option>
<option value="16"> 16 </option>
<option value="17"> 17 </option>
<option value="18"> 18 </option>
<option value="19"> 19 </option>
<option value="20"> 20 </option>
<option value="21"> 21 </option>
<option value="22"> 22 </option>
<option value="23"> 23 </option>
<option value="24"> 24 </option>
<option value="25"> 25 </option>
<option value="26"> 26 </option>
<option value="27"> 27 </option>
<option value="27"> 27 </option>
<option value="28"> 28 </option>
<option value="29"> 29 </option>
<option value="30"> 30 </option>
<option value="31"> 31 </option>
</select>
</p>
<p>
<label for="Select Year"> Select Year
<?php
if ($missing && in_array('year', $missing)) : ?>
<span class="warning"> Please select year</span>
<?php endif; ?>
</label>
<select name="year" id="year" >
<option value="Year"> Year </option>
<option value="1990"> 1990 </option>
<option value="1991"> 1991 </option>
<option value="1992"> 1992 </option>
<option value="1993"> 1993 </option>
<option value="1994"> 1994 </option>
<option value="1995"> 1995 </option>
</select>
</p>
<p>
<label for="Select gender"> Select gender
<?php
if ($missing && in_array('Select gender', $missing)) : ?>
<span class="warning"> Please select your gender</span>
<?php endif; ?>
</label>
<input type="radio" name="gender" id="malegender">
<label for="gender" > Male</label>
<input type="radio" name="gender" id="femalegender">
<label for="gender"> Female</label>
</p>
<input type="submit" name="send" id="send" value="send">
</form>
<?php } ?>
</body>
</html>
Code for the registered user:
Register user:
<?php
$errors = [];
$missing = [];
if($_SERVER['REQUEST_METHOD'] == "POST"){
$username = $_POST["username"];
$password = $_POST["password"];
$firstname = $_POST["name"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
$month = $_POST["month"];
$day = $_POST["day"];
$year = $_POST["year"];
$gender = $_POST["gender"];
if (!isset($_POST['username']) || strlen($_POST['username']) < 3) {
$missing[] = "username";
}else{
}
if (!isset($_POST['name']) || strlen($_POST['name']) < 3) {
$missing[] = "name";
}else{
}
if (!isset($_POST['lastName'])|| strlen($_POST['lastName']) < 3) {
$missing[] = "lastName";
}
if (!isset($_POST['email']) || strlen($_POST['email']) < 3 ) {
$missing[] = "email";
}
if (!isset($_POST['re-password']) || strlen($_POST['re-password']) < 3 ) {
$missing[] = "re-password";
}
if (!isset($_POST['password']) || strlen($_POST['password']) < 3 ) {
$missing[] = "password";
}
if (!isset($_POST['month']) || $_POST['month'] == "Month" ) {
$missing[] = "month";
}
if (!isset($_POST['year']) || $_POST['year'] == "Year" ) {
$missing[] = "year";
}
if (!isset($_POST['day']) || $_POST['day'] == "Day") {
$missing[] = "day";
}
if (!isset($_POST['gender'])) {
$missing[] = "Select gender";
}
if(count($missing) > 0){
echo "validation error!!!";
}else{
$dsn = "mysql:host=";
$host = "localhost";
$db = "registration";
$dsn .= $host.";";
$dsn .= "dbname=".$db;
$user = 'root';
$dbh = new PDO($dsn, $user);
$selectQuery = "SELECT * FROM register_table WHERE username = :username OR email_adress = :email";
$stmt = $dbh->prepare($selectQuery);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0){
echo "User exists!!!";
}else{
$stmtInsert = $dbh->prepare("INSERT INTO register_table (username, password, first_name, last_name, email_adress, month, day, year, gender) VALUES (:username, :password, :name, :lastName, :email, :month, :day, :year, :gender)");
$stmtInsert->bindParam(':username', $username);
$stmtInsert->bindParam(':password', $password);
$stmtInsert->bindParam(':name', $firstname);
$stmtInsert->bindParam(':lastName', $lastName);
$stmtInsert->bindParam(':email', $email);
$stmtInsert->bindParam(':month', $month);
$stmtInsert->bindParam(':day', $day);
$stmtInsert->bindParam(':year', $year);
$stmtInsert->bindParam(':gender', $gender);
$stmtInsert->execute();
$arr = $stmtInsert->errorInfo();
print_r($arr);
echo "New records created successfully!!!";
}
$editQuery = "SELECT username FROM register_table";
$editResult = mysql_query($editQuery);
while($user = mysql_fetch_array($editQuery))
$dbh = null;
}
}
This is code I use on my database 2 sets of code - view.php displays the records with an option to edit next to each record in the list then if you click on edit it opens edit.php displaying a form to change and save the details. If you need it I can send the table structure and contents as well. There is quite a lot of code but I want to give the whole picture of a working system that I think does exactly what you want. It is mysql but I am converting to mysqli
view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM stats")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>date</th> <th>Home Team</th> <th></th><th></th><th>Away Team</th> <th></th> <th></th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['hometeam'] . '</td>';
echo '<td>' . $row['fthg'] . '</td>';
echo '<td>' . $row['ftag'] . '</td>';
echo '<td>' . $row['awayteam'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
edit.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $hometeam, $awayteam, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="hometeam" value="<?php echo $hometeam; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="awayteam" value="<?php echo $awayteam; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$hometeam = mysql_real_escape_string(htmlspecialchars($_POST['hometeam']));
$awayteam = mysql_real_escape_string(htmlspecialchars($_POST['awayteam']));
// check that hometeam/awayteam fields are both filled in
if ($hometeam == '' || $awayteam == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $hometeam, $awayteam, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE stats SET hometeam='$hometeam', awayteam='$awayteam' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM stats WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$hometeam = $row['hometeam'];
$awayteam = $row['awayteam'];
// show form
renderForm($id, $hometeam, $awayteam, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
</body>
</html>

Bowling score calculator PHP form submit via AJAX

I have been building a bowling score calculator.
The calculator itself works but you must enter all scores in the form at once and then it will calculate the total score.
I wanted it to loop form the form to enter your score for each frame, submit the form show the current score and reload the form again for the next frame.
This is the first time I have used ajax and followed a tutorial on how to submit a form via ajax but it does not seem to be working.
The two scripts are below.
PHP Script:
<?php
session_start();
//start a new game
if (isset($_GET["endGame"]) && $_GET["endGame"] == 'yes') {
session_destroy();
//redirect to homepage and remove any get parameters
$location="http://localhost/bbc/v8.php";
echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">';
}
//Check if the number of players has been set
if (isset($_POST['next'])) {
//Determine thye number players
foreach ($_POST['numberOfPlayers'] as $player) {
$_SESSION['numberOfPlayers'] = $player;
$location="http://localhost/bbc/v8.php";
echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">';
}
//check number of players has been set before enter player names
} elseif (isset($_SESSION['numberOfPlayers'])) {
$numberOfPlayers = $_SESSION['numberOfPlayers'];
if (!isset($_POST['playerSubmit']) || (isset($_POST['scores']))) {
?>
<!-- Form to enter the playes names -->
<form method="post" action="">
<fieldset>
<?php
$x = 1;
echo '<div class="custTitle"><h3>Enter player names below</h3></div>';
while ($x <= $numberOfPlayers) {
echo '<input class="form-control" type="text" name="players[]" placeholder="Player ' . $x . '">';
$x++;
}
?>
</fieldset>
<input type="submit" name="playerSubmit" value="Start Game">
</form>
<?php
}// close if
}
if (isset($_POST['playerSubmit'])) {
$players = array();
foreach ($_POST['players'] as $player) {
$players[] = $player;
}
// save player names array to session for reuse
$_SESSION['players'] = $players;
}
//Check player name have been submitted
if(isset($_POST['playerSubmit']) || isset($_SESSION['players'])) {
//create global variable of players array
$players = $_SESSION['players'];
$_SESSION['frameScore'] = array(0);
$frameCount = 1;
while ($frameCount <=9 ) {
?>
<!-- Form to enter players score-->
<form method="post" action="" class="ajax">
<?php
$i = 0;
while($i < $_SESSION['numberOfPlayers']){
echo '<fieldset>';
echo '<h3>' . $players[$i] . '</h3>';
$x=1;
// loop the form 21 times for maximum of 21 throws
while($x <= 3){
?>
<label>Throw, <?php echo $x; ?></label>
<select class="form-control" name="score[<?php echo $i; ?>][<?php echo $x; ?>]">
<option value="0">0</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">X</option>
</select>
<?php
$x++;
}// close 21 throws while
?>
<input type="hidden" name="player[<?php echo $i; ?>]" value="<?php echo $players[$i] ?>">
</fieldset>
<?php
$i++;
}// close while for looping throuhg players
?>
<input type="submit" value="Finish Game" name="scores"/>
</form>
<?php
// close player submit if
// check if any scores have been submitted
if(isset($_POST['score'])) {
$i = 0;
$result = [];
foreach($_SESSION['players'] as $name) {
$result[$name] = $_POST['score'][$i];
$pins = $_POST['score'][$i];
$game = calculateScore($i, $pins);
$i++;
}
}
$frameCount++;
}// close do while
// if number of players is not yet set the show the form to select number of players
} else {
?>
<!-- Form to select the number players -->
<h2>How many players will be bowling?</h2>
<form method="post" action="">
<select class="form-control" name="numberOfPlayers[]">
<option name="numberOfPlayers[]" value="1">1</option>
<option name="numberOfPlayers[]" value="2">2</option>
<option name="numberOfPlayers[]" value="3">3</option>
<option name="numberOfPlayers[]" value="4">4</option>
<option name="numberOfPlayers[]" value="5">5</option>
<option name="numberOfPlayers[]" value="6">6</option>
</select>
<input type="submit" name="next" value="Next">
</form>
<?php
}// close else
// if the number of players has been set show a 'New Game' button
if (isset($_SESSION['numberOfPlayers'])) {
echo '<button class="btn_lrg"><span>New Game</span></button>';
}
// function to calculate the players scores
function calculateScore($player, $pins) {
global $players;
$frame = 0;
// create an array for the frame score
//$frameScore = $_SESSION['frameScore'];
//$frameScore = array(0);
//loop for 10 frames of a game
while ($frame <=9) {
$_SESSION['frameScore'][$frame] = array_shift($pins);
//Check for a strike
if($_SESSION['frameScore'][$frame] == 10) {
$_SESSION['frameScore'][$frame] = (10 + $pins[0] + $pins[1]);
// No strike, so take in two throws
} else {
$_SESSION['frameScore'][$frame] = $_SESSION['frameScore'][$frame] + array_shift($pins);
//Check for a spare
if($_SESSION['frameScore'][$frame] == 10) {
$_SESSION['frameScore'][$frame] = (10 + $pins[0]);
}
}// close if
//Move to the next frame and loop again
$frame++;
}// close while
//echo out player scoreborad
echo '<h3>' .$_SESSION["players"][$player]. '</h3>' . '<h4>' . array_sum($_SESSION['frameScore']) . '</h4>';
}// end calculateScore function
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<!-- End Bowling Calculator Script -->
Javascript/Ajax:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
});
return false;
});

Categories