script dosen't execute ajax call - php

I'm sending ajax request to the file, but for some reason the file doesn't complete operation, I know that request reaches the file, because it echoes request received, and it stops there. I can't figure out why.
<?php
/**
* Created by PhpStorm.
* Date: 23.2.2015.
* Time: 5:20
* Version 1.1
*/
$nacin_rada = 'echo';//promjenjivo u session
$mysqli = mysqli_connect('localhost', 'root', 'password', 'database');
$year = date("Y");
echo 'request received';
if (isset($_POST['submit'])) { //get_magic_quotes_gpc removed in php 5.4.0
$username = stripslashes($_POST['username']);
$password = stripslashes(md5($_POST['password']));
$passverif = stripslashes(md5($_POST['passverif']));
$email = stripslashes($_POST['email']);
$ime = stripslashes($_POST['ime']);
$prezime = stripslashes($_POST['prezime']);
$dan = stripslashes($_POST['dan']);
$mjesec = stripslashes(intval($_POST['mjesec']));
$godina = stripslashes(intval($_POST['godina']));
$avatar_source = stripslashes($_POST['avatar']);
$sex = stripslashes($_POST['sex']);
if ($sex == 'žensko' and $avatar_source == '') {
$avatar_source = 'default_profile_female.jpeg'; //potrebno dodati podršku za default sliku
} elseif ($sex == 'muško' and $avatar_source == '') {
$avatar_source = 'default_profile_male.jpeg'; //potrebno dodati podršku za default sliku
}
if ($username == '' or $password == '' or $passverif == '' or $email == '' or $ime == '' or $prezime == '' or $dan == '' or $mjesec == '' or $godina == '' or $avatar_source == '') {
echo ' You didn\'t fill out all the forms';
exit;
}
if ($password <= 2) {
echo 'Password too short';
exit;
}
if ($passverif <= 2) {
echo 'Password verification too short';
exit;
}
if ($password != $passverif) {
echo 'Vaše lozinke se ne podudaraju';
exit;
}
if ($mjesec > '12' or $mjesec < '1') {
echo $mjesec . 'nije valjani izbor';
exit;
}
if ($godina > $year) { //year defined at line 12
echo 'Vi ste iz budučnosti?';
exit;
}
if ($godina == '0000') {
echo '0000 nije valjani izbor';
exit;
}
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE email='$email'") or die("Query Failed");// redefining sql query for user data selection
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if ($num_row >= 1) {
echo '<span style="color:white;">U bazi podataka več postoji račun s tim Emailom</span>';
} elseif ($num_row == 0) {
$insert_users = mysqli_query($mysqli, "INSERT INTO users(username, password, email, ime, prezime,sex, avatar, dan, mjesec, godina) VALUES ('$username','$password','$email','$ime','$prezime','$sex','$avatar_source','$dan','$mjesec','$godina')");
$insert_user_data = mysqli_query($mysqli, "INSERT INTO user_data(hometown, love_status, about) VALUES ('NULL','NULL','NULL' )");
echo 'Registracija uspješna,možete se prijaviti';
} else echo 'Registracija neuspjela';
}
?>

You had several errors:
In your AJAX call use this way to send the parameters, like bloodyKnuckles pointed out:
data: { username: username, password: password, passverif: passverif, email: email ... }
Also, $_POST['submit'] isn't defined. Instead, try using $_POST['username'] or something else from your parameters.

JQuery ajax method, data parameter takes, among other things, an object, such as:
data: { username: username, password: password, passverif: passverif, email: email ... }
You're passing:
data: "{username,password,passwordverif,email...}"
A couple things that don't work there: 1) not key: value pairs, and 2) that's a string, not an object.
Another problem, these:
var username = $('.username').val;
...need to be changed to:
var username = $('.username').val();
Notice the parenthesis at the end.
So you have 3 things to fix. Two in your JavaScript, and one in your PHP file.
JavaScript:
Use object notation in data setting.
Don't quote that object.
PHP:
Use something other than $_POST['submit'] to check for form data on your server script.

