I am attempting to create an ajax call to my php file to insert data. The issue I am running into is the data I send over is not being recognized.
The variables you will see in the php file is what is not being recognized:
$home_comment = $_POST['home_comment'];
$username = $user->data()->username;
I am running an ini file that has the connection $con within it and it always has the $user variable.
Does anyone see what I am doing wrong?
<form action="" method="POST" id="comment-form">
<label for="comment">Comment</label>
<textarea cols="15" id="home-comment" name="comment" placeholder="Message" rows="5" maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
Ajax:
$("#comment-form").on("submit", function (event) {
//event.preventDefault();
var home_comment = $("#home_comment").val();
$.ajax({
url: "comment-send.php",
type: "POST",
data: {
"home_comment": home_comment
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to post comment!");
alert(data);
} else {
/*$("#newsletter-form")[0].reset();
$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();*/
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
PHP file:
$home_comment = $_POST['home_comment'];
$username = $user->data()->username;
$okay = true;
if ( $okay ) {
$comment_insert = "
INSERT INTO home_comments
(id, user_id, username, comment)
VALUES(?, ?, ?, ?)
";
$comment_stmt = $con->prepare($comment_insert);
$comment_stmt->execute(array('', $user_id, $username, $home_comment));
}
return false;at the bottom of your submit? If it's not there and everything happens quickly you may not see a page flash and you've just submitted to the page you're on.return false;after your AJAX function or a submit button will submit old school style.//event.preventDefault();toovar home_comment = $("#home_comment").val();vs<textarea cols="15" id="home-comment"... >See the issue? Maybe you should justserialize()the form to preventtyopsin the future. Hint:_and-are not equal.