我有 2 个输入字段“用户”和“评论”,我希望使用 AJAX 异步保存用户输入,因此无需刷新。到目前为止,我已经将它添加到数据库中,但由于某种原因它是空的。我相信原因是我没有正确附加值。
HTML(JS在head标签之间):
<p>User: <input type="text" id="userName" /></p>
<p>Comment : <input type="text" id="comment" /></p>
<input type="button" value="Submit" onclick="callServer();" />
JS:
function callServer(){
var usr = document.getElementById("user").value;
var cmnt = document.getElementById("comment").value;
var ajaxRequest = XMLHttpRequest();
ajaxRequest.open("POST", "insert.php", true);
ajaxRequest.send(null);
}
PHP:
<?php
// Setting variables for the elements
$user = $_POST['user'];
$comment = $_POST['comment'];
// Establishing connection and selecting db
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db('local',$con);
// Doing the query for the insert
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comment')");
mysql_query($query, $con);
mysql_close($con);
?>