<html>
<style>
body{
outline: none;
background-color:#222222;
}
select{
background-color: #FFFFFF;
border: 0 solid transparent;
width: 100px;
}
table{
margin-left: 850px;
border: 1px solid blue;
border-radius: 5px;
background:#EAEAEC;
margin-top:0;
}
input{width:372px;height:34px;}
.submit{background-color:white;border:0 transparent}
.mjesec{position:absolute;margin-left:200px;}
.dan{margin-left:40px;position:absolute;margin-top:-25px;}
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function Registracija_ajax() {
var username = $('.username').val;
var password = $('.password').val;
var passverif = $('passverif').val;
var email = $('.email').val;
var ime = $('.ime').val;
var prezime = $('.prezime').val;
var dan = $('.dan').val;
var mjesec = $('.mjesec').val;
var godina = $('.godina').val;
var avatar_source = $('.avatar_source').val;
var sex = $('.sex').val;
$.ajax({
type: "POST",
url: "registration.php",
data: "{username,password,passverif,email,ime,prezime,dan,mjesec,godina,avatar_source,sex}",
beforeSend: function () {
$('.loading_gif').css('display:inline');
},
success: function (response) {
$('.response').html(response);
}
});
}
</script>
<body>
<table cellspacing="21">
<tr>
<td>
<input name="username" required="ddd" placeholder="username" class="username">
</td>
</tr>
<tr>
<td>
<input name="password" type="password" required placeholder="password" class="password">
</td>
</tr>
<tr>
<td>
<input name="passverif" type="password" required placeholder="password" class="passverif">
</td>
</tr>
<tr>
<td>
<input name="email" placeholder="email" required class="email">
</td>
</tr>
<tr>
<td>
<input name="ime" placeholder="ime" required class="ime">
</td>
</tr>
<tr>
<td>
<input name="prezime" placeholder="prezime" required class="prezime">
</td>
</tr>
<tr>
<td>
<select name="sex" class="sex" style="margin-left:40px;position:absolute;">
<option value="male">Muško</option>
<option value="female">Žensko</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="godina" class="godina" style="margin-left:200px;position:absolute;margin-top:-23px;">
<option value="0000">Godina</option>
<?php
$beggining_year = date('Y') - 13;
$end_year = '1975';
while ($end_year <= $beggining_year) {
echo '<option value="' . $beggining_year . '">' . $beggining_year . '</option>';
$beggining_year--;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select class="mjesec" name="mjesec">
<option value="0000">Mjesec</option>
<?php
$beggining_month = '1';
$end_month = '12';
while ($beggining_month <= $end_month) {
echo '<option value="' . $end_month . '">' . $end_month . '</option>';
$end_month--;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select class="dan" name="dan">
<option value="0000">Dan:</option>
<?php
$beggining_day = '1';
$end_day = '31';
while ($beggining_day <= $end_day) {
echo '<option value="' . $end_day . '">' . $end_day . '</option>';
$end_day--;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<input class="avatar" name="avatar" placeholder="Profile photo(link only)">
</td>
</tr>
<tr>
<td>
<button value="submit" class="submit" onclick="Registracija_ajax()" name="submit">Registracija</button>
</td>
</tr>
</table>
</body>
<div class="response"></div>
#Philip Sorokin ,you have the other file above.

Related

PHP / AJAX: Delete unsuccessful at AJAX

Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:
1) dashboard.php will display 3 select option which is team, time from and time to
2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).
3) All data row will be listed and each data have a delete button. User can delete data based on data row.
My problem is, the data is not deleted.
Below is my current code.
dashboard.php
<select class="form-control" name="team" id="team">
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
<td width="1%"></td>
</td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
</tr>
</table><br>
<div id = "dashboard">
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
$('#range').click(function(){
var from = $('#from').val();
var to = $('#to').val();
var team = $('#team').val();
if(from != '' && to != '' && team != '')
{
$.ajax({
url:"range.php",
method:"POST",
data:{from:from, to:to, team:team},
success:function(data)
{
$('#dashboard').html(data);
}
});
}
else
{
alert("Please select both team and date range");
}
});
if($('#from').val() && $('#to').val() && $('#team').val()){
$('#range').click();
}
});
</script>
range.php (AJAX)
<?php
require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";
$email = $_SESSION['login_user'];
if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0)
{
echo'
<form method="post" action="">
<div class="row" style="height: 300px; overflow-y: scroll;">
<div class="col-lg-12 grid-margin stretch-card">
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th>id</th>
<th>Date</th>
<th>Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td align="center">';
echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $report_id .'" data-toggle="tooltip">View</a></td>';
echo '<td align="center">';
echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
delete_ajax.php
<?php
require_once '../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");
?>
Can anyone knows what is the problem? The data cannot deleted!. Help anyone
maybe this is because in the range.php file you have 2 form tags
first is outside while function
<form method="post" action="">
and second one is in while function
<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">
try removing the first one

jQuery generated elements not recognized on $_POST

I'm developing a Wordpress plugin using PHP and jQuery, the function below is called when the <select> input is changed, so far it works as intended and the inputs are generated properly but when I submit the form, the generated elements are undefined when called in $_POST.
<?php
function random_event() {
global $wpdb;
//Table for all the event details
$tablename = $wpdb->prefix."random_event";
// Table to store all banner stores
$tablename2 = $wpdb->prefix."random_event_banner_stores";
//Table for store all poster
$tablename4 = $wpdb->prefix."random_event_poster";
// Table storing all user registrations
$tablename3 = $wpdb->prefix."random_event_winners";
//Junction table to map the poster to banner store
$tablename5 = $wpdb->prefix."random_event_poster_banner";
//Junction table to map the poster to event
$tablename6 = $wpdb->prefix."random_event_poster_event";
$tablename5 = $wpdb->prefix."random_event_poster_banner";
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
$update_this_event = -1;
$banner_stores = [];
//Deletion
if(isset($_POST['delete_event'])) {
$event_id = esc_sql($_POST['event_id']);
$sql = "DELETE from $tablename WHERE id= '" . $event_id . "'";
try{
$event = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
$banner_store_id = esc_sql($_POST['banner_id']);
$name = esc_sql($_POST['banner_store_name']);
$description = esc_sql($_POST['banner_store_description']);
$location_note = esc_sql($_POST['banner_store_location_note']);
$address = esc_sql($_POST['banner_store_address']);
$status = esc_sql($_POST['banner_store_status']);
$sql = "UPDATE $tablename SET name = '" . $name . "'
, description = '" . $description . "'
, location_note = '" . $location_note . "'
, address = '" . $address . "'
, status = '" . $status . "' WHERE id = '" . $banner_store_id . "'";
try{
$participants = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['select_update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
// $pssql = "select * from $tablename2";
// $banner_stores = $wpdb->get_results($pssql);
$pssql = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.store_id is null";
// $pssql = "select * from $tablename2";
$banner_stores = $wpdb->get_results($pssql);
$pssql2 = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.id = '".$update_this_event."'";
$current_banner_store = $wpdb->get_results($pssql2);
if(count($current_banner_store) != 0) {
array_push($banner_stores, $current_banner_store[0]);
}
$poster_sql = "select ap.*, a.name as poster_name, ap.qty as qty from $tablename6 as ap inner join $tablename4 as a on a.id = ap.poster_id where ap.event_id = $update_this_event";
$poster_event = $wpdb->get_results($poster_sql);
$poster_petone = [];
foreach($results as $result) {
if($result->id == $update_this_event) {
$poster_sql = "select a.* from $tablename5 as ap inner join $tablename4 as a on a.id = ap.poster_id where banner_store_id = ".$result->store_id;
$poster_petone = $wpdb->get_results($poster_sql);
}
}
}else if(isset($_POST['cancel_update_event'])){
$update_this_event = -1;
}else if (isset($_POST['save_update_event'])) {
$update_this_event = intval(esc_sql($_POST['event_id']));
$title = esc_sql($_POST['title']);
$qty = 0;
$description = esc_sql($_POST['description']);
$prize = esc_sql($_POST['prize']);
$event_code = esc_sql($_POST['event_code']);
$event_from = esc_sql($_POST['event_from']);
$event_to = esc_sql($_POST['event_to']);
$banner_store_id = esc_sql($_POST['banner_store_id']);
if(isset($_POST['poster_ids'])){
$poster_ids = $_POST['poster_ids'];
$poster_qtys = $_POST['poster_qty'];
}
$query = "UPDATE $tablename set title='$title',description='$description',event_code='$event_code',valid_from='$event_from',valid_to='$event_to',store_id='$banner_store_id', prize = '$prize' ";
$query .= "where id = $update_this_event";
$result_insert = $wpdb->query($query);
$delete_query = "delete from $tablename6 where event_id = $update_this_event";
$wpdb->query($delete_query);
for($i = 0; $i < count($poster_ids); $i++) {
$poster_id = esc_sql($poster_ids[$i]);
$poster_qty = esc_sql($poster_qtys[$i]);
$poster_query = "INSERT INTO $tablename6 (event_id,poster_id, qty) values ";
$poster_query .= "('$update_this_event','$poster_id','$poster_qty');";
$poster_insert = $wpdb->get_results($poster_query);
$poster_result = $wpdb->insert_id;
}
$update_this_event = -1;
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
}
?>
<style type="text/css" emb-not-inline="">
.table-container {
width: 100%;
max-width: 100%;
overflow-x: auto;
}
.hidden {
display: none;
}
.banner-button {
background-color: #ffffff;
border-radius: 5px;
padding: 5px;
font-size: 13px;
min-width: 75px;
}
table {
border: none;
text-align: center;
}
table tr:nth-child(even) {
background-color: #dddddd;
}
table tr:nth-child(odd) {
background-color: #ffffff;
}
table th {
background-color: #23282d;
color: #ffffff;
}
table th:first-child{
border-radius: 20px 0px 0px 0px;
}
table th:last-child{
border-radius: 0px 20px 0px 0px;
}
table {
border-radius: 20px 20px 0px 0px;
}
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<h1>View All events</h1>
<br/>
<div class="table-container" style="
width: 100%;
max-width: 100%;
overflow-x: auto;
">
<table cellpadding="10" border=1 style="border-style: solid #AAA">
<tr>
<th>Title</th>
<th>Description</th>
<th>Prize</th>
<th>event Code</th>
<th>banner Store</th>
<th>poster Qty</th>
<th>Validity</th>
<th>QR code</th>
<th>Action</th>
</tr>
<?php
foreach($results as $result) {
if($update_this_event == $result->id) { ?>
<tr>
<form method="post" name="formtest1" id="formtest1">
<td valign="top"><input type="text" name="title" value="<?php echo $result->title ?>"/> </td>
<td valign="top"><input type="text" name="description" value="<?php echo $result->description ?>"/> </td>
<td valign="top"><input type="text" name="prize" value="<?php echo $result->prize ?>"/> </td>
<td valign="top"><input type="text" name="event_code" value="<?php echo $result->event_code ?>"/> </td>
<td valign="top">
<!-- <select onChange="changebanner(this)" id="banner_store_id" name="banner_store_id"> -->
<select id="banner_store_id" name="banner_store_id">
<?php
foreach($banner_stores as $pstore) {
if($result->banner_id == $pstore->id) {
?>
<option SELECTED value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}else {
?>
<option value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}
}
?>
</select>
</td>
<td valign="top">
<div id="poster_div">
<table border="0" cellpadding=5>
<?php
if(count($poster_event) == 0) {
for($i = 0; $i < count($poster_petone); $i++)
{
?>
<tr>
<td>
<input type="hidden" name="poster_ids[]" value="<?php echo $poster_petone[$i]->id?>"><?php echo $poster_petone[$i]->name?>
</td>
<td>
<input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_petone[$i]->qty ?>">
</td>
</tr>
<?php
}
}else {
for($i = 0; $i < count($poster_event); $i++)
{
?>
<tr>
<td><input type="hidden" name="poster_ids[]" value="<?php echo $poster_event[$i]->poster_id?>"><?php echo $poster_event[$i]->poster_name?></td>
<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_event[$i]->qty?>"></td>
</tr>
<?php
}
}?>
</table>
</div>
</td>
<td valign="top"><input id="event_from" name="event_from" type="text" value="<?php echo $result->valid_from ?>"/> - <input name="event_to" id="event_to" type="text" value="<?php echo $result->valid_to ?>"/> </td>
<td valign="top"></td>
<td valign="top">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> ">
<input type="submit" name="save_update_event" value="save" class="banner-button">
<input type="submit" name="cancel_update_event" value="cancel" class="banner-button">
</td>
</form>
</tr>
<?php
} else {
?>
<tr>
<td valign="top"><?php echo $result->title ?> </td>
<td valign="top"><?php echo $result->description ?> </td>
<td valign="top"><?php echo $result->prize ?> </td>
<td valign="top"><?php echo $result->event_code ?> </td>
<td valign="top"><?php echo $result->banner_name ?> </td>
<td valign="top"><?php get_poster_of_event($result->id ) ?> </td>
<td valign="top"><?php echo $result->valid_from ?> - <?php echo $result->valid_to ?></td>
<td valign="top"><?php generate_random("https://generic.com/event/?random=".$result->event_code, $result->title) ?> </td>
<td valign="top">
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="delete_event" value="delete" class="banner-button"/>
</form>
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="select_update_event" value="update" class="banner-button"/>
</form>
</td>
</tr>
<?php
}
}
?>
</table>
</div>
<script>
let jQueryNC = jQuery.noConflict();
jQueryNC( function() {
jQueryNC( "#event_to" ).datepicker({ dateFormat: 'yy-mm-dd' });
jQueryNC( "#event_from" ).datepicker({ dateFormat: 'yy-mm-dd' });
} );
jQueryNC("body").on("change", "#banner_store_id", function() {
changebanner(jQueryNC(this));
});
function changebanner(e){
let jQueryNC = jQuery.noConflict();
jQueryNC( "#poster_div" ).html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
let value = jQueryNC("#banner_store_id").val();
console.log(e.value);
formData.append('poster_id', value);
formData.append('action', 'get_poster');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let posters = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for(let i = 0; i < posters.length; i++)
{
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="poster_ids[]" value="'+posters[i].id+'">'+posters[i].name+'</td>';
htmldiv += '<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="'+posters[i].qty+'"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#poster_div").html(htmldiv);
}
}
</script>
<?php
} ?>
Clarification: when the select input is not changed, the inputs inside container div are recognized upon submitting without any errors, but when the contents of container div are changed via changebanner; the new inputs and tables are created but if it is submitted, the inputs like poster_ids[] is not recognized by $_POST['poster_ids']
EDIT added the entire code in hopes of clarifying the problem
I tried to explain the issue in my comments but maybe it will be easier to see here.
Your initial form on page load has a bunch of inputs etc in it, including some poster_ids and poster_qty.
If you submit that form, by clicking the submit button, a standard HTML form submission via POST happens. All the inputs that exist in the form on page load will be sent in the request, and your PHP will get all of them.
But if you don't submit the form, and instead change the selected #banner_store_id option, some Javascript takes over. That JS will do a few things:
Create an empty formData object, ignoring everything currently in your form;
Add 2 new key/value pairs to that formData
POST those 2 values to your PHP. Note this is not a standard HTML POST like the one that happens when you click submit, it is an AJAX POST. It is essentially independent of the <form> on the page, and it will only POST the fields from the form if you specifically add them. The code you have does not do that, and so does not include any of your existing form fields.
If you try to use $_POST['poster_ids'] in the PHP which receives this JS POST, it will fail, because those fields were not in the request. The only things there are a poster_id and an action.
If you do want to include all the fields in your form in the data you POST via JS when changing #banner_store_id, you need to create a formData with the form itself, as shown in the docs:
let myForm = document.getElementById('formtest1');
let formData = new FormData(myForm);
If you do this, then all the inputs on your form are bundled up and included in that formData, and just like with the normal POST will all be sent to your PHP.
Here's the relevant part of your code, commented to explain it further:
function changebanner(e) {
// Create a new FormData object - **NOTE** it is empty! You have not passed
// in your existing form, so none of the form inputs already on the page are
// in FormData. If you POSTed it right away $_POST would be completely empty.
let formData = new FormData();
// Now add 2 items to it
formData.append('poster_id', value);
formData.append('action', 'get_poster');
// Now make your POST, and send formData, which has just those 2 items
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
// The POST is done, you sent poster_id and action and nothing else to your PHP
}
Try taking out the onchange(this) in the select and instead use the jQuery on.("change").
Without seeing the exact error or what you have tried it is hard to say exactly but trying to access a variable that has not be created yet often gives an undefined because you are trying to access it before it exists. By using the jQuery on function you can find things added after DOM has loaded.
Good luck.
$("body").on("change", "#data_store_id", function() {
changeSELECTED($(this));
});
function changeSELECTED(e) {
let jQueryNC = jQuery.noConflict();
jQueryNC("#container_div").html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
formData.append('data_id', e.value);
formData.append('action', 'get_data');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/adminfolder/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let datas = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for (let i = 0; i < datas.length; i++) {
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="data_ids[]" value="' + datas[i].id + '">' + datas[i].name + '</td>';
htmldiv += '<td><input type="text" name="data_qty[]" placeholder= "Qty Allocation" value="' + datas[i].qty + '"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#container_div").html(htmldiv);
}
}
<select id="data_store_id" name="data_store_id">
<?php
foreach($data_stores as $dstore) {
if($result->data_id == $dstore->id) {
?>
<option SELECTED value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}else {
?>
<option value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}
}
?>
</select>

how to make Laser fiche quote page in php (record indert,update, delete and listing)

I have made one application for laser fiche quote page.
Make lase fiche quote page in PHP
create an Order Management System
How can I achieve:
create a new data form
quote edit data
quote delete in listing
Insert record code :
<script type="text/javascript">
function calc(control){
var row = $(control).parent().parent();
var qty = row.find("input[id^='qty']").val();
var price = row.find("input[id^='unitprice']").val();
var laspprice = row.find("input[id^='laspprice']").val();
row.find("input[id^='subtotal']").val( (qty * price) + (qty *laspprice) );
var grandTotal = 0;
$(".subtotal").each(function () {
var stval = parseFloat($(this).val());
grandTotal += isNaN(stval) ? 0 : stval;
});
$('#grdtot').val(grandTotal.toFixed(2));
}
</script>
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "******";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, parrent_id, listitem, unitprice, lsapprice FROM avantlist";
$result = $conn->query($sql);
if ($result->num_rows > 0){
?>
<div class="lf-quote-page">
<div class="lf-title clearfix">
<div class="wrap">
<h1 class="entry-title">Laserfiche Avante Quote</h1>
</div>
</div>
<div class="lf-content">
<div class="wrap">
<div class="lf-quote-table">
<form action="http://10.0.0.16:8080/data2/userdata.php" method="post" id="form">
<table id="tblProducts" class="table">
<thead>
<tr>
<td style="width: 40%;"><b>List Item</b></td>
<td><b>Quantity</b></td>
<td><b>Unit Price</b></td>
<td><b>LSAP Price</b></td>
<td><b>Sub-Total</b></td>
<td width="150"><b>Select Sub Item</b></td>
</tr>
<tr><td colspan="6"><b>Server</b></td></tr>
</thead>
<tbody>
<input type="hidden" class="id" value="<?php $id; ?>" name="id" id="id[]" style="width:300px;"/>
<?php
$i = 1;
$j = 1;
while($row = $result->fetch_assoc()){
$id = $row['id'];
$parrent_id = $row['parrent_id'];
$listitem = $row['listitem'];
$unitprice = $row['unitprice'];
$lsapprice = $row['lsapprice'];
if($parrent_id == 0 || $parrent_id == 2 || $parrent_id == 3) {
if($row['id']!=='10' && $row['id']!=='14' && $row['id']!=='17' && $row['id']!=='20'){?>
<tr data-type="parent<?php echo $i++;?>" id="<?php echo 'row'.$id;?>">
<td><input type="text" class="listitem" value="<?php echo $listitem; ?>" name="listitem[]" id="listitem" readonly/></td>
<td><input type="text" class="qty" value="0" name="qty[]" onkeypress="return isNumberKey(event)" id="qty" onblur="calc(this)"/></td>
<td><input type="text" class="unitprice" value="<?php echo $unitprice;?>" name="unitprice[]" id="unitprice" readonly/></td>
<td><input type="text" class="laspprice" value="<?php echo $lsapprice;?>" name="laspprice[]" id="laspprice" readonly/></td>
<td><input type="text" class="subtotal" value="0" name="subtotal[]" id="subtotal" readonly/></td>
<td><?php if ($parrent_id == 0) { ?><input type="checkbox" onchange="showDetails(this)" /></td><?php } ?>
</tr>
<?php } if($row['id']=='10') {?>
<tr><td colspan="6"><b><?php echo $listitem;?></b></td></tr>
<?php } if($row['id']=='14') {?>
<tr><td colspan="6"><b><?php echo $listitem;?></b></td></tr>
<?php } if($row['id']=='17') {?>
<tr><td colspan="6"><b><?php echo $listitem;?></b></td></tr>
<?php } if($row['id']=='20') {?>
<tr><td colspan="6"><b><?php //echo $listitem;?></b></td></tr>
<?php }
}elseif($parrent_id == 0 || $parrent_id == 1) {?>
<tr data-type="child<?php echo $j++;?>" class="hide">
<td><input type="text" class="listname" value="<?php echo $listitem; ?>" name="listname[]" id="listname" readonly/></td>
<td><input type="text" class="qty" value="0" name="qty[]" onkeypress="return isNumberKey(event)" id="qty" onblur="calc(this)"/></td>
<td><input type="text" class="unitprice" value="<?php echo $unitprice;?>" name="unitprice[]" id="unitprice" readonly/></td>
<td><input type="text" class="laspprice" value="<?php echo $lsapprice;?>" name="laspprice[]" id="laspprice" readonly/></td>
<td><input type="text" class="subtotal" value="0" name="subtotal[]" id="subtotal" readonly/></td>
<td> </td>
</tr>
<?php }
}?>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td style="text-align:right;">Total System Price:</td>
<td><input type="text" class="grdtot" value="" id="grdtot" name="" readonly/></td>
</tr>
</tfoot>
</table>
<div class="quote-bottom-row clearfix">
<div class="quote-lable">
<label>Quote name</label>
<input type="text" class="formbox" name="quotename" required><br>
<input type="submit" value="Submit" name="submit" class="btn"/>
<input type="button" value="cancel" name="cancel" class="btn gray-btn"/>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php } ?>
<script type="application/javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script>
function showDetails(chk) {
//var animalType = animal.getAttribute("data-type");
var tr = $(chk).parent().parent();
var attr = tr.attr("data-type");
var attr1 = tr.attr("data-type");
var attr = attr.replace("parent", "child")
var t = $("#tblProducts").children('tbody').children('tr').each(function (element) {
if ($(chk).prop('checked') == true) {
if ($(this).attr("data-type") == attr) {
$(this).addClass("show");
$(this).removeClass("hide");
}
else {
if ($(this).attr("data-type").indexOf("child") != -1) {
$(this).addClass("hide");
$(this).removeClass("show");
}
if ($(this).attr("data-type").indexOf("parent") != -1) {
if ($(this).attr("data-type") != attr1) {
$(this).children().find("input").prop('checked', false);
}
}
}
}
else
{
$(this).children().find("input").prop('checked', false);
if ($(this).attr("data-type").indexOf("child") != -1) {
$(this).addClass("hide");
}
}
});
// $(tr).addClass("show");
//$(tr).removeClass("hide");
}
</script>
Edit/Delete code : [Edit functionality not working, Delete functionality working]
<script type="text/javascript">
function calc(control){
var row = $(control).parent().parent();
var qty = row.find("input[id^='qty']").val();
var price = row.find("input[id^='unitprice']").val();
var laspprice = row.find("input[id^='laspprice']").val();
row.find("input[id^='subtotal']").val( (qty * price) + (qty *laspprice) );
var grandTotal = 0;
$(".subtotal").each(function () {
var stval = parseFloat($(this).val());
grandTotal += isNaN(stval) ? 0 : stval;
});
$('#grdtot').val(grandTotal.toFixed(2));
}
</script>
<input type="hidden" name="quoteid" value=<?php echo $_GET['quoteid'];?>>
<?php
if(isset($_POST['update'])){
$servername = "****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$quoteid = $_GET['quoteid'];
$sql = "DELETE FROM userdata1 WHERE quoteid='$quoteid'";
echo $sql;
if($conn->query($sql) === TRUE){
//echo "Record deleted successfully";
$servername = "******";
$username = "******";
$password = "******";
$dbname = "*****";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn2->connect_error);
}
$listitem = $_POST['listitem'];
$qty = $_POST['qty'];
$unitprice = $_POST['unitprice'];
$laspprice = $_POST['laspprice'];
$subtotal = $_POST['subtotal'];
$quotename = $_POST['quotename'];
function getGUID(){
if(function_exists('com_create_guid')){
return com_create_guid();
}
else{
mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45);// "-"
$uuid = "" // "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.""; // "}"
return $uuid;
}
}
$GUID = getGUID();
$GUID = str_replace("{","",$GUID );
$GUID = str_replace("}","",$GUID );
foreach($_POST['listitem'] as $row=>$Listitem){
//$username=mysqli_real_escape_string($Listitem);
//$id=$_POST['id'][$row];
$listitem=$_POST['listitem'][$row];
$qty=$_POST['qty'][$row];
$unitprice=$_POST['unitprice'][$row];
$laspprice=$_POST['laspprice'][$row];
$subtotal=$_POST['subtotal'][$row];
$quotename=$_POST['quotename'][$row];
$sql2 = "INSERT INTO userdata1(listitem, qty, unitprice, laspprice, subtotal, quotename, quoteid)
VALUES('$listitem', '$qty', '$unitprice', '$laspprice', '$subtotal', '$quotename','$GUID')";
//print_r($sql2 .'<br/>');
$result2 = mysqli_query($sql2)or die(mysqli_error());
//print_r($result2);
}
if($result2){
echo "Quote updated successful";
echo "<meta http-equiv=\"refresh\" content=\"1;URL=http://10.0.0.16:8080/data2/index.php?file=Product_list \">";
}
}
else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
}
$servername = "******";
$username = "*****";
$password = "*****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$quoteid = $_GET['quoteid'];
$sql = "SELECT * FROM userdata1 WHERE quoteid='$quoteid'";
$result = $conn->query($sql);
if ($result->num_rows > 0){
?>
<div class="lf-quote-page">
<div class="lf-title clearfix">
<div class="wrap">
<h1 class="entry-title">Laserfiche Avante Quote- Update</h1>
</div>
</div>
<div class="lf-content">
<div class="wrap">
<div class="lf-quote-table">
<form action="<?php $_PHP_SELF ?>" method="post" id="form">
<table id="tblProducts" class="table">
<thead>
<tr>
<td style="width: 40%;"><b>List Item</b></td>
<td><b>Quantity</b></td>
<td><b>Unit Price</b></td>
<td><b>LSAP Price</b></td>
<td><b>Sub-Total</b></td>
<!--<td width="150"><b>Select Sub Item</b></td>-->
</tr>
<tr><td colspan="5"><b>Server</b></td></tr>
</thead>
<input type="hidden" class="id" value="<?php $id; ?>" name="id" id="id[]" style="width:300px;"/>
<tbody>
<?php
$i = 1;
$j = 1;
while($row = $result->fetch_assoc()){
$id = $row['id'];
$listitem = $row['listitem'];
$qty = $row['qty'];
$unitprice = $row['unitprice'];
$laspprice = $row['laspprice'];
$subtotal = $row['subtotal'];
$quotename = $row['quotename'];
//$quoteid = $row['quoteid'];
?>
<tr data-type="parent<?php echo $i++;?>" id="<?php echo 'row'.$id;?>">
<td><input type="text" class="listitem" value="<?php echo $listitem; ?>" name="listitem[]" id="listitem" readonly/></td>
<td><input type="text" class="qty" value="0" name="qty[]" onkeypress="return isNumberKey(event)" id="qty" onblur="calc(this)"/></td>
<td><input type="text" class="unitprice" value="<?php echo $unitprice;?>" name="unitprice[]" id="unitprice" readonly/></td>
<td><input type="text" class="laspprice" value="<?php echo $laspprice;?>" name="laspprice[]" id="laspprice" readonly/></td>
<td><input type="text" class="subtotal" value="0" name="subtotal[]" id="subtotal" readonly/></td>
<!--<td><?php //if ($parrent_id == 0) { ?><input type="checkbox" onchange="showDetails(this)" /></td><?php //} ?>-->
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td style="text-align:right;">Total System Price:</td>
<td><input type="text" class="grdtot" value="" id="grdtot" name="" readonly/></td>
</tr>
</tfoot>
</table>
<div class="quote-bottom-row clearfix">
<div class="quote-lable">
<label>Quote name</label>
<input type="text" class="formbox" value="<?php echo $quotename; ?>" name="quotename[]" required><br>
<input type="submit" name="update" value="Update" class="btn">
<input type="button" value="cancel" name="cancel" class="btn gray-btn"/>
<input type="hidden" name="quoteid" value=<?php echo $_GET['quoteid'];?>>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php } ?>
<script type="application/javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script>
function showDetails(chk) {
//var animalType = animal.getAttribute("data-type");
var tr = $(chk).parent().parent();
var attr = tr.attr("data-type");
var attr1 = tr.attr("data-type");
var attr = attr.replace("parent", "child")
var t = $("#tblProducts").children('tbody').children('tr').each(function (element) {
if ($(chk).prop('checked') == true) {
if ($(this).attr("data-type") == attr) {
$(this).addClass("show");
$(this).removeClass("hide");
}
else {
if ($(this).attr("data-type").indexOf("child") != -1) {
$(this).addClass("hide");
$(this).removeClass("show");
}
if ($(this).attr("data-type").indexOf("parent") != -1) {
if ($(this).attr("data-type") != attr1) {
$(this).children().find("input").prop('checked', false);
}
}
}
}
else
{
$(this).children().find("input").prop('checked', false);
if ($(this).attr("data-type").indexOf("child") != -1) {
$(this).addClass("hide");
}
}
});
}
</script>
You can load your calc function like this:
window.onload = function()
{
calc();
};
Manage Radio button Like this:
<?php if($row['id']=='1') {?>
<input type="radio" name="rad" value="rad1" onchange="showDetails(this);" />
<?php } ?>
<?php if($row['id']=='2') {?>
<input type="radio" name="rad" value="rad3" onchange="showDetails(this);" />
<?php } ?>
<script>
if(selValue=='rad1')
{
$(".addqty1").val(1);
$("input.addqty1").attr("readOnly", true);
$("input.addqty3").attr("disabled", true);
$("input.addqty4").attr("disabled", true);
$("input.addqty5").attr("disabled", true);
$("input.addqty6").attr("disabled", true);
$("input.addqty7").attr("disabled", true);
$("input.addqty8").attr("disabled", true);
$("input.addqty9").attr("disabled", true);
}
else if(selValue=='rad2')
{
$(".addqty2").val(1);
$(".subtotal").val('');
$("input.addqty3").attr("readOnly", true);
$("input.addqty3").attr("disabled", false);
$("input.addqty4").attr("readOnly", true);
$("input.addqty1").attr("disabled", true);
$("input.addqty2").attr("disabled", true);
$("input.addqty5").attr("disabled", true);
$("input.addqty6").attr("disabled", true);
$("input.addqty7").attr("disabled", true);
$("input.addqty8").attr("disabled", true);
$("input.addqty9").attr("disabled", true);
}
</script>
Not tested, hope this help for you.

PHP redirect to page on form submit based on select

I am trying to get PHP to read my select options as variables and then echo out a particular page based on the users choice.
The login system is functional but only logs me into one page.
<form action="login.php" method="POST">
<table cellspacing="10">
<tr>
<td>Email: </td>
<td><input type='text' name='email'/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type='password' name='password'/></td>
</tr>
<tr>
<td>Event: </td>
<td>
<select name="event">
<option><?php echo $title?></option>
<option><?php echo $title2?></option>
</select>
</td>
</tr>
</table>
<br />
<button class="button" type='submit' name='Submit' value='Submit' />Login</button>
</form>
<?php
if (!empty($email) && !empty($password)) {
$pdo = getPdo();
$statement = $pdo->prepare('SELECT * FROM awdawda WHERE email=:email;');
$statement->bindParam(':email', $email);
$statement->execute();
$data = $statement->fetch();
$pdo = null;
if (!empty($data)) {
$dbemail = $data['email'];
$dbpassword = $data['password'];
$dbfullname = $data['fullname'];
if ($password == $dbpassword) {
$_SESSION['fullname'] = $dbfullname;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
if ($_POST['event']) {
$event1=$title;
echo '<script type="text/javascript">window.location = "http://awda/adwa/awd1.php" </script>';
}
if ($_POST['event']) {
$event2=$title2;
echo '<script type="text/javascript">window.location = "http://awdaw/awda/adwa.php" </script>';
}
}
echo '<div style="padding: 10px;">Login Failed: Password Incorrect</div>';
}
echo '<div style="padding: 10px;">User not found</div>';
}
?>
That is the code I am using to login with. I left out what was above it since it all works fine right now.
You have to give value to the options of your select tag
<select name="event">
<option value="value1"><?php echo $title?></option>
<option value="value2"><?php echo $title2?></option>
</select>
and have to update your php logic according to these value
if ($_POST['event'] == "value1") {
$event1=$title;
echo '<script type="text/javascript">window.location = "http://awda/adwa/awd1.php" </script>';
}
if ($_POST['event'] == "value2") {
$event2=$title2;
echo '<script type="text/javascript">window.location = "http://awdaw/awda/adwa.php" </script>';
}

Form validates but won't submit data to database table

I'm working on this project and it's pretty much finished, it's a form that validates if the user submits invalid data, but for some reason the data won't store in the table and therefore won't get posted back to the screen, I'm just wondering if anybody could spot where I'm going wrong as I've been looking at it for over an hour. Thanks a lot.
Below is my code:
index.php
<!Doctype html public>
<body>
<table cellpadding="5">
<td>
<h1> Games Club Website</h1>
<form action="process.php" method = "post">
<tr>
<td class="label">
<label for="firstName">
First name
</label>
</td>
<td>
<input type="text"
name="firstName"
id="firstName"
value="<?php
if (isset($validator))
echo $validator->getValue('firstName');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('firstName');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="lastName">
Surname
</label>
</td>
<td>
<input type="text"
name="lastName"
id="lastName"
value="<?php
if (isset($validator))
echo $validator->getValue('lastName');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('lastName');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="email">
Email Address
</label>
</td>
<td>
<input type="text"
name="email"
id="email"
value="<?php
if (isset($validator))
echo $validator->getValue('email');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('email');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="age">
Age
</label>
</td>
<td>
<input type="text"
name="age"
id="age"
value="<?php
if (isset($validator))
echo $validator->getValue('age');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('age');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label>
Gender
</label>
</td>
<td>
<label for="genderMale">Male</label>
<input type="radio"
name="gender"
id="genderMale"
value="Male"
<?php
if (isset($validator))
echo $validator->isChecked("gender", "Male");
?>
/>
<label for="genderFemale">Female?</label>
<input type="radio"
name="gender"
id="genderFemale"
value="Female"
<?php
if (isset($validator))
echo $validator->isChecked("gender", "Female");
?>
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('gender');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label>
What is your preferred gaming platform?
</label>
</td>
<td>
<label for="consoleXbox">Xbox 360</label>
<input type="radio"
name="console"
id="consoleXbox"
value="Xbox 360"
<?php
if (isset($validator))
echo $validator->isChecked("console", "Xbox 360");
?>
/>
<label for="consolePs3">Playstation 3</label>
<input type="radio"
name="console"
id="consolePs3"
value="PS3"
<?php
if (isset($validator))
echo $validator->isChecked("console", "PS3");
?>
<label for="consoleWii">Nintendo Wii</label>
<input type="radio"
name="Console"
id="consoleWii"
value="Wii"
<?php
if (isset($validator))
echo $validator->isChecked("console", "Wii");
?>
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('console');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="password1">
Enter a password:
</label>
</td>
<td>
<input type="password"
name="p1"
id="p1"
value="<?php
if (isset($validator))
echo $validator->getValue('p1');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('p1');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="p2">
Confirm password:
</label>
</td>
<td>
<input type="password"
name="p2"
id="p2"
value="<?php
if (isset($validator))
echo $validator->getValue('p2');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('p2');
?>
</span>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit"
name="submitButton"
id="submitButton"
value="Confirm Registration" />
<input type="reset"
name="resetButton"
id="resetButton"
value="Clear Data"
style="margin-right: 20px;" />
</td>
</tr>
</form>
</td>
</table>
</body>
</html>
Process.php
<?php
require_once "FormValidator.php";
$validator = new FormValidator();
if ($validator->validate($_POST)) {
require 'dao.php';
}
else {
require 'index.php';
}
?>
FormValidator.php
<?php
class FormValidator {
private $valid;
private $errors;
private $data;
public function __construct() {
$this->valid = TRUE;
$this->errors = array();
$this->data = NULL;
}
public function validate($data) {
$this->data = $data;
if (empty($data['firstName'])) {
$this->valid = FALSE;
$this->errors['firstName'] = 'A <u>First Name</u> is required<br/>';
}
if (empty($data['lastName'])) {
$this->valid = FALSE;
$this->errors['lastName'] = 'A <u>Surname</u> is required.<br/>';
}
if (empty($data['p1'])) {
$this->valid = FALSE;
$this->errors['p1'] = 'A <u>Password</u> is required.<br/>';
}
if (empty($data['console'])) {
$this->valid = FALSE;
$this->errors['console'] = 'Please choose a <u>Console</u>.<br/>';
}
if (empty($data['p2'])) {
$this->valid = FALSE;
$this->errors['p2'] = 'Please <u>Confirm</u> password.<br/>';
}
if (empty($data['age'])) {
$this->valid = FALSE;
$this->errors['age'] = 'Please enter your <u>Age</u>.<br/>';
}
else if (!$this->isValidIntegerInRange($data['age'], 18, 100)) {
$this->valid = FALSE;
$this->errors['age'] = 'Invalid age. You also need to be at least 18 to sign up.<br/>';
}
if (empty($data['email'])) {
$this->valid = FALSE;
$this->errors['email'] = 'Please enter a valid <u>email address</u>.<br/>';
}
else if (!$this->isValidEmail($data['email'])) {
$this->valid = FALSE;
$this->errors['email'] = 'Incorrect format (name#website.something is required)<br/>';
}
if (empty($data['p2'])) {
$this->valid = FALSE;
$this->errors['p2'] = 'Please <u>Confirm</u> password.<br/>';
}
if (!empty($data['p1'])
&& !empty($data['p2'])
&& $data['p1'] !== $data['p2']) {
$this->valid = FALSE;
$this->errors['p2'] = 'Error, passwords <u>do not match</u> .<br/>';
}
if (empty($data['gender'])) {
$this->valid = FALSE;
$this->errors['gender'] = '<u>Please select a Gender.<u>';
}
return $this->valid;
}
public function getError($key) {
$error = "";
if (isset($this->errors[$key])) {
$error = $this->errors[$key];
}
return $error;
}
public function getValue($key) {
$value = "";
if (isset($this->data[$key])) {
$value = $this->data[$key];
}
return $value;
}
public function isChecked($key, $value) {
$checked = "";
if (isset($this->data[$key]) && $this->data[$key] === $value) {
$checked = ' checked="checked"';
}
return $checked;
}
public function isSelected($key, $value) {
$selected = "";
if (isset($this->data[$key]) && $this->data[$key] === $value) {
$selected = ' selected="selected"';
}
return $selected;
}
private function isValidEmail($email) {
return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
}
protected function isValidIntegerInRange($integer, $min, $max) {
$options = array(
'options' => array(
'min_range' => $min,
'max_range' => $max,
)
);
return (filter_var($integer, FILTER_VALIDATE_INT, $options) !== FALSE);
}
}
?>
dao.php
<html>
<body>
<?php
//Make connection to the database
$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";
TRY {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$console = $_POST['console'];
$p1 = $_POST['p1'];
$p2 = $_POST['p2'];
if (isset($_POST['id'])) {
//Updates the record
$id = $_POST['id'];
$sql = "UPDATE userprofile2 SET"
. "firstName=".$conn->quote($fname)
. "lastName=".$conn->quote($lastName)
. "email=".$conn->quote($email)
. "age=".$conn->quote($age)
. "gender=".$conn->quote($gender)
. "console=".$conn->quote($console)
. "p1=".$conn->quote($p1)
. "p2=".$conn->quote($p2)
. "WHERE id = ".$conn->quote($id);
$userprofile2 = $conn->query($sql);
} else {
// Inserts new values into table
$sql = "INSERT INTO userprofile2(firstName, lastName, email, age, gender, console, p1, p2"
. " ) VALUES ("
. $conn->quote($firstName).","
. $conn->quote($lastName).","
. $conn->quote($email).","
. $conn->quote($age).","
. $conn->quote($gender).","
. $conn->quote($console).","
. $conn->quote($p1).","
. $conn->quote($p2) . ")";
$userprofile2 = $conn->query($sql);
}
} elseif (isset($_GET['ID'])) {
// edit mode, allows user to change a selected parameter in the table (Not working)
$userEditDataRows = $conn->query('SELECT * FROM userprofile2 WHERE ID ='.$conn->quote($_GET['ID']));
if (sizeof($userEditDataRows)>0) {
// $row = $userEditDataRows[0];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$email = $row['email'];
$age = $row['age'];
$gender = $row['gender'];
$console = $row['console'];
$console = $row['p1'];
$console = $row['p2'];
$ID = $_GET['ID'];
}
} else {
//Set the empty values for fields that haven't been filled in
$firstName = '';
$lastName = '';
$email = '';
$age = '';
$gender = '';
$console = '';
$p1 = '';
$p2 = '';
$ID = false;
}
//construct the table
$sql = "SELECT * FROM userprofile2";
$userprofile2 = $conn->query($sql);
$table = '<table>';
$table .= '<tr>';
$table .= '<th> ID </th>
<th> First Name </th>
<th> Last Name </th>
<th> Email Address </th>
<th> Age </th>
<th> Gender </th>
<th> Console </th>
<th> Password </th>
<th> Password (Confirmed) </th>';
$table .= '</tr>';
foreach ($userprofile2 as $userprofile2) {
$table .= ' <tr>';
$table .= ' <td>' . $userprofile2['id'] ." ". '</td>';
$table .= ' <td>' . $userprofile2['firstName'] . '</td>';
$table .= ' <td>' . $userprofile2['lastName'] . '</td>';
$table .= ' <td>' . $userprofile2['email'] . '</td>';
$table .= ' <td>' . $userprofile2['age'] . '</td>';
$table .= ' <td>' . $userprofile2['gender'] . '</td>';
$table .= ' <td>' . $userprofile2['console'] . '</td>';
$table .= ' <td>' . $userprofile2['p1'] . '</td>';
$table .= ' <td>' . $userprofile2['p2'] . '</td>';
$table .= ' </tr> ';
}
$table .= '</table>';
} catch (PDOException $e) {
exit("Connection failed: " . $e->getMessage());
//catches errors and prints them to screen
}
?>
<h2>Thank you <?php echo $_POST["firstName"]; // confirmation of a successful
//entry ?>, your details have been stored!<br /></h2>
<u><h1>Here are the contents of your database:</h1></u>
<?php echo $table ?>
</br>
Click Here to go back to the form. </br>
<html>
<body>
I think the problem is $_POST['id']. It's not defined anywhere so it doesn't get the chance to insert because of the following code block:
if (isset($_POST['id'])) {
Try using $_GET['id'] instead:
if (isset($_GET['id'])) {

Categories