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

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 -->

Related

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

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.

Why isn't the file being read from being posted

I have code that is supposed to post a file to a php using js. It is not working. I have previously attempted to view the image that is being sent. This has not worked. Incase anyone wanted to view what the code does, this is a sample login: username:john & password:1234.If anyone could help me, thanks in advance.
This is the html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyCg8CauUyZeBGffR_2yAv7hkb-pD9zuzrA",
authDomain: "push-notifications-affa8.firebaseapp.com",
databaseURL: "https://push-notifications-affa8.firebaseio.com",
projectId: "push-notifications-affa8",
storageBucket: "push-notifications-affa8.appspot.com",
messagingSenderId: "1027448457059"
};
firebase.initializeApp(config);
</script>
<link rel="manifest" href="/manifest.json">
<title>MegaLords</title>
<link rel="stylesheet" href="styles/main.css">
<style>
#fileToUpload {
display:none;
}
#logout {
all: initial;
font-family: "Comic Sans MS", "Comic Sans", cursive;
cursor: pointer;
}
#logout:hover{
color: blue;
}
</style>
<script src="script/main.js"></script>
</head>
<body>
<div id="test" class = "topnav">
<a class=active>Home</a>
<a href=news.php>News</a>
<a href=contact.php>Contact</a>
<a href=about.php>About</a>
<a href=buy.php>Buy</a>
<?php
if(isset($_COOKIE['username'])){
echo "<a href=game.php>Play</a>";
echo "<button onclick=" . "document.getElementById('id04').style.display='block'" . ">Profile</button>";
}else{
echo "<button onclick=" . "document.getElementById('id01').style.display='block'" . ">Sign Up</button>";
echo "<button onclick=" . "document.getElementById('id02').style.display='block'" . "> Login</button>";
}
?>
</div>
<div id="id01" class="modal" style = 'padding-top: 50px;'>
<form id=signUpForm class="modal-content">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<p id ="errusra" class="err"></p>
<label><b>Username</b></label>
<input id="signUpUsername" type="text" placeholder="Enter Username" class = "profile" required>
<p id="erremaila" class="err"></p>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" id="signUpEmail" class = "profile" required>
<p id="errpswa" class="err"></p>
<label><b>Password</b></label>
<input id="signUpPassword"type="password" placeholder="Enter Password" class = "profile" required>
<p id="errrepswa" class="err"></p>
<label><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" id="passwordRepeat" class = "profile" required>
<label>
<input type="checkbox" checked="checked" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelSignUpbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
<div id="id02" class="modal" style = "padding-top: 50px;">
<form id="loginform"class="modal-content animate">
<div class="imgcontainer">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">×</span>
<img src="images/loginformimg.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<p id="loginerr" class = 'err'></p>
<label><b>Username</b></label>
<input id="loginUsername"type="text" placeholder="Enter Username" class="profile" required>
<label><b>Password</b></label>
<input id="loginPassword"type="password" placeholder="Enter Password" class = "profile" required>
<label>
<input type="checkbox" checked="checked" name = "cookies"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1; overflow:auto;">
<button type="submit"style="background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;">Login</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelLoginbtn loginButton">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<div id="id04" class="modal" style = "padding-top: 50px;">
<form id="changeInfoForm"class = "modal-content animate">
<div class="imgcontainer">
<?php
if(isset($_COOKIE['profilepic'])){
echo "<span onclick=" . '"document.getElementById(' . "'id04').style.display='none' " . '" class="close" title="Close Modal">×</span>
<label for="fileToUpload">
<img src="players/'. $_COOKIE['username']. '/' . $_COOKIE['profilepic'] . '" alt="Avatar" class="avatar" id="img">
</label>
<input type="file" name="fileToUpload" id="fileToUpload">';
}else{
echo "<span onclick=" . '"document.getElementById(' . "'id04').style.display='none' " . '" class="close" title="Close Modal">×</span>
<label for="fileToUpload">
<img src="images/loginformimg.png" alt="Avatar" class="avatar">
</label>
<input type="file" name="fileToUpload" id="fileToUpload">';
}
?>
</div>
<div class="container">
<label>
<b>Username:</b> <input id=changeusername class="profile" name="username"value = <?php echo $_COOKIE['username'];?>>
</label>
<br>
<label>
<b>Email:</b> <input id=changeemail class="profile" name="email"value = <?php if(isset($_COOKIE['email'])){ echo $_COOKIE['email']; } ?>>
</label>
<br>
<label>
<b>New Password:</b> <input id="changerepassword"type="password" name="password"class="profile" >
</label>
<br>
<label>
<b>Current Password:</b> <input id=changepassword type="password" name="new-password"class="profile" required>
</label>
<br>
</div>
<div class="container" style="background-color:#f1f1f1; overflow:auto;">
<input type="submit"style="background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;" value="Change Profile Info"name="submit">
<button type="button" onclick="document.getElementById('id04').style.display='none'" class="cancelLoginbtn loginButton">Cancel</button>
<span class="psw"><a id="logout"onclick="logout()">Logout</a></span>
</div>
</form>
</div>
<script src="profile.js"></script>
<?php include 'selectimage.php'?>
<h1>Welcome to MegaLords</h1>
<p>MegaLords is a place where mortals can become gods, and fallen gods can become true gods once more. Becoming a god is a very difficult process, and cannot be explained. Contact me if you wish to become a god.
<h4>Requirements</h4>
<ul>
<li>You must have beaten the game</li>
<li>You must be a mortal or fallen god</li>
<li>You must be weaker than a lower god</li>
<li>You cannot be a mythical creature, but we are looking for mythical creatures</li>
</ul>
<h4>Instructions</h4>
<ol>
<li>Beat the game</li>
<li>The Owner will immediately contact you, if not contact them</li>
<li>The Owner will grant you goddhood</li>
</ol>
</p>
<footer>
<p>Posted by: Electrox</p>
<p>Contact information: QuiMortemKing#gmail.com.</p>
</footer>
</body>
</html>
This is the website
https://omegalords.ga/
This is the js
if(window.location.href == "http://megalords.000webhostapp.com"){
window.location.href = "https://megalords.000webhostapp.com"
}else {
console.log(window.location.href)
}
// Get the modal
var modalLogin = document.getElementById('id02');
var modalSignUp = document.getElementById('id01');
var modalProfile = document.getElementById('id04');
var loginUsername = document.getElementById("loginUsername");
var loginPassword = document.getElementById("loginPassword");
var loginform = document.getElementById("loginform");
var signUpEmail = document.getElementById("signUpEmail");
var signUpUsername = document.getElementById("signUpUsername");
var signUpPassword = document.getElementById("signUpPassword");
var signUpRePassword = document.getElementById("passwordRepeat");
var signUpForm = document.getElementById("signUpForm");
var changeInfoUsername = document.getElementById("changeusername")
var changeInfoEmail = document.getElementById("changeemail")
var changeInfoPassword = document.getElementById("changepassword")
var changeInfoRePassword = document.getElementById("changerepassword")
var changeInfoForm = document.getElementById("changeInfoForm")
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalLogin) {
modalLogin.style.display = "none";
}else if (event.target == modalSignUp) {
modalSignUp.style.dis4play = "none";
}else if (event.target == modalProfile){
modalProfile.style.display = "none";
}
}
var style = document.createElement('style');
var topnav = document.getElementsByClassName('topnav')[0];
var percent = 1/topnav.childElementCount * 100;
style.innerHTML += ".topnav a, button{float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; BORDER: none; width: " + percent + "%; }"
document.getElementsByTagName('head')[0].appendChild(style);
var getEmail = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
if(this.responseText == "Please Refresh"){
location.reload();
}else {
return;
}
}else if(this.status == 404 || this.readyState === 0 || this.status == 404 && this.readyState === 0){
document.body.innerHTML = "File Not Found"
}
}
xhttp.open("GET", "getemail.php", true)
xhttp.send()
}
var getProfilepic = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "Please Refresh"){
location.reload();
}else if(this.responseText == "Your Account is Broken. The Dev Has Been Notified"){
document.body.innerHTML += this.responseText
}else if(this.responseText == "No Profile Picture Found"){
var confirmation = confirm("Would You like to Set a Profile picture?");
if(confirmation === true){
modalProfile.style.display = "block"
}
}
}
}
xhttp.open("GET", 'getprofileimage.php', true)
xhttp.send()
}
var signUp = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == " Sign Up Complete"){
location.reload();
}else{
if(this.responseText == "No"){
document.getElementById("errusra").innerHTML = this.responseText;
}else{
switch(this.responseText){
case " *That Username Is Taken":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You may only have letters and numbers as a username":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You must have between 2 and 8 characters as username":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *Invalid email":
document.getElementById("erremaila").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You must have at least one lowercase, uppercase, and a number as a password":
document.getElementById("errpswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You may only have between 3 and 12 characters as password":
document.getElementById("errpswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *Passwords do not match":
document.getElementById("errrepswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
break;
default:
document.body.innerHTML =this.responseText
console.log(this.responseText)
}
}
}
}
}
xhttp.open("GET",'checkregister.php?eml=' + signUpEmail.value + '&usrnm=' + signUpUsername.value + '&psw=' + signUpPassword.value + '&repsw='+ signUpRePassword.value,true);
xhttp.send();
}
var login = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "Login Successful!"){
location.reload();
}else{
modalLogin.style.display = "block";
console.log(this.responseText)
document.getElementById("loginerr").innerHTML = this.responseText;
}
}
}
xhttp.open("GET",'checklogin.php?usrnm=' + loginUsername.value + '&psw=' + loginPassword.value,true)
xhttp.send();
}
var logout = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
location.reload();
}
}
xhttp.open("GET",'logout.php', true);
xhttp.send();
}
var changeInfo = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
window.wormData = new FormData();
var file = document.getElementById("fileToUpload").files[0];
wormData.append('fileToUpload', file)
wormData.append('username',changeInfoUsername.value);
wormData.append('email',changeInfoEmail.value);
wormData.append('password',changeInfoPassword.value);
if(!(changeInfoRePassword.value == "")){
wormData.append('new-password',changeInfoRePassword.value)
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText)
}
}
xhttp.open("POST","changeinfo.php",true);
xhttp.send(wormData);
}
signUpForm.addEventListener('submit',signUp);
loginform.addEventListener('submit',login);
changeInfoForm.addEventListener('submit',changeInfo);
getEmail();
getProfilepic();
This is the php
<?php
include 'templates/connect.php';
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST["new-password"])){
$newpassword = $_POST["new-password"];
}
$currusername = $_COOKIE['username'];
$query="SELECT * FROM `Users`
WHERE `username` = '$currusername' AND `psw` = '$password';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$id = $row[0];
//echo $row[3];
if(!$result || mysqli_num_rows($result) === 0){
echo $username . $password;
}else{
if($row[1] === $username){
if($row[3] === $email || $email == ""){
if(isset($newpassword)){
$query="UPDATE `Users` SET `psw` = '$newpassword' WHERE `id` = '$id';";
echo $query;
$result = mysqli_query($conn, $query);
}else {
echo "Everything is the same";
}
}
}else if(isset($email)){
if(isset($newpassword)){
$query="UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
rename('players/' . $row[1], 'players/' . $username);
$result = mysqli_query($conn, $query);
}
}else if(isset($newpassword)){
$query="UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
UPDATE `Users` SET `email` = '$email' WHERE id = '$id';
UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
$result = mysqli_query($conn, $query);
rename('players/' . $row[1], 'players/' . $username);
}else {
echo "Everything is the same";
}
}
foreach($_FILES as $data){
echo $data[name];
}
if(isset($_FILES['fileToUpload'])){
$target_dir = "players/". $_COOKIE['username'] . "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(file_exists($_FILES['fileToUpload']['tmp_name']) || is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo basename( $_FILES["fileToUpload"]["name"]);
$query = "UPDATE `Users` SET `userimage` = '". $_FILES["fileToUpload"]["name"] . "' WHERE `username` = '$currusername'";
unlink("players/$row[1]/$row[5]");
$result = mysqli_query($conn, $query);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
You have to set the enctype attribute in your form, so that the server can read the file.
<form id="changeInfoForm" class = "modal-content animate" enctype="multipart/form-data">

{"type":"error","text":"Sorry Request must be Ajax POST"}

I don't know why I'm still getting that error. I've been trying to remove the error, but I still receiving it. I need help because I ran out of choices. What I'm doing wrong? What I have to do?
This is my html:
<div class="modal fade" id="contactModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Contact Us</h4>
</div>
<div class="modal-body">
<div class="contact">
<form id='contacts_form' method="post" action="contacts.php">
<div class="field-group">
<input class="form-control" type="text" id="name" name="name" placeholder="Name" />
</div>
<div class="field-group">
<input class="form-control" type="email" id="email" name="email" placeholder="E-mail" />
</div>
<div class="field-group">
<input class="form-control" type="text" id="message" name="message" placeholder="Message" />
</div>
<div class="field-group">
<input type="submit" class="form_submit" value="Send Message" />
</div>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
</div>
This is my jQuery
(function($) {
'use strict';
jQuery(document).ready(function(){
/*PRELOADER JS*/
$(window).load(function() {
$('.status').fadeOut();
$('.preloader').delay(350).fadeOut('slow');
});
/*END PRELOADER JS*/
/*START MENU JS*/
$('a.page-scroll').on('click', function(e){
var anchor = $(this);
$('html, body').stop().animate({
scrollTop: $(anchor.attr('href')).offset().top - 50
}, 1500);
e.preventDefault();
});
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.menu-top').addClass('menu-shrink');
} else {
$('.menu-top').removeClass('menu-shrink');
}
});
$(document).on('click','.navbar-collapse.in',function(e) {
if( $(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) {
$(this).collapse('hide');
}
});
/*END MENU JS*/
/*START TESTIMONIAL JS*/
$('.carousel').carousel({
interval:5000,
pause:'false',
});
/*END TESTIMONIAL JS*/
/*START PARTNER LOGO*/
$('.partner').owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 4,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
/*END PARTNER LOGO*/
$("#form_submit").click(function(e){
e.preventDefault();
var form = $(this).parents('form');
form.find('.form-control').removeClass('error');
form.find('.error_block').remove();
var post_data;
var errors = formValidation(form),
output;
if( Object.keys(errors).length > 0 ) {
showErrors(form, errors);
} else {
if(form.attr('id') == 'contacts_form') {
post_data = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'message' : $('input[name=message]').val()
};
//Ajax post data to server
jQuery.post('contacts.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error_block">'+response.text+'</div>';
} else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contacts_form .form-control").val('');
}
form.find('.form_row').slideUp();
form.find("#contact_results").hide().html(output).slideDown();
}, 'json');
} else {
post_data = {
'subscribe_email': $('input[name=subscribe_email]').val(),
};
jQuery.post('subscribe.php', post_data, function(response){
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}, 'json');
}
}
return false;
});
});
/*START WOW ANIMATION JS*/
new WOW().init();
/*END WOW ANIMATION JS*/
})(jQuery);
This is my php
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array(
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output);
}
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email;
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail1 = #mail($to_email1, $name, $message_body, $headers);
$send_mail2 = #mail($to_email2, $name, $message_body, $headers);
if(!$send_mail1 || !$send_mail2)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$name .'! Thank you for your email'));
die($output);
}
}
?>
You're saying that if it's not set and it's not equal to xmlhttprequest to fail. You need to say OR instead of AND
if(
false === isset($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'
) {
// you code
}
<div class="modal fade" id="contactModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Contact Us</h4>
</div>
<div class="modal-body">
<div class="contact">
<form id='contacts_form' method="post" action="contacts" onsubmit="event.preventDefault();">
<div class="field-group">
<input class="form-control" type="text" id="name" name="name" placeholder="Name" />
</div>
<div class="field-group">
<input class="form-control" type="email" id="email" name="email" placeholder="E-mail" />
</div>
<div class="field-group">
<input class="form-control" type="text" id="message" name="message" placeholder="Message" />
</div>
<div class="field-group">
<input type="submit" id="form_submit" class="form_submit" value="Send Message" />
</div>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/wow/0.1.12/wow.min.js"></script>
<script>new WOW().init();</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"></script>
<script>
(function($) {
'use strict';
jQuery(document).ready(function(){
/*PRELOADER JS*/
$(window).on('load',function() {
$('.status').fadeOut();
$('.preloader').delay(350).fadeOut('slow');
});
/*END PRELOADER JS*/
/*START MENU JS*/
$('a.page-scroll').on('click', function(e){
var anchor = $(this);
$('html, body').stop().animate({
scrollTop: $(anchor.attr('href')).offset().top - 50
}, 1500);
e.preventDefault();
});
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.menu-top').addClass('menu-shrink');
} else {
$('.menu-top').removeClass('menu-shrink');
}
});
$(document).on('click','.navbar-collapse.in',function(e) {
if( $(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) {
$(this).collapse('hide');
}
});
/*END MENU JS*/
/*START TESTIMONIAL JS*/
$('.carousel').carousel({
interval:5000,
pause:'false',
});
/*END TESTIMONIAL JS*/
/*START PARTNER LOGO*/
$('.partner').owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 4,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
/*END PARTNER LOGO*/
$("#form_submit").click(function(e){
//alert('ok');
var output;
//e.preventDefault();
var form = $(this).parents('form');
form.find('.form-control').removeClass('error');
form.find('.error_block').remove();
var post_data;
if(form.attr('id') == 'contacts_form') {
post_data = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'message' : $('input[name=message]').val()
};
//Ajax post data to server
jQuery.post('http://localhost/stackoverflow/contacts', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error_block">'+response.text+'</div>';
} else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contacts_form .form-control").val('');
}
form.find('.form_row').slideUp();
form.find("#contact_results").hide().html(output).slideDown();
}, 'json');
} else {
post_data = {
'subscribe_email': $('input[name=subscribe_email]').val(),
};
jQuery.post('subscribe.php', post_data, function(response){
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}, 'json');
}
//}
return false;
});
});
/*START WOW ANIMATION JS*/
new WOW().init();
/*END WOW ANIMATION JS*/
})(jQuery);

