我想要实现的 - 是将变量的值存储在数据库中。现在我的js代码中有var currentValue,它等于输入字段的值。我必须实现的 - 是将该变量的值传递给sql数据库。其余代码工作正常 - 我可以存储日期时间和IP地址。
HTML:
<html>
<head>
<?php include('add.php') ?>
<link rel = "stylesheet" href = "styles.css" type = "text/css">
<link href="https://fonts.googleapis.com/css?family=Vollkorn" rel="stylesheet">
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<title>Тестовое задание Трофимов</title>
</head>
<body>
<div id = "main_container">
<div id = "success_message">
<p>Товар добавлен в корзину</p>
<div id = "tooltip_arrow"></div>
</div>
<div class = "clearfix"></div>
<div id = "form">
<input name = "submit" type = "button" value = "купить" id = "button">
<div class = "quantity_counter" id = "minus"><a href="#" id="decrease">–</a></div>
<input type = "text" size = "3" value = "1" id = "input_quantity" name = "input_quantity"></input>
<div class = "quantity_counter" id = "plus"><a href="#" id="increase">+</a></div>
</div>
<div class = "clearfix"></div>
<div id = "error_message"><br/><p>Укажите количество товаров!</p></div>
</div>
<script type ="text/javascript" src = "js.js"></script>
</body>
</html>
JS:
$(document).ready(function(){
var currentValue = 1;
$('#increase').click(function(e){
e.preventDefault();
currentValue = parseInt($('#input_quantity').val());
currentValue++;
$('#input_quantity').val(currentValue);
});
$('#decrease').click(function(e){
e.preventDefault();
currentValue = parseInt($('#input_quantity').val());
currentValue--;
if(currentValue < 1) {
currentValue = 0;
}
$('#input_quantity').val(currentValue);
});
function Messager(){
this.showMessage = function(container){
$(container).fadeIn();
setTimeout(function() {
$(container).fadeOut();
}, 3000);
};
this.success = function(){
this.showMessage("#success_message");
};
this.error = function(){
this.showMessage("#error_message");
};
}
$('#button').click(function(e){
$.ajax({
url: "add_to_cart.php",
type: 'post',
dataType: 'html',
data: {
id: currentValue,
}
}).done(function(response){
var msg = new Messager();
if (currentValue != 0) {
msg.success();
} else {
msg.error();
}
});
});
});
PHP:
<?php
$servername = "myhost";
$username = "myUsername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$currentValue = $_POST['currentValue'];
$date = date('Y/m/d H:i:s');
$sql = sprintf("INSERT INTO test (amount, ip, date)
VALUES ('%s', '%s', '%s')", $currentValue, $_SERVER['REMOTE_ADDR'], $date);
if ($conn->query($sql) === TRUE) {
echo '<script type="text/javascript">',
'Messager();',
'</script>'
;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
无论我在输入字段中有什么值 - 它在SQL中显示为0。