How do i make the headings of table align to the content? - javascript

I am a beginner to appscript. I am developing a payment system where user can see their payment history and can pay their payment. But for now after I have made some changes to my code, after that the content and headings wont get aligned together, so Im now seeking for some help from you guys. I have included the link to my appscript and some images to explain my self better. Thank you so much
Code.gs
var url = "https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006";
var streetSheetName = "JALAN SANGGUL 4";
function doGet(e) {
var streetSheetName = "JALAN SANGGUL 4"; // Added
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
return HtmlService.createHtmlOutputFromFile('WebAppLogin')
.setTitle("Resident Payment");
}
function checkLogin(username, password) {
var found_record = '';
var name = '';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("USERNAMES");
var getLastRow = webAppSheet.getLastRow();
for(var i = 2; i <= getLastRow; i++) {
if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == username.toUpperCase() && webAppSheet.getRange(i, 7).getValue() == password) {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
} else if (username.toUpperCase() == 'ADMIN' && password == 'ADMINPASSWORD') {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
}
}
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
if(found_record == '') {
found_record = 'FALSE';
}
return [found_record, username,name];
}
function GetRecords(username,filter) {
var filteredDataRangeValues = GetUsernameAssociatedProperties(username);
var resultArray = GetPaymentRecords(filteredDataRangeValues,filter);
var resultFilter = getYears();
result = {
data: resultArray,
filter: resultFilter
};
return result;
}
function getYears() {
var ss= SpreadsheetApp.openByUrl(url);
var yearSheet = ss.getSheetByName("Configuration");
var getLastRow = yearSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if(return_array.indexOf(yearSheet.getRange(i, 2).getDisplayValue()) === -1) {
return_array.push(yearSheet.getRange(i, 2).getDisplayValue());
}
}
return return_array;
}
function changePassword(username, newPassword) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("USERNAMES");
var range = sheet.getRange("A2:A").createTextFinder(username).matchEntireCell(true).findNext();
if (range) {
range.offset(0, 6).setValue(newPassword);
}
}
function GetUsernameAssociatedProperties(username) {
var filteredDataRangeValues = '';
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName("USERNAMES");
var dataRangeValues = displaySheet.getDataRange().getValues();
if (username.toUpperCase() == 'ADMIN') {
dataRangeValues.shift();
filteredDataRangeValues = dataRangeValues;
} else {
filteredDataRangeValues = dataRangeValues.filter(row => row[0].toUpperCase() == username.toUpperCase());
}
return filteredDataRangeValues;
}
function GetPaymentRecords(userProperties,filter) {
var streetSheetName = PropertiesService.getScriptProperties().getProperty("streetSheetName"); // Added
var transpose = m => m[0].map((_, i) => m.map(x => x[i]));
var resultArray = [];
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName(streetSheetName);
var addressValues = displaySheet.getRange("B:C").getValues();
var paidMonthValues = displaySheet.getRange(1, 7, displaySheet.getLastRow(), displaySheet.getLastColumn() - 6).getValues();
//Logger.log(addressValues);
//Logger.log(transpose(paidMonthValues));
userProperties.forEach((v, i) => {
var userHouseNumber = v[1];
var userStreet = v[2];
var column = addressValues.reduce(function callbackFn(accumulator, currentValue, index, array) {
if (currentValue[0] == userHouseNumber && currentValue[1] == userStreet) {
return index
} else {
return accumulator
}
}, '');
//Logger.log(column);
Logger.log(filter)
Logger.log(paidMonthValues);
if(filter=="None"){
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}else{
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
if(element[0].includes(filter))return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}
resultArray = resultArray.concat(result);
//Logger.log(resultArray);
})
//Remove null elements
resultArray = resultArray.filter(element=>{
Logger.log(element!=null)
return element != null;
});
return resultArray;
}
WebAppLogin.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
console.log(output);
var username = output[1];
var name = output[2];
if(output[0] == 'TRUE') {
document.getElementById("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("errorMessage").innerHTML = "";
document.getElementById("currentUser").value = name; // CHANGE
google.script.run.withSuccessHandler(displayTable).GetRecords(username,"None");
} else if(output[0] == 'FALSE') {
document.getElementById("firstLastName").innerHTML = "";
document.getElementById("currentUser").value = "";
document.getElementById("myFilter").innerHTML = "";
document.getElementById("errorMessage").innerHTML = "Failed to Login";
document.getElementById("LoginButton").innerHTML = "Login";
}
}).checkLogin(username, password);
}
function filter(){
var filterStr = document.getElementById("filterYear").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(username, filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
ar = ar.sort((a, b) => new Date(a).getTime() > new Date(b).getTime() ? -1 : 1).splice(-12); // <--- Added
var name = document.getElementById("currentUser").value; // CHANGE
if(ar.length > 0) {
var displayTable = '<table class=\"table\" id=\"mainTable\">';
displayTable += "<tr>";
displayTable += "<th>Month</th>";
displayTable += "<th>House Number</th>";
displayTable += "<th>Street</th>";
displayTable += "<th>Payment Status</th>";
displayTable += "</tr>";
ar.forEach(function(item, index) {
displayTable += "<tr>";
displayTable += "<td>"+item[0]+"</td>";
displayTable += "<td>"+item[1]+"</td>";
displayTable += "<td>"+item[2]+"</td>";
displayTable += "<td>"+item[3]+"</td>";
displayTable += "</tr>";
});
displayTable += "</table>";
} else {
var displayTable = "<span style=\"font-weight: bold\" >No Records Found</span>";
}
var filter = '';
if(filterString.length > 0) {
filter += '<label for="years" style="font-size: 20px">Select the Year</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option>';
filterString.filter(String).forEach(str => {
filter += '<option value="'+str+'">'+str+'</option>';
});
filter += '</select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
}
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
if (!ar.some(([a,,,d]) => {
var t = new Date(a);
return year == t.getFullYear() && month == t.getMonth() && d.toUpperCase() == "PAID";
})) {
document.getElementById("digitalgoods-030521182921-1").style.display = "block";
}
document.getElementById("displayRecords").innerHTML = displayTable;
document.getElementById("firstLastName").innerHTML = "USER: " + name;
document.getElementById("myFilter").innerHTML = filter;
document.getElementById("LoginButton").innerHTML = "Login";
document.getElementById("username").value = '';
document.getElementById("password").value = '';
}
//change the link according to ur webapp latest version
function LogOut(){
window.open("https://script.google.com/macros/s/AKfycbwKa4sQ441WUIqmU40laBP0mfiqNMiN-NghEvwUnJY/dev",'_top');
}
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
</script>
</head>
<body>
<style>
h2 {text-align: center;}
div {text-align: center;}
.col-centered{margin: 0 auto;float: none;}
</style>
<h2> Resident Payment Status Portal</h2>
</div>
<div id="loginDisplay" style="padding: 10px">
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>User Name</label>
<input type="text" id="username" class="form-control" required/>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>Password</label><br>
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<hr>
<button class="btn btn-primary" type="button" id="LoginButton" onclick="GetRecords()" >
Login
</button>
<span id="errorMessage" style="color: red" ></span>
</div>
<hr>
<div style="display:none" id="dataDisplay">
<div>
<h2 id="firstLastName"></h2>
</div>
<input type="hidden" id="currentUser" value=""/>
<div style="width:1200px;margin:0 auto;">
<div id ="myFilter" class="form-group"></div>
<hr>
<div id="displayRecords" style="padding: 10px;" ></div>
<!----Paypal Button-------->
<hr>
<div style="width:500px;margin:0 auto;">
<div id="digitalgoods-030521182921-1" style="display: none;"></div>
<script>(function (div, currency) {var item_total = {currency_code: currency,value: '50.00',},tax_total = {currency_code: currency,value: '0.00' },render = function () {window.paypal.Buttons({createOrder: function (data, actions) {return actions.order.create({application_context: {brand_name: "",landing_page: "BILLING",shipping_preference: "NO_SHIPPING",payment_method: {payee_preferred: "UNRESTRICTED"}},purchase_units: [{description: "",soft_descriptor: "digitalgoods",amount: {breakdown: {item_total: item_total,tax_total: tax_total},value: '50.00' },items: [{name: "Monthly Fees",quantity: 1,description: "",sku: "1",unit_amount: item_total,tax: tax_total}]}]});},onApprove: function (data, actions) {return actions.order.capture().then(function (details) {div.innerHTML = "Order completed. You\x27ll receive an email shortly!";});},onCancel: function (data) {},onError: function (err) {div.innerHTML = "<pre>" + err.toString()}}).render("#digitalgoods-030521182921-1");},init = function () {window.digitalgoods = window.digitalgoods || [];window.digitalgoods.push(render);var file = "https://www.paypal.com/sdk/js?client-id=AS-86gVX_DfakSkq6YZDJRdKZb4SMIziOd5c9DIKy4extQrpb0VFEprDleB_duKI4BJQQRewUdfliZEf\x26currency=MYR";var script = document.createElement("script");script.type = "text/javascript";script.src = file;script.onload = function() {var i = window.digitalgoods.length;while (i--) {window.digitalgoods[i]();}};div.appendChild(script);};init();})(document.getElementById("digitalgoods-030521182921-1"), "MYR");</script>
</div>
<!-----Change Password----------->
<div>
<!--<button type="button" class="btn btn-primary btn-md" onclick="changePassword()">Change Password</button>-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Change Password
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLongTitle">Change Password</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter New Password</label><br>
<input type="password" id="newPassword" class="form-control" required/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="changePassword()">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<hr>
<!-----Log Out----------->
<div>
<button type="button" class="btn btn-default btn-md" onclick="LogOut()">
<span class="glyphicon glyphicon-log-out"></span> Log out
</button>
</div>
</div>
</body>
</html>

Can you put this code in WebAppLogin.html
<!DOCTYPE html>
<html>
<head>
</style>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
console.log(output);
var username = output[1];
var name = output[2];
if(output[0] == 'TRUE') {
document.getElementById("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("errorMessage").innerHTML = "";
document.getElementById("currentUser").value = name; // CHANGE
google.script.run.withSuccessHandler(displayTable).GetRecords(username,"None");
} else if(output[0] == 'FALSE') {
document.getElementById("firstLastName").innerHTML = "";
document.getElementById("currentUser").value = "";
document.getElementById("myFilter").innerHTML = "";
document.getElementById("errorMessage").innerHTML = "Failed to Login";
document.getElementById("LoginButton").innerHTML = "Login";
}
}).checkLogin(username, password);
}
function filter(){
var filterStr = document.getElementById("filterYear").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(username, filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
ar = ar.sort((a, b) => new Date(a).getTime() > new Date(b).getTime() ? -1 : 1).splice(-12); // <--- Added
var name = document.getElementById("currentUser").value; // CHANGE
if(ar.length > 0) {
var displayTable = '<table class=\"table\" id=\"mainTable\">';
displayTable += "<tr>";
displayTable += '<th style=\"text-align: center;\">Month</th>';
displayTable += '<th style=\"text-align: center;\">House Number</th>';
displayTable += '<th style=\"text-align: center;\">Street</th>';
displayTable += '<th style=\"text-align: center;\">Payment Status</th>';
displayTable += "</tr>";
ar.forEach(function(item, index) {
displayTable += "<tr>";
displayTable += "<td>"+item[0]+"</td>";
displayTable += "<td>"+item[1]+"</td>";
displayTable += "<td>"+item[2]+"</td>";
displayTable += "<td>"+item[3]+"</td>";
displayTable += "</tr>";
});
displayTable += "</table>";
} else {
var displayTable = "<span style=\"font-weight: bold\" >No Records Found</span>";
}
var filter = '';
if(filterString.length > 0) {
filter += '<label for="years" style="font-size: 20px">Select the Year</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option>';
filterString.filter(String).forEach(str => {
filter += '<option value="'+str+'">'+str+'</option>';
});
filter += '</select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
}
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
if (!ar.some(([a,,,d]) => {
var t = new Date(a);
return year == t.getFullYear() && month == t.getMonth() && d.toUpperCase() == "PAID";
})) {
document.getElementById("digitalgoods-030521182921-1").style.display = "block";
}
document.getElementById("displayRecords").innerHTML = displayTable;
document.getElementById("firstLastName").innerHTML = "USER: " + name;
document.getElementById("myFilter").innerHTML = filter;
document.getElementById("LoginButton").innerHTML = "Login";
document.getElementById("username").value = '';
document.getElementById("password").value = '';
}
//change the link according to ur webapp latest version
function LogOut(){
window.open("https://script.google.com/macros/s/AKfycbwKa4sQ441WUIqmU40laBP0mfiqNMiN-NghEvwUnJY/dev",'_top');
}
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
</script>
</head>
<body>
<style>
h2 {text-align: center;}
div {text-align: center;}
.col-centered{margin: 0 auto;float: none;}
</style>
<h2> Resident Payment Status Portal</h2>
</div>
<div id="loginDisplay" style="padding: 10px">
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>User Name</label>
<input type="text" id="username" class="form-control" required/>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3" style="margin:0 auto">
<label>Password</label><br>
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<hr>
<button class="btn btn-primary" type="button" id="LoginButton" onclick="GetRecords()" >
Login
</button>
<span id="errorMessage" style="color: red" ></span>
</div>
<hr>
<div style="display:none" id="dataDisplay">
<div>
<h2 id="firstLastName"></h2>
</div>
<input type="hidden" id="currentUser" value=""/>
<div style="width:1200px;margin:0 auto;">
<div id ="myFilter" class="form-group"></div>
<hr>
<div id="displayRecords" style="padding: 10px;" ></div>
<!----Paypal Button-------->
<hr>
<div style="width:500px;margin:0 auto;">
<div id="digitalgoods-030521182921-1" style="display: none;"></div>
<script>(function (div, currency) {var item_total = {currency_code: currency,value: '50.00',},tax_total = {currency_code: currency,value: '0.00' },render = function () {window.paypal.Buttons({createOrder: function (data, actions) {return actions.order.create({application_context: {brand_name: "",landing_page: "BILLING",shipping_preference: "NO_SHIPPING",payment_method: {payee_preferred: "UNRESTRICTED"}},purchase_units: [{description: "",soft_descriptor: "digitalgoods",amount: {breakdown: {item_total: item_total,tax_total: tax_total},value: '50.00' },items: [{name: "Monthly Fees",quantity: 1,description: "",sku: "1",unit_amount: item_total,tax: tax_total}]}]});},onApprove: function (data, actions) {return actions.order.capture().then(function (details) {div.innerHTML = "Order completed. You\x27ll receive an email shortly!";});},onCancel: function (data) {},onError: function (err) {div.innerHTML = "<pre>" + err.toString()}}).render("#digitalgoods-030521182921-1");},init = function () {window.digitalgoods = window.digitalgoods || [];window.digitalgoods.push(render);var file = "https://www.paypal.com/sdk/js?client-id=AS-86gVX_DfakSkq6YZDJRdKZb4SMIziOd5c9DIKy4extQrpb0VFEprDleB_duKI4BJQQRewUdfliZEf\x26currency=MYR";var script = document.createElement("script");script.type = "text/javascript";script.src = file;script.onload = function() {var i = window.digitalgoods.length;while (i--) {window.digitalgoods[i]();}};div.appendChild(script);};init();})(document.getElementById("digitalgoods-030521182921-1"), "MYR");</script>
</div>
<!-----Change Password----------->
<div>
<!--<button type="button" class="btn btn-primary btn-md" onclick="changePassword()">Change Password</button>-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Change Password
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLongTitle">Change Password</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter New Password</label><br>
<input type="password" id="newPassword" class="form-control" required/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="changePassword()">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<hr>
<!-----Log Out----------->
<div>
<button type="button" class="btn btn-default btn-md" onclick="LogOut()">
<span class="glyphicon glyphicon-log-out"></span> Log out
</button>
</div>
</div>
</body>
</html>
Happy to help.
Thanks.

Related

My javascript can't read property of php database $row insert with innerText

I'm making an online shop for my school project and when I try to put a value of $row that is in my database I keep getting and error that says "Uncaught TypeError: Cannot read property innerText of undefined". The code should add the product to the cart, it works as intended on the HTML file, but not in the php file. I tried looking for a solution, but nothing worked. How can I fix this?
Here is the php code:
<?php
session_start();
?>
<html>
<head>
<title>Projekt</title>
<link rel="stylesheet" href="still.css">
</head>
<body>
<a name="home"></a>
<div class="header">
<div class="container">
<div class="navbar">
<div class="logo">
<img src="logo.png" width="125px">
</div>
<nav>
<ul>
<li><?php
if (isset($_SESSION['username'])){
print("<a href=logout.php>".$_SESSION['username']."</a>");
}
else{
print("<a href='login.php'>Login</a>");
}
?></li>
<li><?php
if (isset($_SESSION['username'])){
print("");
}
else{
print("<a href='register.php'>Register</a>");
}
?></li>
</ul>
</nav>
<img src="cart.png" width="30px" height="30px">
</div>
<div class="row">
<div class="col-2">
<h1>Basketball shop</h1>
</div>
<div class="col-2">
<img src="nba.png">
</div>
</div>
</div>
</div>
<div class="quick">
<ul>
<li>Shoes</li>
<li>Basketball</li>
<li>Jersey</li>
<li>Cart</li>
</ul>
</div>
<div class="cont2">
<h2 class="naslov">Shoes <a name="shoes"></a></h2>
<?php
$mysqli = mysqli_connect("localhost", "root", "", "shop"); // spajanje na server i bazu
if(!mysqli_connect_errno($mysqli)) { // provjera da li je bila greska
$br=1;
$znak="$";
$sql = "SELECT * FROM proizvodi";
// print($sql);
$result = mysqli_query($mysqli, $sql); // izvršavanje upita
if($result==True) {
if($mysqli->affected_rows==0) {
echo "Nema nijednog predmeta u bazi.";
} else {
print("<div class='row'>");
while($row = mysqli_fetch_assoc($result)) { // dohvat svakog retka iz $result
print("<div class='col-3'>
<a href='detalji.php?id={$row['id']}'><img class='cart-item-image' src='{$row['slika']}'/></a>
<h4 class='cart-item-title'>{$row['naziv']}</h4>
<p class='shop-item-price'>$znak{$row['cijena']}</p>
<input type='hidden' name='id' value={$row['id']}>
<button class='btn btn-primary shop-item-button'type='button'>ADD TO CART</button>
</div>");
$br++;
if($br==4){
print("</div>
<h2 class='naslov'>Basketball <a name='basketball'></a></h2>
<div class='row'>");
}
if($br==7){
print("</div>
<h2 class='naslov'>Jersey <a name='jersey'></a></h2>
<div class='row'>");
}
}
print("</div>");
mysqli_free_result($result); // oslobađanje memorije
}
} else {
print(" Upit je neuspješno izvršen! ");
}
} else {
print(" Greška kod spajanja na bazu! " . mysqli_connect_error());
}
?>
</div>
<div class="razmak"></div><a name="cart"></a>
<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-price cart-header cart-column">PRICE</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="warriors.jpg" width="100" height="100">
<span class="cart-item-title">Warriors</span>
</div>
<span class="cart-price cart-column">$25</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>
</div>
<div class="cart-row">
<div class="cart-item cart-column">
<img class="cart-item-image" src="uacurry7.jpg" width="100" height="100">
<span class="cart-item-title">Under Armour 7</span>
</div>
<span class="cart-price cart-column">$110</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="2">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>
</div>
</div>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> $245</span>
</div>
<button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>
</section>
</div>
</div><div class="footer">
<div class="container">
<h3 class="text">basketballshop.com</h3>
</div>
<script src="store.js"></script>
</body>
</html>
And here is javascript (Note: I'm new to javascript so I was making this code through youtube):
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
var quantityInputs = document.getElementsByClassName('cart-quantity-input')
for (var i = 0; i < quantityInputs.length; i++) {
var input = quantityInputs[i]
input.addEventListener('change', quantityChanged)
}
var addToCartButtons = document.getElementsByClassName('shop-item-button')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
alert('Thank you for your purchase')
var cartItems = document.getElementsByClassName('cart-items')[0]
while (cartItems.hasChildNodes()) {
cartItems.removeChild(cartItems.firstChild)
}
updateCartTotal()
}
function removeCartItem(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
updateCartTotal()
}
function quantityChanged(event) {
var input = event.target
if (isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
}
function addToCartClicked(event) {
var button = event.target
var shopItem = button.parentElement
var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
addItemToCart(title, price, imageSrc)
updateCartTotal()
}
function addItemToCart(title, price, imageSrc) {
var cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
var cartItems = document.getElementsByClassName('cart-items')[0]
var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
for (var i = 0; i < cartItemNames.length; i++) {
if (cartItemNames[i].innerText == title) {
alert('This item is already added to the cart')
return
}
}
var cartRowContents = `
<div class="cart-item cart-column">
<img class="cart-item-image" src="${imageSrc}" width="100" height="100">
<span class="cart-item-title">${title}</span>
</div>
<span class="cart-price cart-column">${price}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>`
cartRow.innerHTML = cartRowContents
cartItems.append(cartRow)
cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var total = 0
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total + (price * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}
The problem is at the function addToCartClicked(event) with the innerText property.
Hope you are doing well!
I figured out the following issue in your code hope this can help you with the issue you are facing. In your code you have
print("<div class='col-3'>
<a href='detalji.php?id={$row['id']}'><img class='cart-item-image' src='{$row['slika']}'/></a>
<h4 class='cart-item-title'>{$row['naziv']}</h4>
<p class='shop-item-price'>$znak{$row['cijena']}</p>
<input type='hidden' name='id' value={$row['id']}>
<button class='btn btn-primary shop-item-button'type='button'>ADD TO CART</button>
</div>");
here if you check in your PHP code you used class names that are
cart-item-title and cart-item-image
while in your javascript code you used this
shop-item-title and shop-item-image

Submit Button Not Changing Questions

I am building a cute webpage for my teacher (who's very fun) as a Christmas present, but whenever I enter text into the input box and submit any question past the first, the code marks it as incorrect. I thought I had fixed this problem when I changed the question submit, every time the question changes, but apparently not. Can someone tell me what I'm doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Funn Chunn | Quiz</title>
<link rel="icon" href="images/alabama logo.png"/>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body onload="firstQ();">
<div class='container'>
<div class='row'>
<h1 id='mainHeader'>Funn Chunn | Quiz</h1>
</div>
<div class='row'>
<h3 id='questionBox'></h3>
</div>
<div class='row'>
<form id="inputBoxOuter">
<input id='inputBox' type='text'></br>
<button class='btn btn-lg btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>
</form>
</div>
<div class='row'>
<form id="playAgainOuter">
</form>
</div>
<div class="row">
<p id="subText"></p>
</div>
<div class="row">
<div id="logoImgOuter"><img class="mx-auto" id="logoImg" src="images/alabama logo.png"/></div>
</div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
JavaScript
var mainHeaderJs = document.getElementById("mainHeader");
var questionBoxJs = document.getElementById("questionBox");
var inputBoxJs = document.getElementById("inputBox");
var inputBoxOuterJs = document.getElementById("inputBoxOuter");
var subTextJs = document.getElementById("subText");
var logoImgOuterJs = document.getElementById("logoImgOuter");
var playAgainOuter = document.getElementById("playAgainOuter");
var playerScore = 0;
function finalScore() {
mainHeaderJs.innerHTML = "You Got a Score of " + playerScore + " Out of 10";
playAgainOuter.innerHTML = "<button class='btn btn-lg btn-info mx-auto' id='playAgain' onclick='playAgain();'>Play Again</button>"
questionBoxJs.innerHTML = "";
inputBoxOuterJs.innerHTML = "";
}
function playAgain() {
mainHeaderJs.innerHTML = "Funn Chunn | Quiz";
firstQ();
playerScore = 0;
playAgainOuter.innerHTML = "";
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>";
}
function moveOnGood() {
subTextJs.innerHTML = "Correct! Moving on to the next question";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function moveOnBad() {
subTextJs.innerHTML = "Moving on to the next question...";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function firstQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 1: What is Mrs. Chunn's Favorite Team?";
}, 2000);
}
function firstQAnswer() {
var Q1Answer = inputBoxJs.value;
Q1Answer = Q1Answer.toUpperCase();
if (Q1Answer == "ALABAMA") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON TIDE") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
moveOnBad();
secondQ();
}
}
function secondQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 2: Is Mrs. Chunn a Millenial?";
}, 2000);
}
function secondQAnswer() {
var Q2Answer = inputBoxJs.value;
Q2Answer = Q2Answer.toUpperCase();
if (Q2Answer == "YES") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "YEAH") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "Y") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswerAlt();'>Enter</button>";
moveOnBad();
thirdQ();
}
}
This isn't the best solution, but its one that should work. Just initialize inputBoxjs = ''; and update inputBoxjs at the start of every question function.
So change
var inputBoxJs = document.getElementById("inputBox");
to
var inputBoxJs = '';
and add this line
inputBoxJs = document.getElementById("inputBox");
above your Q1Answer and Q2Answer variables.
Then just add your thirdQ function and variables after you're finished with your Q2 functions.
Hopefully this helps.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Funn Chunn | Quiz</title>
<link rel="icon" href="images/alabama logo.png"/>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body onload="firstQ();">
<div class='container'>
<div class='row'>
<h1 id='mainHeader'>Funn Chunn | Quiz</h1>
</div>
<div class='row'>
<h3 id='questionBox'></h3>
</div>
<div class='row'>
<form id="inputBoxOuter">
<input id='inputBox' type='text'> <br/>
<button class='btn btn-lg btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>
</form>
</div>
<div class='row'>
<form id="playAgainOuter">
</form>
</div>
<div class="row">
<p id="subText"></p>
</div>
<div class="row">
<div id="logoImgOuter"><img class="mx-auto" id="logoImg" src="images/alabama logo.png"/></div>
</div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
<script>
var mainHeaderJs = document.getElementById("mainHeader");
var questionBoxJs = document.getElementById("questionBox");
var inputBoxJs = '';
var inputBoxOuterJs = document.getElementById("inputBoxOuter");
var subTextJs = document.getElementById("subText");
var logoImgOuterJs = document.getElementById("logoImgOuter");
var playAgainOuter = document.getElementById("playAgainOuter");
var playerScore = 0;
function finalScore() {
mainHeaderJs.innerHTML = "You Got a Score of " + playerScore + " Out of 10";
playAgainOuter.innerHTML = "<button class='btn btn-lg btn-info mx-auto' id='playAgain' onclick='playAgain();'>Play Again</button>"
questionBoxJs.innerHTML = "";
inputBoxOuterJs.innerHTML = "";
}
function playAgain() {
mainHeaderJs.innerHTML = "Funn Chunn | Quiz";
firstQ();
playerScore = 0;
playAgainOuter.innerHTML = "";
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>";
}
function moveOnGood() {
subTextJs.innerHTML = "Correct! Moving on to the next question";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function moveOnBad() {
subTextJs.innerHTML = "Moving on to the next question...";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function firstQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 1: What is Mrs. Chunn's Favorite Team?";
}, 2000);
}
function firstQAnswer() {
inputBoxJs = document.getElementById("inputBox");
var Q1Answer = inputBoxJs.value;
Q1Answer = Q1Answer.toUpperCase();
if (Q1Answer == "ALABAMA") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON TIDE") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
moveOnBad();
secondQ();
}
}
function secondQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 2: Is Mrs. Chunn a Millenial?";
}, 2000);
}
function secondQAnswer() {
inputBoxJs = document.getElementById("inputBox");
var Q2Answer = inputBoxJs.value;
Q2Answer = Q2Answer.toUpperCase();
if (Q2Answer == "YES") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "YEAH") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "Y") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswerAlt();'>Enter</button>";
moveOnBad();
thirdQ();
}
}
</script>

