1
我想使用ajax將表單中的數據插入數據庫。當我運行它時,它只顯示index.php代碼,什麼都不做。我無法找出錯誤。所以,請幫助我運行此代碼。使用ajax插入MySql數據庫
的index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input type="text" id="name" placeholder="Enter Text">
<button id="submit" onClick="js()" type="button"> Submit</button>
<script>
function js() {
var name = document.getElementById("name").value ;
$.ajax({
type:'POST',
data: name,
url:"insert.php",
success:function(result){
alert(success);
}
});
}
</script>
</body>
</html>
insert.php
<?php
$connection = mysqli_connect('localhost', 'root', '', 'sample');
if($_POST['name']){
$name=$_POST['name'];
$q= "insert into test ('$name')";
$query = mysqli_query($connection, $q);
if($query){
echo 'inserted';
}
}
?>
什麼是'test'的表結構?如果多於1列,則需要指定列名稱。你也可以執行'$ query = mysqli_query($ connection,$ q)或者死(mysqli_error($ connection));'調試 – Sean
你需要在'index.php'文件中包含'jquery'。一種資源可以是[this](https://developers.google.com/speed/libraries/#jquery) –