Quando crio um novo input, ele não é inserido na tabela mysql
Criei um formulário para envio dos pedidos, assim que o cliente colocar os dados e concluir a compra. Fiz a maior parte com requisições ajax, está tudo funcionando perfeitamente, e como certeza disso, após clicar em finalizar compra, o cliente é redirecionado para página '4d-thank-you.php', onde ele recebe a mensagem de que o pedido foi efetuado com sucesso. Mais eu quero adicionar mais um campo, para o cliente inserir o endereço, mais já tentei de todas as formas, efetuo todas modificações certinhas, e quando clico em Finalizar compra, o cliente não é mais redirecionado para a página '4d-thank-you.php', ou seja a requisição não está sendo feita com sucesso. Vou deixar abaixo os códigos que fazem o carrinho funcionar e a inserir os dados do formulário no Mysql, esse código está funcionando, porém, quando adiciono mais um campo ele para de funcionar, se puderem me ajudar preciso urgente para um projeto. Esse é o carrinho, e a parte onde o cliente coloca as informações para concluir o pedido. <?php
// SHOPPING CART WILL BE STORED IN THE SESSION
// $_SESSION['cart'][PRODUCT ID] = QUANTITY
require __DIR__. DIRECTORY_SEPARATOR. "lib". DIRECTORY_SEPARATOR. "2a-config.php". switch ($_POST['req']) { /* [INVALID REQUEST] */ default: echo "INVALID REQUEST". break. /* [ADD ITEM TO CART] */ case "add": if (is_numeric($_SESSION['cart'][$_POST['product_id']])) { $_SESSION['cart'][$_POST['product_id']] ++. } else { $_SESSION['cart'][$_POST['product_id']] = 1. } echo "Produto adicionado ao carrinho". break. /* [COUNT TOTAL NUMBER OF ITEMS] */ case "count": $total = 0. if (count($_SESSION['cart'])>0) { foreach ($_SESSION['cart'] as $id => $qty) { $total += $qty. } } echo $total. break. /* [SHOW CART] */ case "show": // Fetch products require PATH_LIB. "2b-lib-db.php". require PATH_LIB. "4c-lib-cart.php". $cartLib = new Cart(). $products = $cartLib->details(). // Cart contents in HTML $sub = 0. $total = 0.?> <h1 style="font-family: 'Gotham Light. '" class="text-center text-info mt-2">Minhas compras . <i class="fa fa-gift"></i></h1> <table id="cart-table"> <tr> <th>Remover</th> <th>Quantidade</th> <th>Nome do produto</th> <th>Preço</th> </tr> <?php if (count($_SESSION['cart'])>0) { foreach ($_SESSION['cart'] as $id => $qty) { $sub = $qty * $products[$id]['product_price']. $total += $sub.?> <tr> <td> <a href="#" class="text-danger lead" onclick="cart.remove(<?= $id?>). "> <i class="fa fa-trash"></i></a> </td> <td><input class="form-control" id='qty_<?= $id?>' onchange='cart.change(<?= $id?>). ' type='number' value='<?= $qty?>'/></td> <td><?= $products[$id]['product_name']?></td> <td><?= sprintf("$%0.2f", $sub)?></td> </tr> <?php }} else {?> <tr align="center" ><td colspan="3" align="center"> . Seu carrinho está vazio .  . <button class="btn btn-success"><a style="color: white. text-decoration: none. " href="index.php">Continuar comprando</a></button></td></tr> <?php }?> <tr> <td colspan="2"></td> <td><strong>Preço total</strong></td> <td><strong><?= sprintf("$%0.2f", $total)?></strong></td> </tr> </table> <hr> <?php if (count($_SESSION['cart']) > 0) {?> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg"><i class="fa fa-credit-card"></i> . Finalizar Compra</button>
<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <form class="p-2" onsubmit="return cart.checkout(). "> <div class="form-row"> <div class="form-group col-md-6"> <label for="co_name">Nome completo</label> <input type="text" class="form-control" id="co_name" placeholder="Nome completo"> </div> <div class="form-group col-md-6"> <label for="co_email">Seu email</label> <input type="email" class="form-control" id="co_email" value="" disabled> </div> </div> <div class="form-group"> <label for="co_address">Rua, Sítio</label> <input type="text" class="form-control" id="co_address" placeholder="Digite a rua ou sítio onde mora"> </div> <div class="form-group"> <label for="inputAddress2">Bairro</label> <input type="text" class="form-control" id="inputAddress2" placeholder="Digite o bairro onde mora"> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputState">Município</label> <select id="inputState" class="form-control" disabled> <option>União dos Palmares</option> </select> </div> <div class="form-group col-md-2"> <label for="inputZip">Zip</label> <input type="text" class="form-control" id="inputZip"> </div> </div> <input type="submit" class="btn btn-info btn-block" value="checkout">
</form> </div> </div>
</div> <!---- FIM FINALIZAR COMPRA E MAIS DUVIDAS -----> <?php } break. /* [CHANGE QTY] */ case "change": if ($_POST['qty'] == 0) { unset($_SESSION['cart'][$_POST['product_id']]). } else { $_SESSION['cart'][$_POST['product_id']] = $_POST['qty']. } echo "Ação realizada com sucesso". break. /* [CHECKOUT] */ // @TODO // Beef up this section on your own! // There are no error & security checks in this simple example // You may also want to add more of your own checkout procedures here case "checkout": require PATH_LIB. "2b-lib-db.php". require PATH_LIB. "4c-lib-cart.php". $cartLib = new Cart(). if ($cartLib->checkout($_POST['name'], $_POST['email'])) { $_SESSION['cart'] = []. echo "OK". } else { echo $cartLib->error. } break. /* [ALTERNATIVE CHECKOUT] */ // This version sends an email to the customer on successful checkout case "checkout-email": require PATH_LIB. "2b-lib-db.php". require PATH_LIB. "4c-lib-cart.php". $cartLib = new Cart(). if ($cartLib->checkout($_POST['name'], $_POST['email'])) { $_SESSION['cart'] = []. // @TODO // Format this email message as you see fit $order = $cartLib->get($cartLib->orderID). $to = $_POST['email']. $subject = "Order Received". $message = "". foreach ($order['items'] as $pid=>$p) { $message.= $p['product_name']. " - ". $p['quantity']. "<br>". } $headers = implode("\r\n", [ 'MIME-Version: 1.0', 'Content-type: text/html. charset=utf-8', 'From: john@doe.com' ]). echo @mail($to, $subject, $message, $headers)? "OK": "ERROR sending email!". } else { echo $cartLib->error. } break. }?> Aqui é feita a inserção do formulário no Mysql <?phpclass Cart extends DB {
function details () { // details(): get details of items in cart // Empty if (count($_SESSION['cart'])==0) { return false. } // Get products in cart $sql = "SELECT * FROM `products` WHERE `product_id` IN (". $sql.= str_repeat('?,', count($_SESSION['cart']) - 1). '?'. $sql.= ")". return $this->fetch($sql, array_keys($_SESSION['cart']), "product_id"). } function checkout ($name, $email) { // checkout(): checkout, create new order // PARAM $name: customer's name // $email: customer's email address // Init $this->start(). // Create the order entry first $pass = $this->exec( "INSERT INTO `orders` (`order_name`, `order_email`) VALUES (?,?)", [$name, $email] ). // Insert the items if ($pass) { $this->orderID = $this->lastID. $sql = "INSERT INTO `orders_items` (`order_id`, `product_id`, `quantity`) VALUES ". $cond = []. foreach ($_SESSION['cart'] as $id=>$qty) { $sql.= "(?,?,?),". array_push($cond, $this->orderID, $id, $qty). } $sql = substr($sql, 0, -1). ". ". $pass = $this->exec($sql, $cond). } // Finalize $this->end($pass). return $pass. } function get ($id) { // get (): get order // PARAM $id: order ID $order = $this->fetch( "SELECT * FROM `orders` WHERE `order_id`=?", [$id] ). $order['items'] = $this->fetch( "SELECT * FROM `orders_items` LEFT JOIN `products` USING (`product_id`) WHERE `orders_items`.order_id=?", [$id], "product_id" ). return $order. }
}?> Esse é o script, que ajuda nas funcionalidades do Carrinho de compras. // @TODO -// There is literally little to no interface in this script.
// Feedback meesage such as "item added to cart" uses raw Javascript alert
// Bootstrap, jQuery, Angular, or vanilla CSS - Implement your own interface.
var cart = { ajax: function (opt) { // ajax(): helper function, do AJAX request // PARAM opt.data: data to be sent, an object with key-value pairs // opt.url: target URL // opt.target: (optional) ID of HTML element, put server response in here if provided // opt.load: (optional) function to call when AJAX load is complete // DATA var data = null. if (opt.data) { data = new FormData(). for (var d in opt.data) { data.append(d, opt.data[d]). } } // AJAX var xhr = new XMLHttpRequest(). xhr.open('POST', opt.url, true). xhr.onload = function(){ if (xhr.status!=200) { console.log(xhr). alert("AJAX error. Server responded with error code " + xhr.status + " " + xhr.statusText). } else { if (opt.target) { document.getElementById(opt.target).innerHTML = this.response. } if (typeof opt.load == "function") { opt.load(this.response). } } }. xhr.send(data). }, add: function (id) { // add (): add item to cart // PARAM id: product ID cart.ajax({ url: "4b-ajax-cart.php", data: { req: "add", product_id: id }, load: function (res) { cart.count(). // @TODO alert(res). } }). }, count: function () { // count(): update items count cart.ajax({ url: "4b-ajax-cart.php", data: { req: "count", }, target: "page-cart-count" }). }, toggle: function (reload) { // toggle(): show/hide cart // PARAM reload: force cart reload? var pgPdt = document.getElementById("page-products"), pgCart = document.getElementById("page-cart"). if (reload || pgCart.classList.contains("ninja")) { cart.ajax({ url: "4b-ajax-cart.php", data: { req: "show", }, target: "page-cart", load: function () { pgPdt.classList.add("ninja"). pgCart.classList.remove("ninja"). } }). } else { pgPdt.classList.remove("ninja"). pgCart.classList.add("ninja"). } }, change: function (id) { // change(): change quantity var qty = document.getElementById("qty_"+id).value. cart.ajax({ url: "4b-ajax-cart.php", data: { req: "change", product_id: id, qty: qty }, load: function (res) { cart.count(). cart.toggle(1). // @TODO alert(res). } }). }, remove: function (id) { // remove(): remove item from cart document.getElementById("qty_"+id).value = 0. cart.change(id). }, checkout: function () { // checkout (): checkout cart.ajax({ url: "4b-ajax-cart.php", data: { req: "checkout", // @TODO // Change to checkout-email if you want an email to be sent on checkout // req: "checkout-email", name: document.getElementById("co_name").value, email: document.getElementById("co_email").value, }, load: function (res) { if (res=="OK") { window.location = "4d-thank-you.php". } else { gen.nShow(res). } } }). return false. }
}. window.addEventListener("load", cart.count). Discussão (0)
Carregando comentários...