我有一個網站,您可以在文本框中鍵入內容,並且會發送我寫入數據庫的內容。發送信息到數據庫,無需重新加載頁面
我一直堅持我的網頁不得不重新加載,這是在我的情況非常麻煩。我不熟悉Ajax,但我聽說它可以用來完成這項任務。我有2個文件,其中一個名爲demo.php,它將信息發送到服務器,此時有一個標頭,可將我重定向到我不想要的那個頁面。
我希望能夠在不重新加載頁面的情況下將數據發送給服務器。另一個頁面是index.php這是我正確的文本框併發送文本到我的數據庫這兩個文件都列在下面。
這是demo.php
<?php
header("Location: http://mywebsite.com");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "working";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<form action="demo.php" method="post" />
<p> <input id="textbox" type="text" name="firstname" placeholder="Enter What You Want Your Message To Be" /></p>
<input id="textbox1" type="submit" value="Submit" />
</form>
我在index.php的第二次嘗試
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="button" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
});
</script>
</html>
[基本PHP和AJAX]的可能的複製( http://stackoverflow.com/questions/5298401/basic-php-and-ajax) – VeeeneX