ordersubmit

This commit is contained in:
StockiP
2022-06-02 08:09:40 +02:00
parent dd12b3f6ee
commit bd5e702782
5 changed files with 538 additions and 2 deletions

135
components/checkout.html Normal file
View File

@@ -0,0 +1,135 @@
<div class="container wrapper maincontent">
<div class="row g-5">
<div class="col-md-5 col-lg-4 order-md-last">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-success">Dein Einkaufswagen</span>
<span class="badge bg-success rounded-pill" id="gesamtMengeCart"></span>
</h4>
<ul class="list-group mb-3" id="productListSideways">
</ul>
<form class="card p-2">
<div class="input-group">
<input type="text" class="form-control" placeholder="Promo code">
<button type="submit" class="btn btn-secondary">Redeem</button>
</div>
</form>
</div>
<div class="col-md-7 col-lg-8">
<h4 class="mb-3">Ihre angegebene Adresse:</h4>
<form class="needs-validation" novalidate="">
<div class="row g-3">
<div class="col-sm-6">
<label for="firstName" class="form-label">Vorname</label>
<input type="text" class="form-control" id="firstName" placeholder="" required="">
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-sm-6">
<label for="lastName" class="form-label">Nachname</label>
<input type="text" class="form-control" id="lastName" placeholder="" required="">
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
<div class="col-12">
<label for="address" class="form-label">Address</label>
<input type="text" class="form-control" id="address" placeholder="1234 Main St" required="">
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="col-md-4">
<label for="state" class="form-label">Stadt</label>
<input type="text" class="form-control" id="city" placeholder="" required="">
<div class="invalid-feedback">
Please provide a valid state.
</div>
</div>
<div class="col-md-3">
<label for="zip" class="form-label">Zip</label>
<input type="text" class="form-control" id="zip" placeholder="" required="">
<div class="invalid-feedback">
Zip code required.
</div>
</div>
</div>
<hr class="my-4">
<!--
<div class="form-check">
<input type="checkbox" class="form-check-input" id="same-address">
<label class="form-check-label" for="same-address">Shipping address is the same as my billing
address</label>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="save-info">
<label class="form-check-label" for="save-info">Save this information for next time</label>
</div>
-->
<h4 class="mb-3">Bezahlung</h4>
<div class="my-3">
<div class="form-check">
<input id="credit" name="paymentMethod" type="radio" checked="checked" required="" onclick="javascript:paymentTypeClicked()">
<label class="form-check-label" for="credit">Kreditkarte</label>
</div>
<div class="form-check">
<input id="lieferung" name="paymentMethod" type="radio" required="" onclick="javascript:paymentTypeClicked()">
<label class="form-check-label" for="lieferung">Bei Lieferung (Bar oder Karte)</label>
</div>
</div>
<div class="row gy-3" id="creditCardData">
<div class="col-md-6">
<label for="cc-name" class="form-label">Name auf der Karte</label>
<input type="text" class="form-control" id="cc-name" placeholder="" required="">
<small class="text-muted">Vor und Nachname wie auf der Karte ersichtlich</small>
<div class="invalid-feedback">
Name on card is required
</div>
</div>
<div class="col-md-6">
<label for="cc-number" class="form-label">Kreditkartennummer</label>
<input type="text" class="form-control" id="cc-number" placeholder="" required="">
<div class="invalid-feedback">
Credit card number is required
</div>
</div>
<div class="col-md-3">
<label for="cc-expiration" class="form-label">Ablaufdatum</label>
<input type="text" class="form-control" id="cc-expiration" placeholder="" required="">
<div class="invalid-feedback">
Expiration date required
</div>
</div>
<div class="col-md-3">
<label for="cc-cvv" class="form-label">CVV</label>
<input type="text" class="form-control" id="cc-cvv" placeholder="" required="">
<div class="invalid-feedback">
Security code required
</div>
</div>
</div>
<hr class="my-4">
<button class="w-100 btn btn-success btn-lg" id="submitOrder">Bestellung aufgeben</button>
</form>
</div>
</div>
</div>
<script src="../js/checkout.js"></script>