PHP undefined index and file_get_contents(): Filename cannot be empty

I get these following errors
Notice: Undefined index: imgupload in
C:\xampp\htdocs\cdrrmo\includes\newsfeed.inc.php on line 9
Warning: file_get_contents(): Filename cannot be empty in
C:\xampp\htdocs\cdrrmo\includes\newsfeed.inc.php oI line 9
I want to save the photo in my database, although I get the mentioned errors, the other values are accepted and stored in my database:
if (isset($_POST['send'])){
include_once 'includes/dbh.inc.php';
$_SESSION['location'] = mysqli_real_escape_string($conn, $_POST['location']);
$_SESSION['message'] = mysqli_real_escape_string($conn, $_POST['message']);
$file = addslashes(file_get_contents($_FILES["imgupload"]["tmp_name"]));
//insert the user into the database
$sql = "INSERT INTO newsfeed (user_email,user_uid,user_location, user_message,user_attachment) VALUES ('{$_SESSION['u_email']}','{$_SESSION['u_uid']}','{$_SESSION['location']}', '{$_SESSION['message']}','$file');";
if(mysqli_query($conn, $sql)){
echo "Event has been reported!";
exit();
}?>
<form action="includes/newsfeed.inc.php" method="POST">
<br><br><br><br>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Location</label>
<input type="text" name="location" class="form-control" placeholder="Press 'Get Geolocation'" id="location" required readonly="readonly"><p id="demo1"></p>
<center><button type="button" onclick="getLocation();" required>Get Geolocation</button></center>
<script>
var x = document.getElementById("demo1");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("location").value = position.coords.latitude + ',' + position.coords.longitude;
}
</script>
</div>
</div>
</div>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12"">
<label for="name">Message</label>
<textarea name="message" class="form-control" placeholder="Message" id="message" rows="15" required></textarea>
</div>
</div>
</div>
</form>
<br>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Upload Image</label><br>
<form method="post" enctype="multipart/form-data">
<div class="container">
<p><div class="fileUpload btn btn-primary">
<form action="" method="post" enctype="multipart/form-data">
<span>+</span>
<input type="file" class="upload" name="imgupload" id="imgupload" multiple="multiple">
<br />
</form>
</div><a id="imgpreview"></a></p>
<button class="btn btn-primary" name="send" id="send">POST</button>
</div>
</form>
</div>
</div>
</div>
<!-- script of upload photo -->
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#imgupload').on('change', function(){
var imgItem = $(this)[0].files;
var imgCount = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var imgExt = imgPath.substring(imgPath.lastIndexOf('.')+1).toLowerCase();
var imgPreview = $('#imgpreview');
imgPreview.empty();
if(imgExt == "gif" || imgExt == "png" || imgExt == "jpg" || imgExt == "jpeg" || imgExt == "bmp"){
if (typeof(FileReader) != "undefined") {
for(var i = 0; i < imgCount; i++){
var reader = new FileReader();
var fn = imgItem[i].name;
var fs = imgItem[i].size;
var ft = imgItem[i].type;
reader.onload = function(e){
$("<img />",{
"src": e.target.result,
"width": "60px",
"height": "60px",
"class": "imgClass",
"title": fn +" and size "+ fs + " bytes and types "+ ft,
"alt": fn +" and size "+ fs + " bytes and types "+ ft,
}).appendTo(imgPreview);
}
imgPreview.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
imgPreview.html("This browser does not support FileReader");
}
}else{
imgPreview.html("File not supported!");
}
});
});
</script>
<!-- end of script -->
<!-- SCRIPT OF UPLOADED PHOTO -->
<script>
$(document).ready(function(){
$('#send').click(function(){
var image_name = $('#imgupload').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#imgupload').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#imgupload').val('');
return false;
}
}
});
});
</script>
<!-- END OF SCRIPT -->
what i did here is, I just removed the other <form> tags
if (isset($_POST['send'])){
include_once 'includes/dbh.inc.php';
$_SESSION['location'] = mysqli_real_escape_string($conn,
$_POST['location']);
$_SESSION['message'] = mysqli_real_escape_string($conn, $_POST['message']);
$file = addslashes(file_get_contents($_FILES["imgupload"]["tmp_name"]));
//insert the user into the database
$sql = "INSERT INTO newsfeed (user_email,user_uid,user_location, user_message,user_attachment) VALUES ('{$_SESSION['u_email']}','{$_SESSION['u_uid']}','{$_SESSION['location']}', '{$_SESSION['message']}','$file');";
if(mysqli_query($conn, $sql)){
echo "Event has been reported!";
exit();
}?>
<form action="includes/newsfeed.inc.php" method="POST" enctype="multipart/form-data">
<br><br><br><br>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Location</label>
<input type="text" name="location" class="form-control" placeholder="Press
'Get Geolocation'" id="location" required readonly="readonly"><p id="demo1"></p>
<center><button type="button" onclick="getLocation();" required>Get Geolocation</button></center>
<script>
var x = document.getElementById("demo1");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("location").value = position.coords.latitude + ',' + position.coords.longitude;
}
</script>
</div>
</div>
</div>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Message</label>
<textarea name="message" class="form-control" placeholder="Message" id="message" rows="15" required></textarea>
</div>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Upload Image</label><br>
<div class="container">
<p><div class="fileUpload btn btn-primary">
<span>+</span>
<input type="file" class="upload" name="imgupload" id="imgupload" multiple="multiple">
<br />
</div><a id="imgpreview"></a></p>
<button class="btn btn-primary" name="send" id="send">POST</button>
</div>
</div>
</div>
</div>
</form>
<!-- script of upload photo -->
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#imgupload').on('change', function(){
var imgItem = $(this)[0].files;
var imgCount = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var imgExt = imgPath.substring(imgPath.lastIndexOf('.')+1).toLowerCase();
var imgPreview = $('#imgpreview');
imgPreview.empty();
if(imgExt == "gif" || imgExt == "png" || imgExt == "jpg" || imgExt == "jpeg" || imgExt == "bmp"){
if (typeof(FileReader) != "undefined") {
for(var i = 0; i < imgCount; i++){
var reader = new FileReader();
var fn = imgItem[i].name;
var fs = imgItem[i].size;
var ft = imgItem[i].type;
reader.onload = function(e){
$("<img />",{
"src": e.target.result,
"width": "60px",
"height": "60px",
"class": "imgClass",
"title": fn +" and size "+ fs + " bytes and types "+ ft,
"alt": fn +" and size "+ fs + " bytes and types "+ ft,
}).appendTo(imgPreview);
}
imgPreview.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
imgPreview.html("This browser does not support FileReader");
}
}else{
imgPreview.html("File not supported!");
}
});
});
</script>
<!-- end of script -->
<!-- SCRIPT OF UPLOADED PHOTO -->
<script>
$(document).ready(function(){
$('#send').click(function(){
var image_name = $('#imgupload').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension =
$('#imgupload').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#imgupload').val('');
return false;
}
}
});
});
</script>
<!-- END OF SCRIPT -->

