我正在尝试创建我的第一个AJAX调用。我所要做的就是向我的数据库发送一条消息,其中包含user_id,消息和日期。
截至目前,当我点击提交按钮时,甚至都没有发生任何事情。为什么这不提交,我不确定我是否正确创建了ajax调用。
我做错了什么?
我的ajax电话
$(document).ready(function(){
$("#$(".contactButton")").on("change", function(){
$user = this.value;
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: "username="+$user,
success: function(text){
if(text == "Error!"){
alert("Unable to get user info!");
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Payment Status Changed!');
$('.announcement_success').delay(5000).fadeOut(400);
alert(data);
} else {
var txtArr = text.split('|');
}
},
error: function(xhr, textStatus, errorThrown){
alert(textStatus + "|" + errorThrown);
}
});
});
});
我的表格
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements" >
<textarea rows="4" cols="50" id="announcement_message "name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<input type="button" class="contactButton" value="Add Announcement" id="submit">
</label>
</form>
PHP文件insert_announcements
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('isi', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
答案 0 :(得分:0)
Jquery Code - 点击Add announcement按钮时,会调用libunistring进行ajax调用。
<form action="" method="POST" id="insert_announcements" >
<textarea rows="4" cols="50" id="announcement_message"name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<input type="text" id="userid" value="" placeholder="user id">
<label for="contactButton">
<input type="button" class="contactButton" value="Add Announcement" id="submit">
</label>
</form>
这应该是你的HTML -
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (mysqli_escape_string($_POST['userid']), mysqli_escape_string($_POST['msg']), NOW())");
现在代码为php -
{{1}}