可能是主题/名称中的重复,但以前的解决方案都不会起作用,因为我遗漏了某些内容或者还有其他内容正在发生。
表单 - 看似随意 - 失败(不改变任何字段中的数据,只是在html中设置的默认值),当它成功时,PHP文件只记录两个值,第二个和第四个(都是纯的)数字/整数)。它不回显的两个是1:文本字段和3:浮点数。
这是.php选择的结果 -
Connected
'' + '8080' + '' + '1'
这是.html和.js,我在这里错过了什么?
<form id="form_0" name="form_0" method="post" action="">
<input type="text" id="coinname" name="coinname" value="litecoin"><br>
<input type="number" id="coins" name="coins" value="8080"><br>
<input type="number" id="cost" name="cost" value="0.0808"><br>
<input type="number" id="show" name="show" value="1"><br>
<input type="submit" id="submit" name="submit" value="Save">
</form>
<script>
$("#form_0").submit(function() {
var selectedcoin = $("#coinname").val();
var coins = $("#coins").val();
var buyprice = $("#cost").val();
var show = $("#show").val();
$.ajax({
type: "POST",
url: "write-database.php",
data: "selectedcoin=" + selectedcoin + "&coins=" + coins + "&buyprice=" + buyprice + "&show=" + show,
success: function(data) {
alert(data);
}
});
});
</script>
这是.php
<?php
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo "Connected <br>";
}
$selectedcoin=$_POST['selectedcoin'];
$coins=$_POST['coins'];
$buyprice=$_POST['buyprice'];
$show=$_POST['show'];
$sql= mysqli_query($conn,"INSERT INTO coin_price (coin_name, coin, price, display) VALUES ('".$selectedcoin."','".$coins."','".$buyprice."','".$show."')");
echo "'$selectedcoin' + '$coins' + '$buyprice' + '$show'";
mysqli_close($con);
?>
答案 0 :(得分:1)
只需使用serialize方法从表单值中获取所有数据,作为$ _POST全局变量中的输入名称。
<form id="form_0" name="form_0" method="post" action="">
<input type="text" id="coinname" name="coinname" value="litecoin"><br>
<input type="number" id="coins" name="coins" value="8080"><br>
<input type="number" id="cost" name="cost" val="0.0808"><br>
<input type="number" id="show" name="show" value="1"><br>
<input type="submit" id="submit" name="submit" value="Save">
</form>
<script>
$("#form_0").submit(function() {
e.preventDefault();
$.ajax({
type: "POST",
url: "write-database.php",
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<?php
$selectedcoin=$_POST['coinname'];
$coins=$_POST['coins'];
$buyprice=$_POST['cost'];
$show=$_POST['show'];
$sql= mysqli_query($conn,"INSERT INTO coin_price (coin_name, coin, price, display) VALUES ('".$selectedcoin."','".$coins."','".$buyprice."','".$show."')");
echo "'$selectedcoin' + '$coins' + '$buyprice' + '$show'";
?>
答案 1 :(得分:1)
我没有禁用刷新页面的默认提交行为...
$("#form_0").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "write-database.php",
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});