Read and write excel using javascript and hta

Here is the code to read the data from the excel sheet and paste that data into html table. It shows an error,when i convert the data from html table to excel sheet,but at the sametime this coding is working in vbscript,not working in javascript what is the solution for that..
<html>
<head>
<HTA:application
Applicationname="MyApp"
BORDER="dialog"
BORDERSTYLE="complex"
Caption="yes"
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
VERSION="2.0"
WINDOWSTATE="maximize"/>
<title>Read Excel</title>
<style type="text/css">
body
{
background-color:White;
}
P
{
font:bold 18px arial;
}
</style>
<script language="javascript" type="text/javascript">
var rowCount,colCount,selectexcel,objExcel,tempcol,intRow,intCol;
var rowData;
var mySpan;
var textData;
function ReadExcelData()
{
selectexcel = prompt("Please enter the file path", "D:\VBScriptTrainee\Sample.xlsx");
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = false;
objExcel.Workbooks.Open(selectexcel);
rowCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
colCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Columns.Count
alert(rowCount);
alert(colCount);
//colCount=colCount+1;
tempcol=colCount;
rowData="<table border=2>";
for (intRow=1;intRow <= rowCount;intRow++)
{
rowData = rowData + "<tr>";
for (intCol=1;intCol <= colCount;intCol++)
{
if ((intRow != 1) && (intCol ==tempcol))
{
rowData = rowData + "<td>" + "<input type='checkbox' id='flag_id' name='flag' />" + "</td>";
}
else if (intRow ==1)
{
rowData = rowData + "<td>" + objExcel.Cells(intRow,intCol).Value + "</td>";
}
else
{
rowData= rowData + "<td><div contentEditable='True'>" + objExcel.Cells(intRow,intCol).Value + "</div></td>";
}
}
rowData = rowData + "</tr>";
}
rowData =rowData + "</table>";
//document.write(rowData);
mySpan = document.getElementById('Span_id_two');
mySpan.innerHTML = rowData + "<br>";
//objExcel = undefined;
}
function WriteExcelData()
{
//mwresult = Msgbox ("Are you Sure to Write ?",vbOKCancel)
//var objExcelTwo;
//objExcelTwo = new ActiveXObject("Excel.Application");
//objExcelTwo.Visible = true;
//objExcelTwo.Workbooks.Open(selectexcel);
var tableValue;
var mySpan=document.getElementById('Span_id_two');
textData=mySpan.innerHTML;
var tab=document.getElementsByTagName("table")(0);
var mytable = document.getElementsByTagName("table")(0).rows.length;
//document.write(mytable);
var mytable1= document.getElementsByTagName("table")(0).rows(0).cells.length;
//document.write(mytable1);
for(n = 0;n<=(mytable-1);n++)
{
for(j = 0;j<=(mytable1-1);j++)
{
objExcel.Cells(n+1,j+1).Value = tab.Rows(n).Cells(j).innerHTML;
tableValue = tab.Rows(n).Cells(j).innerHTML;
if(tableValue == "<INPUT id=flag_id type=checkbox CHECKED name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="Yes";
}
if(tableValue == "<INPUT id=flag_id type=checkbox name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="No";
}
}
}
//var find ="<*>";
//var rplace =" ";
//objExcel.Cells.Replace find,rplace;
//MsgBox "Data Exported Successfully",vbInformation
//objExcel.ActiveWorkbook.Save;
//Set objExcel=nothing
}
</script>
</head>
<body>
<center>
<img src="Excel.png" height=200 width=300/>
</center>
<center>
<h1 align="center" style="color:blue"><img src="icon-developer-icon.png" height=100px width=100px/>
Read Excel (Row by Row)</h1><br>
<input type="button" name="Read" value="Click To Read" onclick="ReadExcelData()"/>
<input type="button" name="Write" value="Click To Write" onclick="WriteExcelData()"/>
</center>
<br>
<br>
<div>
<center>
<!--<table border="2px" color="Red">
<th id="thead"></th>
<tr>
<td>-->
<br>
<!--<div class="jumbotron">-->
<span ID="Span_id_two" Style="Color:blue;" name="text_name">
</span>
<br>
<!--</td>
</tr>
</table>-->
<marquee direction="Right" style="Color:red;">**Note : Select only excel files**</marquee>
</center>
</div>
</div>
</div>
</div>
</body>
</html>
It shows the following error 'object doesn't support this property or method'
in WriteExcelData function.

