I have a php project that inserts the coordinates of the selected seats of a theater in a db msql.
This is the js file that draws the map and contains the variables.
var price = 0; //price
var $cart = $('#selected-seats'); //Sitting Area
var $counter = $('#counter'); //Votes
var $total = $('#total'); //Total money
var sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaa__a',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaabbb'
],
naming : {
top : true,
rows: ['A','B','C','D','E'],
getLabel : function (character, row, column) {
return column;
}
},
seats:{
a:{
price: 99.9
},
b:{
price: 200
}
},
legend : { //Definition legend
node : $('#legend'),
items : [
[ 'a', 'available', 'Option' ],
[ 'a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
var maxSeats = 3;
var ms = sc.find('selected').length;
//alert(ms);
if (ms < maxSeats) {
price = this.settings.data.price;
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+'</option>')
.attr('id', 'cart-item-'+this.settings.id)
.attr('value', this.settings.id)
.attr('alt', price)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
$counter.attr('value', sc.find('selected').length+1);
$total.text(recalculateTotal(sc));
$total.attr('value', recalculateTotal(sc));
return 'selected';
}
alert('You can only choose '+ maxSeats + ' seats.');
return 'available';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length-1);
$counter.attr('value', sc.find('selected').length-1);
//Delete reservation
$('#cart-item-'+this.settings.id).remove();
//update totalnum
$total.text(recalculateTotal(sc));
$total.attr('value', recalculateTotal(sc));
//Delete reservation
//$('#cart-item-'+this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-line camelcase
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
// #todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
// Add total money
function recalculateTotal(sc) {
var total = 0;
$('#selected-seats').find('option:selected').each(function () {
total += Number($(this).attr('alt'));
});
return number_format(total,2,'.','');
}
This file is viewed by a PHP file in a form like this
<div class="demo" style="margin-top:10px;min-width: 360px;">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div id="legend"></div>
</div>
<form role="form" id="myfrm2" action="book.php?id=<?php echo $FILM_ID; ?>" method="post">
<input type="hidden" name="session" value="<?php echo $session; ?>">
<input type="hidden" name="date" value="<?php echo $date; ?>">
<select class="form-control" style="display:block;" id="selected-seats" name="seat[]" multiple="multiple"></select>
<p>Tickets: <input id="counter" name="counter" readonly></input></p>
<p>Total: <b>€<input id="total" name="total" readonly></input></b></p>
<button type="submit" style="display: block; width: 100%;" name="book" value="book" class="btn btn-danger">Book</button>
</form>
<?php } ?>
</div>
All data are inserted into a DB mysql by this PHP file
<?php
if (isset($_POST['book'])) {
$date = $_POST["date"];
$session = $_POST["session"];
$counter = $_POST["counter"];
$total = $_POST["total"];
$user_id = $_SESSION["id"];
$film_id = $_GET['id'];
$seat = (isset($_POST['seat']) ? $_POST['seat']:array());
if (is_array($seat)) {
foreach ($seat as $selectedOption){
$query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, BOOKING_PRICE, BOOKING_NUM)
VALUES ('$user_id','$film_id','$session','$date','$selectedOption','$total','$counter')";
$result = mysqli_query ($connection,$query)
or die ("<div class='alert alert-danger' role='alert'>You couldn't execute query</div>");
}
echo " <div class='alert alert-success' role='success'>
Congrats your booking has been done! Print the tickets <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
</div>";
}
}
?>
Everything works correctly, all data are inserted in the DB !
But I have added a data to insert to the DB, the price SEAT_PRICE, so I have changed the "option selected" in the JS file to this
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+' P'+this.settings.data.price+'</option>')
the price (the tag in the console is "alt" is now visible on the page but I don't understand how to store this data to the DB.
Any suggestion is appreciated
OK after many attempts and posts in many forum, I have found my solution.
1) The JS file must be modified like that (passing 2 values):
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+' P'+this.settings.data.price+'</option>')
.attr('id', 'cart-item-'+this.settings.id)
.attr('value', this.settings.id + "|" + this.settings.data.price)
.attr('alt', price)
.data('seatId', this.settings.id)
.appendTo($cart);
2) the PHP file must be changed like that (dividing seat array - separated by "|" - to post the 2 values:
<?php
if (isset($_POST['book'])) {
$date = $_POST["date"];
$session = $_POST["session"];
$counter = $_POST["counter"];
$total = $_POST["total"];
$user_id = $_SESSION["id"];
$film_id = $_GET['id'];
$seat = (isset($_POST['seat']) ? $_POST['seat']:array());
if (is_array($seat)) {
foreach ($seat as $selectedOption){
$ar = explode('|',$selectedOption);
$query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, SEAT_PRICE, BOOKING_PRICE, BOOKING_NUM)
VALUES ('$user_id','$film_id','$session','$date','$ar[0]','$ar[1]','$total','$counter')";
$result = mysqli_query ($connection,$query)
or die ("<div class='alert alert-danger' role='alert'>You couldn't execute query</div>");
}
echo " <div class='alert alert-success' role='success'>
Congrats your booking has been done! Print the tickets <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
</div>";
}
}
?>
Related
Just for fun, I'm trying to build a simple time tracker; the page grabs a stored duration from a database, and you can then add more time to that value, and then store it back to the database.
The value is displayed in h:i:s format, but there's also a hidden span with the same time but just in seconds.
My problem:
I cannot figure out how to submit the contents of the span to the database.
If I instead put the hidden span contents inside a form input, then the content doesn't change; it just submits the original value back to the database.
I really feel like I'm making a bit of a meal out of this.
Here's the current code...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
//wip - for later - and remember to remove the injection!!!
if(sizeof($_POST) != 0){
$query = "UPDATE my_table SET t=SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$pdo->query($query);
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<div>
<div>
<span hidden id="tts"><?php echo $tts; ?></span>
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").text(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.querySelectorAll('div').forEach(div => {
div.querySelectorAll('span')
.forEach(span => console.log(span.textContent));
});
}
</script>
With CBroe's useful hint, the following works... although my attempts at preparing and binding $_GET are failing at the moment, so the query itself remains insecure...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
if(sizeof($_GET) != 0){
$query = "UPDATE my_table SET t = SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<form id="myForm">
<input name="tts" type= "hidden" id="tts" value="tts">
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").val(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
}
</script>
we are displaying Total commission by calculating with below formula
Total commission = commission * Number of Rows
for some rows we have value = "Returned or Cancelled".
if value = "Returned or Cancelled" , we don't want to count those rows for calculating commission.
for below image, now TC = 60, but we need 40 as 1st 2 rows have values Delivered & cancelled.
php
function getDesignerCollection()
{
foreach($order as $orderData)
{
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(":dorder_id" => $orderData['entity_id']));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
if($accountType == "admin")
{
$delivery_status='';
while($datas = $stmt1->fetch())
{
$delivery_status=$datas['delivery_status'];
if($datas['delivery_status']=='P'){$delivery_status='Pending';}
if($datas['delivery_status']=='D'){$delivery_status='Delivered';}
if($datas['delivery_status']=='R'){$delivery_status='Returned';}
if($datas['delivery_status']=='C'){$delivery_status='Cancelled';}
}
$stmt = $user_home->runQuery("SELECT commission1 FROM tbl_users where userID=:uid");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$commission = $row['commission1'] ;
$responce[] = array(
$commission,
$delivery_status,
);
}
script
$(".delete_grid").append("Number of rows : "+mygrid.dataset.getSize());
// Total Commission
var numRows=mygrid.dataset.getSize();
var commission =(mygrid.dataset.data[0][8]);
var total_commission=numRows * commission;
$(".delete_grid").append(" , Total commission : "+total_commission);
var __TEST_DATA__=eval('<?php
echo getDesignerCollection(); ?>');
var grid_demo_id = "myGrid" ;
var dsOption= {
fields :[
{name : 'commission1' },
{name : 'delivery_status' },
],
recordType : 'array',
data : __TEST_DATA__
}
var colsOption = [
{id: 'commission1' , header: "commission1" , width :"80"},
{id: 'delivery_status' , header: "Deliver Status" , width :"130"},
];
var commission=0;
for (var i = 0; i < mygrid.dataset.data.length; i++) {
console.log(mygrid.dataset.data[i]);
if(mygrid.dataset.data[i][10] != "Returned" && mygrid.dataset.data[i][10] != "Cancelled"){
commission=commission+parseInt(mygrid.dataset.data[i][8]);
}
console.log(commission);
}
$(".delete_grid").append(" , Total commission : "+commission);
Use a variable in php as given below
$delivery_status='';
$count = 0;
while($datas = $stmt1->fetch())
{
$delivery_status=$datas['delivery_status'];
if($datas['delivery_status']=='P'){$delivery_status='Pending'; }
if($datas['delivery_status']=='D'){$delivery_status='Delivered'; }
if($datas['delivery_status']=='R'){$delivery_status='Returned'; }
if($datas['delivery_status']=='C'){$delivery_status='Cancelled'; }
if($datas['delivery_status'] != 'R' && $datas['delivery_status'] != 'C'){
$count++;
}
}
Now you can count your totalCommission as
$totalCommission = $count * $commission
Trying to build a commenting system. Were comments are posted with AJAX. With comment count with Pagination. I have success achieving both, but putting them together is another story. I have tried doing 2 ajax calls. One for getting records from the database and showing pagination. The other call for recording records to the database.
// this is the first ajax call to to get the results and show pagination buttons
<script>
function request_page(pn){
var two = <?php echo $img_id; ?>;
var showmax = <?php echo SHOWMAX; ?>; // results per page
var totalpages = <?php echo $totalpages; ?>;
//controls for pigmintation
var pagination_controls = document.getElementById("pagination_controls");
var results_box = document.getElementsByClassName(two)[0];
params = 'showmax=' + showmax + '&totalpages=' + totalpages + '&pn=' + pn + '&img_id=' + two;
request = new ajaxRequest()
request.open("POST", "response5.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
results_box.innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(totalpages != 1)
{
if( pn > 1){
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+totalpages+'</b> ';
if (pn != totalpages) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
<script> request_page(<?php echo $totalpages; ?>); </script>
/// the response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$curPage = (int) sanitizeString($_POST['pn']);
$showmax = (int) sanitizeString($_POST['showmax']);
$totalpages = (int) sanitizeString($_POST['totalpages']);
$z = (int) sanitizeString($_POST['img_id']);
if ($curPage < 1) {
$curPage = 1;
} else if ($curPage > $totalpages) {
$curPage = $totalpages;
}
$offset = ($curPage-1) * $showmax;
// var_dump($showmax);
$one = $showmax;
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
//fetch resuls
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
////ajax call # 2 is triggered when ever the comment form is submitted
<div>
<form method='post' id="form<?php echo $img_id; ?>" name="<?php echo $img_id; ?>">
<textarea class='lake' name='one' placeholder="Comment" id='<?php echo $img_id; ?>'></textarea>
<input id="submit" onclick="showUser(document.getElementById(<?php echo $img_id; ?>).value, <?php echo $img_id; ?>);" type="button" value="Submit">
</form>
</div>
//// the ajax call function
function showUser(a, b){
name = a;
two = b;
yes = "form" + two;
params = 'name1=' + name + '&two1=' + two;
request = new ajaxRequest()
request.open("POST", "response10.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementsByClassName(two)[0].innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(params)
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
document.getElementById(yes).reset();
return false;
}
The response
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
define('SHOWMAX', 5);
$q = sanitizeString($_POST['name1']);
$z = sanitizeString($_POST['two1']);
$b = sanitizeString($_SESSION['user_id']);
$sql = 'INSERT INTO img_comment (img_id, comment, user_id)
VALUES(:img_id, :comment, :user_id)';
// prepare the statement
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':img_id', $z, PDO::PARAM_INT);
$stmt->bindParam(':comment', $q, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $b, PDO::PARAM_INT);
$stmt->execute();
$OK = $stmt->rowCount();
$getCount = 'SELECT COUNT(*) FROM img_comment WHERE img_id ='. $z;
// submit query and store result as $totalPix
$total = $pdo->query($getCount);
$totalCount = $total->fetchColumn();
// var_dump($totalCount);
$total = (int)$totalCount;
$totalpages = (int) ceil($total/ SHOWMAX);
$offset = ($totalpages-1) * SHOWMAX;
$one = SHOWMAX;
if($totalCount > 0){
$getcomments = "SELECT I.comment, I.created, U.user_pic_path, U.user_id, U.username, G.file_name
FROM users U
INNER JOIN img_comment I
ON I.img_id = ?
LEFT OUTER JOIN gallery G
ON G.img_id = U.user_pic_path
WHERE I.user_id = U.user_id
ORDER BY UNIX_TIMESTAMP(created) ASC
LIMIT ?, ?";
$stmt = $pdo->prepare($getcomments);
$stmt->bindParam(1, $z, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->bindParam(3, $one, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch()){
echo "<div class='chat-entry users person triggerProfile'>";
$bulls = get_web_path($row['user_pic_path']);
if(isset($row['file_name']))
{
$done32 = "http://localhost/new11/users/{$row['username']}/thumbs/{$row['file_name']}";
}else
{
$done32 = 'http://localhostnew11/users/noimage.jpg';
}
$bulls = get_web_path($row['file_name']);
echo "<a class='head users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>
<img class='imgcom' src='$done32'>
</a>
<div class='body'>
<div class='basic'>
<span class='username'>
<a class='users' href='http://localhost/new11/scripts/show_user_01.php?user_id={$row['user_id']}'>{$row['username']} </a>
</span>
</div>
<div class='message'>{$row['comment']}
</div>
</div>
</div>";
}
}
}
I an using Javascript when click add button to show multiple text box. but i don't how to store these text box values in database table single column. here i attached my form input coding and javascript for add number of textbox. after submit my form it stores somthing like Array into my table.
<?php
if(isset($_POST['submit']))
{
Include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
$count = $_POST['count'];
for($i = 0 ; $i < $count ; $i++)
{
//$count++;
$routesmore = $_POST['routes_more'];
$routesmore2 = explode('.', $routesmore[0]);
}
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$routesmore2', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
my input box:
<div class="col-lg-8" id="img_upload">
<!-- <input type="text" id="file0" name="routes" style="background:none;width:185px;"> -->
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;width:100px;" id="add_img_btn" class="btn btn-primary">Add Route</a></p>
<input type="hidden" id="aid" value="1">
<input type="hidden" id="count" name="count" value="0">
My Javascript:
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more"+count_id+"' id='file"+count_id_new+"' /></fieldset>  <a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change In JS - Append routes_more[] in jQuery("#divTxt").append in place of routes_more'+count+'.
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more[]' id='file"+count_id_new+"' /></fieldset>  <a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change in PHP Code - Find total count of routes_more textbox. And do accordingly. (No Need of checking how much count was there in your html code.)
<?php
if(isset($_POST['submit']))
{
include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
//For Routes More
$totalRoutesCount = sizeof($_POST['routes_more']);
$totalRoutes="";
for($i=0;$i<$totalRoutesCount;$i++)
{
$totalRoutes = $totalRoutes.$routesmore[$i].",";
}
$totalRoutes = rtrim($totalRoutes, ',');
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$totalRoutes', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
HTML :
<input type="text"
id="file0" name="routes[]"
style="background:none;width:185px;">
PHP:
INSERT Query:
'routes'(BD column) = serialize( $post['routes'] );
Display Time:
unserialize the column routes and print with foreach loop
I am a beginner in programming and i have a java script function that sends the variables of a form to a php script.
In the form i have two tables that hold two dropdowns each.
I can click the plus button to clone the first table row and i can click delete to remove the clones.
The max amount that can be generated is limited to 3 for nativelang and to 6 for practlang.
I have set all the variables that can be generated in the php and the javascript already and if i generate the max amount then it all works fine.
But if i don't generate any or just a few then the ajax.send is not doing anything, actually the form button stops working.
I suspect it is because of the expected data from the already declared variables that are empty because i didn't generate the drop downs.
This is the code that might cause the problem:
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
and this error is returned:
Uncaught TypeError: Cannot read property 'value' of nullsignup.php:954 signupsignup.php:893 onclick
How can i make it send the field even if its empty? or is it the php code?
I assumed the php would just save the fields that hold data and if a variable has no data then it is just saved as empty into the database right?
So thats why i thought it must be the javascript.
Would be super great if someone could help me to make this work :)
Sign up script:
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var ct = _("city").value;
var nl = _("nativelang").value;
var nll = _("nlanglevel").value;
var nl0 = _("nativelang0").value;
var nll0 = _("nlanglevel0").value;
var nl1 = _("nativelang1").value;
var nll1 = _("nlanglevel1").value;
var nl2 = _("nativelang2").value;
var nll2 = _("nlanglevel2").value;
var pl = _("practlang").value;
var pll = _("planglevel").value;
var pl0 = _("practlang0").value;
var pll0 = _("planglevel0").value;
var pl1 = _("practlang1").value;
var pll1 = _("planglevel1").value;
var pl2 = _("practlang2").value;
var pll2 = _("planglevel2").value;
var pl3 = _("practlang3").value;
var pll3 = _("planglevel3").value;
var pl4 = _("practlang4").value;
var pll4 = _("planglevel4").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || ct == "" || nl == "" || pl == ""){
status.innerHTML = "Fill out all of the form fields marked with a star";
} else if(p1 != p2){
status.innerHTML = "Your passwords do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'Email has been sent!';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.trim()!= "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "<div id=\"status\">OK "+u+", <h2>check your email</h2> inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully <h2>activate your account!</h2></div>";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
}
}
Script for the buttons that add or delete rows in the table(table holds dropdowns):
var ncount = -1;
$(document).ready(function(){
$('#addBtnNative').on('click', function(e){
if($('.nativelangdrop').length < 4) {
ncount++;
var initialn_row = $('tr.initialn').first().clone();
var nativelang_name = initialn_row.find('td:eq(0) select').attr('name'); // first td select
var nlanglevel_name = initialn_row.find('td:eq(1) select').attr('name'); // second td select
initialn_row.find('td:eq(0) select').attr('name', nativelang_name + ncount);
initialn_row.find('td:eq(1) select').attr('name', nlanglevel_name + ncount);
var nativelang_id = initialn_row.find('td:eq(0) select').attr('id'); // first td select
var nlanglevel_id = initialn_row.find('td:eq(1) select').attr('id'); // second td select
initialn_row.find('td:eq(0) select').attr('id', nativelang_id + ncount);
initialn_row.find('td:eq(1) select').attr('id', nlanglevel_id + ncount);
$('table.nativelanguages').append(initialn_row);
}
});
});
$(document).ready(function(){
$('#remBtnNative').on('click', function(e){
if($('.nativelangdrop').length > 1) {
ncount--;
var initialn_row = $('tr.initialn').last().remove();
}
});
});
var pcount = -1;
$(document).ready(function(){
$('#addBtnPract').on('click', function(e){
if($('.practlangdrop').length < 6) {
pcount++;
var initialp_row = $('tr.initialp').first().clone();
var practlang_name = initialp_row.find('td:eq(0) select').attr('name'); // first td select
var planglevel_name = initialp_row.find('td:eq(1) select').attr('name'); // second td select
initialp_row.find('td:eq(0) select').attr('name', practlang_name + pcount);
initialp_row.find('td:eq(1) select').attr('name', planglevel_name + pcount);
var practlang_id = initialp_row.find('td:eq(0) select').attr('id'); // first td select
var planglevel_id = initialp_row.find('td:eq(1) select').attr('id'); // second td select
initialp_row.find('td:eq(0) select').attr('id', practlang_id + pcount);
initialp_row.find('td:eq(1) select').attr('id', planglevel_id + pcount);
$('table.practlanguages').append(initialp_row);
}
});
});
$(document).ready(function(){
$('#remBtnPract').on('click', function(e){
if($('.practlangdrop').length > 1) {
pcount--;
var initialp_row = $('tr.initialp').last().remove();
}
});
});
PHP:
if(isset($_POST["u"])){
include_once("php_includes/db_conx.php");
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
$ct = $_POST['ct'];
$nl = preg_replace('#[^a-z]#', '', $_POST['nl']);
$nll = preg_replace('#[^a-z]#', '', $_POST['nll']);
$nl0 = preg_replace('#[^a-z]#', '', $_POST['nl0']);
$nll0 = preg_replace('#[^a-z]#', '', $_POST['nll0']);
$nl1 = preg_replace('#[^a-z]#', '', $_POST['nl1']);
$nll1 = preg_replace('#[^a-z]#', '', $_POST['nll1']);
$nl2 = preg_replace('#[^a-z]#', '', $_POST['nl2']);
$nll2 = preg_replace('#[^a-z]#', '', $_POST['nll2']);
$pl = preg_replace('#[^a-z]#', '', $_POST['pl']);
$pll = preg_replace('#[^a-z]#', '', $_POST['pll']);
$pl0 = preg_replace('#[^a-z]#', '', $_POST['pl0']);
$pll0 = preg_replace('#[^a-z]#', '', $_POST['pll0']);
$pl1 = preg_replace('#[^a-z]#', '', $_POST['pl1']);
$pll1 = preg_replace('#[^a-z]#', '', $_POST['pll1']);
$pl2 = preg_replace('#[^a-z]#', '', $_POST['pl2']);
$pll2 = preg_replace('#[^a-z]#', '', $_POST['pll2']);
$pl3 = preg_replace('#[^a-z]#', '', $_POST['pl3']);
$pll3 = preg_replace('#[^a-z]#', '', $_POST['pll3']);
$pl4 = preg_replace('#[^a-z]#', '', $_POST['pl4']);
$pll4 = preg_replace('#[^a-z]#', '', $_POST['pll4']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
if($u == "" || $e == "" || $p == "" || $g == "" || $c == "" || $ct == "" || $nl == "" || $pl == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 25) {
echo "Username must be between 3 and 25 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
$p_hash = md5($p);
$sql = "INSERT INTO users (username, email, password, gender, country, city, nativelang, nlanglevel, nativelang0, nlanglevel0, nativelang1, nlanglevel1, nativelang2, nlanglevel2, practlang, planglevel, practlang0, planglevel0, practlang1, planglevel1, practlang2, planglevel2, practlang3, planglevel3, practlang4, planglevel4, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ct','$nl','$nll','$nl0','$nll0','$nl1','$nll1','$nl2','$nll2','$pl','$pll','$pl0','$pll0','$pl1','$pll1','$pl2','$pll2','$pl3','$pll3','$pl4','$pll4','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
$to = "$e";
$from = "email#site.com";
$subject = 'blah | Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title> Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;">Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
HTML:
<legend class="legend"><h3>Select your languages</h3></legend>
<ul class="list-unstyled">
<li>
<div class="lala">
<table class="nativelanguages">
<tr>
<td>Spoken language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialn">
<td>
<select class="nativelangdrop" id="nativelang" name="nativelang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select></td>
<td>
<select class="langleveldrop" id="nlanglevel" name="nlanglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnNative">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnNative">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
<div class="lala">
<table style="float:left; margin-top:20px;" id="plang" class="practlanguages">
<tr>
<td>Practicing language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialp">
<td>
<select class="practlangdrop" id="practlang" name="practlang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
<td><select class="langleveldrop" id="planglevel" name="planglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnPract">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnPract">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
</li>
</ul>
Where you get your element values, try changing them to like this:
var u = _("username").value ? _("username").value : '';
This uses a Ternary Operator to set the value of u.
The syntax is: condition ? result-if-True : result-if-False;
Basically, this says, if _("username").value returns a value, assign that value to u, if not, set the value of u to "" (an empty string)
Below is a contrived example using regular jQuery method $("#username").val() I imagine it will also work with _("username").value though Im not sure what the benefit of doing _("username").value is having never seen this before myself.
var u = $("#username").val() ? $("#username").val() : 'not found';
alert(u);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I suggest to use chrome developer tools so you can see what jquery.ajax send
https://developer.chrome.com/devtools#improving-network-performance
in php, you can see what are incoming using
print_r($_POST)
and
print_r($_GET)