我必须通过jQuery和ajax方法插入数据。但是数据没有插入数据库中。请帮助我这种方法是错误的吗?
这是我的代码,
form.html
<!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- <script src="jquery-3.1.0.js" type="text/javascript"></script>-->
<script type="text/javascript">
function submitData()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
var contact = document.getElementById('contact')
$.ajax({
type: 'POST',
url: 'data_ins.php',
data:{
uname:name,
uage:age,
ucontact:contact
},
success: function(response){
$('#success_para').html("Data inserted");
}
});
return false;
}
</script>
</head>
<body>
<form method="POST" onsubmit="return submitData();">
name : <input type="text" name="name" id="name"> <br>
age : <input type="text" name="age" id="age"> <br>
contact : <input type="text" name="contact" id="contact"> <br>
<input type="submit" name="submit" >
</form>
<p id="success_para"></p>
</body> </html>
和,data_ins.php
<?php
$conn = mysqli_connect("localhost","root","","test_db");
$name = $_POST['uname']; $age = $_POST['uage']; $contact = $_POST['ucontact'];
if(!$conn) {
echo"<script>alert('Database Connection Failed or invalid connection');</script>"; }
else {
$sql = "insert into records (name, age, contact) values ('$name', '$age', '$contact')"; mysqli_query($conn, $sql);
mysqli_error($conn); }
?>
请告诉我代码中的错误。提前谢谢。
答案 0 :(得分:1)
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
您的&#34;提交&#34;按钮会导致页面重新加载,因此您无法在onSuccess中看到查询结果。
<input type="button" name="submit" onclick="submitData();" >
你检查了你的回答吗?您也可以在浏览器的检查器中查看它。
success: function(response){
$('#success_para').html(response);
}