user profile update via ajax

hi guys im trying to update user details via ajax but its not updating my users table and just stop executing when possessing... appear here is my code please help if possible
edit_profile.php
<?php
if(isset($_POST["la"])){
$firstname = strip_tags(preg_replace('#[^a-z0-9]#i', '', $_POST['fi']));
$lastname = strip_tags(preg_replace('#[^a-z]#', '', $_POST['la']));
$age = strip_tags(preg_replace('#[0-9]#', '', $_POST['ag']));
$gender = strip_tags(preg_replace('#[^a-z]#', '', $_POST['g']));
// FORM DATA ERROR HANDLING
if($gender == "" || $firsname == "" || $lastname == "" || $age == ""){
echo "some account info is empty.";
exit();
}else{
$sql = "UPDATE users SET gender='$gender', age='$age', lastname='$lastname, firstname='$firstname' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo "account_success";
exit();
}
}
?>
ajax and js
<script type="text/javascript" language="javascript">
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "firstname"){
rx = /[^a-z0-9]/gi;
} else if(elem == "lastname"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function update_profile() {
var fi = _("firstname").value;
var la = _("lastname").value;
var g = _("gender").value;
var ag = _("age").value;
var status2 = _("status_profile");
if(fi == "" || la == "" || ag == "" || g == ""){
status2.innerHTML = "Fill out all of the form data";
status2.style.color = "red";
}else {
_("profilebtn").style.display = "none";
status2.innerHTML = 'processing ...';
var ajax = ajaxObj("POST", "edit_profile.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "account_success"){
_("profilebtn").style.display = "block";
}
}
}
ajax.send("&fi="+fi+"&la="+la+"&g="+g+"&ag="+ag);
}
}
</script>
the html
<div class="row profile-classic">
<div class="col-md-12 m-t-20">
<form name="updateform" id="updateform" onsubmit="return false;">
<div id="profile_form" class="panel">
<div class="panel-title line">
<div class="caption"><i class="fa fa-phone c-gray m-r-10"></i>ACCOUNT</div>
</div>
<div class="panel-body">
<div class="row">
<div class="control-label c-gray col-md-3">Username:</div>
<div class="col-md-6">
<input type="text" class="form-control" value="<?php echo $uname; ?>" disabled="disabled">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Firstname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="firstname" contenteditable="true" value="<?php echo $firstname; ?>">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Lastname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="lastname" placeholder="your lastname" value="<?php echo $lastname; ?>" >
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Age: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="age" value="<?php echo $age; ?>">
</div>
</div><br />
<div class="row">
<div class="col-md-6">
<select class="form-control" onfocus="emptyElement('status_profile')" id="gender" class="form-control">
<option value="<?php echo $gender; ?>"><?php echo $sex; ?></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<button id="profilebtn" onclick="update_profile()" class="btn btn-sm btn-default"><i class="fa fa-floppy-o"></i> Save</button><span id="status_profile"></span>
</div><br />
</div>
</div></form>
</div></div>
You can use mysqli_error($db_conx) to determine what the error is... just have your javascript display it nicely for you.
But also - the variable in your WHERE clause ( $log_username ) is undefined.

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