I'm trying to make a shopping cart using node, SQL, and jade. Everything work sure, but when I reload the page items count in cart is increasing.
I try to make an ajax queries and when I send dates on server I see the error like unknown column undefined in 'where clause'. But when I try to send it without ajax everything working okay. Also it working okay when I send it from ejs template. So, which issue I made?
node.js code
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var session = require('express-session');
var conn = require('./connection');
var connection = conn.connection();
var data;
connection.query('SELECT * FROM products', function (err, rows) {
if (err) throw err;
data = rows;
});
router.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
var cart_data, cart = {};
router.post('/checkout', function (req, res) {
cart = req.session.cart;
if (!cart) {
cart = req.session.cart = {}
}
var id = req.body.id;
var count = parseInt(req.body.count, 10);
cart[id] = (cart[id] || 0) + count;
var ids = Object.keys(cart);
if (ids.length > 0) {
connection.query('SELECT * FROM products WHERE id IN (' + ids + ')', function (err, rows) {
if (err) throw err;
cart_data = rows;
res.render('index', {title: 'Shopping', data: data, currency: 'Rub. ', cart_data: rows, cart: cart});
});
} else {
res.render('index', {title: 'Shopping', data: data, currency: 'Rub. ', cart_data: cart_data});
}
});
router.get('/checkout', function (req, res) {
res.render('index', {title: 'Node Shopping', data: data, currency: 'Rub. ', cart_data: cart_data, cart: cart});
});
jade
extends layout
block content
div(class='container')
h1= title
p Welcome to #{title}
div(class='items')
each item in data
div(class='item')
h3=item.name
p=item.description
div(class='price')
span=currency + item.price
div(class='form-items')
input(type='text', name='count', value='1')
button(type='submit', class='item-select', onclick='showCustomer()', name='id', id='#{item.id}', value='#{item.id}')'add to cart'
ajax
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/checkout", true);
xhttp.send();
}
Thanks