HTML/JS Contact Form Not Sending or Showing Error Message

I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML
<div class="contactForm">
<div class="successMessage alert alert-success alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Thank You! E-mail was sent.
</div>
<div class="errorMessage alert alert-danger alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Oops! An error occured. Please try again later.
</div>
<form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Name <span>(Required)</span></label>
<input type="text" required name="field[]" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email <span>(Required)</span></label>
<input type="email" required name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject</label>
<input type="text" name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Message <span>(Required)</span></label>
<textarea name="field[]" required class="form-control" rows="5"></textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Send Message">
</fieldset>
</form>
</div>
</div>
The JS
/**
* Contact Form
*/
jQuery(document).ready(function ($) {
"use strict";
$ = jQuery.noConflict();
var debug = false; //show system errors
$('.liveForm').submit(function () {
var $f = $(this);
var showErrors = $f.attr('data-show-errors') == 'true';
var hideForm = $f.attr('data-hide-form') == 'true';
var emailSubject = $f.attr('data-email-subject');
var $submit = $f.find('[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$('[name="field[]"]', $f).each(function (key, e) {
var $e = $(e);
var p = $e.parent().find("label").text();
if (p) {
var t = $e.attr('required') ? '[required]' : '[optional]';
var type = $e.attr('type') ? $e.attr('type') : 'unknown';
t = t + '[' + type + ']';
var n = $e.attr('name').replace('[]', '[' + p + ']');
n = n + t;
$e.attr('data-previous-name', $e.attr('name'));
$e.attr('name', n);
}
});
$submit.addClass('disabled');
$f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
$('span.error', $f).remove();
$('.error', $f).removeClass('error');
$('.form-group', $f).removeClass('has-error');
if (data.errors) {
$.each(data.errors, function (i, k) {
var input = $('[name^="' + i + '"]', $f).addClass('error');
if (showErrors) {
input.after('<span class="error help-block">' + k + '</span>');
}
if (input.parent('.form-group')) {
input.parent('.form-group').addClass('has-error');
}
});
} else {
var item = data.success ? '.successMessage' : '.errorMessage';
if (hideForm) {
$f.fadeOut(function () {
$f.parent().find(item).show();
});
} else {
$f.parent().find(item).fadeIn();
$f[0].reset();
}
}
$submit.removeClass('disabled');
cleanupForm($f);
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.removeClass('disabled');
cleanupForm($f);
}
});
return false;
});
function cleanupForm($f) {
$f.find('.temp').remove();
$f.find('[data-previous-name]').each(function () {
var $e = jQuery(this);
$e.attr('name', $e.attr('data-previous-name'));
$e.removeAttr('data-previous-name');
});
}
});
The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>
<?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
//redirect to contact form
echo "Please enable Javascript";
exit;
}
require_once "config.php";
//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";
//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);
if ($data['errors']) {
echo json_encode(array('errors' => $data['errors']));
exit;
}
$html = '<div style="width: 640px; font-size: 11px;">
<h2>' . $mail->Subject . '</h2><ul>
';
foreach ($data['fields'] as $label => $val) {
$html .= '<li>' . $label . ': ' . $val . '</li>';
}
$html .= '</ul></div>';
$mail->setup($html, $_REQUEST, array());
$result = array('success' => 1);
if (!$mail->Send()) {
$result['success'] = 0;
}
echo json_encode($result);
exit;

Categories