View File

@@ -29,6 +29,7 @@ $(document).ready(function() {
});
document.getElementById('cartLink')?.addEventListener('click', function() {
$('#mmlMainContent').load('../components/cart.html');
});
});
$('#marmeladenladen_footer').load('../components/footer.html');

View File

@@ -1,6 +1,13 @@
$(document).ready(function () {
updateCartTotal();
document.getElementById("emptycart").addEventListener("click", emptyCart);
document.getElementById("checkout").addEventListener("click", function () {
if (sessionStorage.getItem('cart') && document.cookie.indexOf("loggedIn=true") != -1) {
$('#mmlMainContent').load('../components/checkout.html');
} else {
$('#mmlMainContent').load('../components/login.html');
}
});
});
@@ -40,7 +47,7 @@ function updateCartTotal() {
totalperproduct = price * count;
totalperproduct = parseFloat(totalperproduct.toFixed(2));
//add price to total
carttable += "<tr><td>" + productid + "</td><td class='text-center'><button type='button' class='btn btn-danger removeproduct'>X</button></td><td>" + productname + "</td><td class='text-end'>" + price + "€</td><td class='text-end'>" + count + "</td><td class='text-end'>" + totalperproduct + "€</td></tr>";
carttable += "<tr><td>" + productid + "</td><td class='text-center'><button type='button' class='btn btn-danger removeproduct'>X</button></td><td>" + productname + "</td><td class='text-end'>" + price + "€</td><td class='text-center'><button type='button' class='btn btn-danger decreasecount float-start'>-</button>" + count + "<button type='button' class='btn btn-success increasecount float-end'>+</button></td><td class='text-end'>" + totalperproduct + "€</td></tr>";
total += totalperproduct;
total = parseFloat(total.toFixed(2));
prodCount += count;
@@ -58,6 +65,17 @@ function updateCartTotal() {
for (var i = 0; i < delbtns.length; i++) {
delbtns[i].addEventListener("click", function() { removeProductFromCart(this); });
}
var incbtns = document.getElementsByClassName("btn btn-success increasecount");
for (var i = 0; i < incbtns.length; i++) {
incbtns[i].addEventListener("click", function() { increaseCount(this); });
}
var decbtns = document.getElementsByClassName("btn btn-danger decreasecount");
for (var i = 0; i < decbtns.length; i++) {
decbtns[i].addEventListener("click", function() { decreaseCount(this); });
}
}
function removeProductFromCart(elem) {
@@ -76,4 +94,49 @@ function removeProductFromCart(elem) {
sessionStorage.setItem('cart', stringCart);
updateCartTotal();
updateCartCount();
}
}
//function to increase product count in cart
function increaseCount(elem) {
console.log("triggered");
var productid = elem.parentNode.parentNode.children[0].innerText;
var cart = JSON.parse(sessionStorage.getItem('cart'));
var items = cart.length;
for (var i = 0; i < items; i++) {
var x = JSON.parse(cart[i]);
if (x.productid == productid) {
x.count++;
cart[i] = JSON.stringify(x);
console.log(x.count);
break;
}
}
var stringCart = JSON.stringify(cart);
sessionStorage.setItem('cart', stringCart);
updateCartTotal();
updateCartCount();
}
//function to decrease product count in cart
function decreaseCount(elem) {
var productid = elem.parentNode.parentNode.children[0].innerText;
var cart = JSON.parse(sessionStorage.getItem('cart'));
var items = cart.length;
for (var i = 0; i < items; i++) {
var x = JSON.parse(cart[i]);
if (x.productid == productid) {
x.count--;
if (x.count < 1) {
cart.splice(i, 1);
break;
} else {
cart[i] = JSON.stringify(x);
break;
}
}
}
var stringCart = JSON.stringify(cart);
sessionStorage.setItem('cart', stringCart);
updateCartTotal();
updateCartCount();
}

169
js/checkout.js Normal file
View File

@@ -0,0 +1,169 @@
$(document).ready(function () {
getProductsOnSide();
getUserData();
//add click listener to submit order button
$('#submitOrder').click(function () {
//supress default
event.preventDefault();
submitOrder();
});
});
function getTotalAmount() {
var cart = JSON.parse(sessionStorage.getItem('cart'));
var items = cart.length;
var total = 0;
for (var i = 0; i < items; i++) {
var x = JSON.parse(cart[i]);
total += x.price * x.count;
}
return total.toFixed(2);
}
function getProductsOnSide() {
var cart = JSON.parse(sessionStorage.getItem('cart'));
var items = cart.length;
for (var i = 0; i < items; i++) {
var x = JSON.parse(cart[i]);
/*console.log(x);
console.log(x.count);
console.log(x.productid)
console.log(x.price);
console.log(x.productname);*/
var total = x.count * x.price;
const productListSideways = document.getElementById('productListSideways');
const product = document.createElement('li');
product.className = "list-group-item d-flex justify-content-between lh-sm";
product.id = productid;
product.innerHTML = `<div>
<h6 class="my-0">${x.productname}</h6>
<small class="text-muted">${x.count} Stück x ${x.price} €</small>
</div>
<span class="text-muted">${total} €</span>`;
productListSideways.appendChild(product);
}
var gesamtMengeCart = getCartCount();
var totalMoneyAmount = getTotalAmount();
$('#gesamtMengeCart').text(gesamtMengeCart);
const totalAmount = document.createElement('li');
totalAmount.className = "list-group-item d-flex justify-content-between";
totalAmount.innerHTML = `<span>Gesamtpreis (EUR)</span>
<strong>${totalMoneyAmount} €</strong>`;
productListSideways.appendChild(totalAmount);
}
function getUserData() {
const firstname = document.getElementById('firstName');
const lastname = document.getElementById('lastName');
const address = document.getElementById('address');
const plz = document.getElementById('zip');
const city = document.getElementById('city');
var username = getCookie('email');
var loggedIn = getCookie('loggedIn');
var sendData = {
"username": username,
};
stringData = JSON.stringify(sendData);
if (loggedIn == 'true') {
$.ajax({
url: '../logic/getUserData.php',
type: 'POST',
cache: false,
datatype: 'json',
data: stringData,
success: function (response) {
const data = JSON.parse(response);
//set data to fields
firstname.value = data.firstname;
lastname.value = data.lastname;
address.value = data.address;
plz.value = data.plz;
city.value = data.city;
}
});
} else {
window.location.href = '../index.html';
}
}
function getCookie(cname) {
let name = cname + "=";
let decodeCookie = decodeURIComponent(document.cookie);
let ca = decodeCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function paymentTypeClicked() {
if (document.getElementById('credit').checked) {
document.getElementById('creditCardData').style.display = 'block';
} else {
document.getElementById('creditCardData').style.display = 'none';
}
}
function submitOrder() {
var cart = JSON.parse(sessionStorage.getItem('cart'));
var items = cart.length;
var total = getTotalAmount();
var firstname = document.getElementById('firstName').value;
var lastname = document.getElementById('lastName').value;
var address = document.getElementById('address').value;
var plz = document.getElementById('zip').value;
var city = document.getElementById('city').value;
if (document.getElementById('credit').checked) {
var paymentId = 2;
var creditCardNumber = document.getElementById('creditCardNumber').value;
var creditCardExpiration = document.getElementById('creditCardExpiration').value;
var creditCardCvv = document.getElementById('creditCardCvv').value;
} else {
var paymentId = 1;
}
var username = getCookie('email');
var loggedIn = getCookie('loggedIn');
var sendData = {
"username": username,
"firstname": firstname,
"lastname": lastname,
"address": address,
"plz": plz,
"city": city,
"total": total,
"cart": cart,
"paymentId": paymentId,
};
stringData = JSON.stringify(sendData);
if (loggedIn == 'true') {
$.ajax({
url: '../logic/submitOrder.php',
type: 'POST',
cache: false,
datatype: 'json',
data: stringData,
success: function (response) {
console.log(response);
if (response == 'success') {
sessionStorage.removeItem('cart');
updateCartCount();
alert('Bestellung erfolgreich abgeschlossen');
$('#mmlMainContent').load('../components/homepage.html');
} else {
alert('Fehler beim Abschicken der Bestellung');
}
}
});
} else {
alert('Bitte einloggen');
}
}

168
logic/submitOrder.php Normal file
View File

@@ -0,0 +1,168 @@
<?php
$data = json_decode(file_get_contents('php://input'));
$email = $data->username;
$firstname = $data->firstname;
$lastname = $data->lastname;
$address = $data->address;
$cart = $data->cart;
$total = $data->total;
$payment = $data->paymentId;
addOrder($email, $total, $payment, $cart);
//addOrdertoDB($user_id, $total, $payment);
//$success = addOrderToDB($user_id, $total, $payment);
/*if ($success) {
$success = addItemsToOrderItems($cart, $user_id);
if ($success) {
echo "success";
} else {
echo "failure";
}
} else {
$success = false;
echo "failure";
}*/
function addOrder($email, $total, $payment, $cart) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
//get UserID
$sql = "SELECT `user_id` FROM `user` WHERE `username` = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id);
if ($stmt->num_rows == 1) {
$stmt->fetch();
} else {
$user_id = 0;
}
//add order to DB
$sql = "INSERT INTO `order_details` (`user_id`, `total`, `payment_id`) VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param("idi", $user_id, $total, $payment);
if ($stmt->execute()) {
$successorderToDB = true;
} else {
$successorderToDB = false;
}
//getLastInsertID
$sql = "SELECT LAST_INSERT_ID() FROM `order_details`";
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($order_id);
if ($stmt->num_rows == 1) {
$stmt->fetch();
} else {
$order_id = 0;
}
//addItemsToOrderItems
for ($i = 0; $i < count($cart); $i++) {
$product = json_decode($cart[$i]);
$product_id = $product->productid;
$quantity = $product->count;
$sql = "INSERT INTO `order_items` (`order_id`, `product_id`, `quantity`) VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param("iii", $order_id, $product_id, $quantity);
if ($stmt -> execute()) {
$successaddItemsToOrderItems = true;
} else {
$successaddItemsToOrderItems = false;
}
}
$stmt->close();
$db -> close();
if ($successorderToDB && $successaddItemsToOrderItems) {
echo "success";
} else {
echo "failure";
}
}
/*function getIdByEmail($email) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
$sql = "SELECT `user_id` FROM `user` WHERE `username` = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id);
if ($stmt->num_rows == 1) {
$stmt->fetch();
} else {
$user_id = 0;
}
$stmt->close();
$db->close();
return $user_id;
}*/
/*function addOrdertoDB($user_id, $total, $payment) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
$sql = "INSERT INTO `order_details` (`user_id`, `total`, `payment_id`) VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param("iis", $user_id, $total, $payment);
if ($stmt->execute()) {
return true;
} else {
return false;
}
$stmt->close();
$db->close();
}*/
/*function getLastInsertID() {
require_once($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
$sql = "SELECT LAST_INSERT_ID() FROM `order_details`";
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($order_id);
if ($stmt->num_rows == 1) {
$stmt->fetch();
} else {
$order_id = 0;
}
$stmt->close();
$db->close();
return $order_id;
}*/
/*function addItemsToOrderItems($order_id, $cart) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
for ($i = 0; $i < count($cart); $i++) {
$product = json_decode($cart[$i]);
$product_id = $product->product_id;
$quantity = $product->quantity;
$sql = "INSERT INTO `order_items` (`order_id`, `product_id`, `quantity`) VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param("iii", $order_id, $product_id, $quantity);
if ($stmt->execute()) {
return true;
} else {
return false;
}
$stmt->close();
$db -> close();
}
}*/