I am trying to create my first AJAX call. All I am trying to do is send a message to my database that will hold a user_id, message, and date.
As of now nothing is even happening when I hit the submit button. Why is this not submitting and I'm not sure if I am creating the ajax call correctly.
What am I doing wrong?
My ajax call
$(document).ready(function () {
$("#submit_announcement").on("click", 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);
}
});
});
});
The Form
<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 file insert_announcements.php
$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!";
}
You have the jquery selector for your button wrong, change it to:
$("#submit").on("click", function(){
You are triggering the click for an element with id #submit_announcement
which is different from the id of your form submit button. Change $("#submit_announcement").on("click", function(){
to
$("#submit").on("click", function(){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With