Reputation:
I am trying to make my submit button send data to my PHP file without reloading, however, when I use this call it doesn't send any data and neither is saved in my database.
$('#formSubmitData').on('submit', function(event) {
event.preventDefault();
var msg = $('#textareaSubmitData').val();
$.ajax({
url: 'searchData.php', //this is ALSO how the text is being send to the database to be retrieved later on.
type: 'POST',
data: {message:msg},
success: function(data) {
console.log(data);
data = msg;
alert(data);
}
});
});
The alert shows the correct value, but in my database, the rows remain empty.
How the PHP code looks like:.
if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
include_once 'dbConn.php';
$name = $_SESSION['userName'];
$msg = $_POST['textareaSubmitData'];
$stmt = $conn->prepare("INSERT INTO messages (name, message) VALUES (?, ?)");
$stmt->bind_param('ss', $name, $msg);
$name = $_SESSION['userName'];
$msg = $_POST['textareaSubmitData'];
$stmt->execute();
$conn->close();
$stmt->close();
} else {
header('Location: index.php?send=failure');
exit();
}
}
Upvotes: 0
Views: 1417
Reputation: 8945
Also – definitively, "look at(!)" what is being sent, using the debugging features of your browser. When the AJAX call goes off, you can see an HTML POST
being done – so, you can see exactly what the URL is, and exactly what data is (or, isn't) being supplied.
On the host side, you can also do things like print_r($_POST)
so that you can once again see what PHP has received.
My experience is that, once you can see what's happening, debugging is very quick and easy. Whereas, guessing leads nowhere.
Upvotes: 0
Reputation: 1301
You are sending the value of submit button in data. You need to send the form data to your server.
$('#formSubmitData').on('submit', function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: 'searchData.php', //this is ALSO how the text is being send to the database to be retrieved later on.
type: 'POST',
data: data,
success: function(data) {
data = msg;
alert(data);
}
});
});
Upvotes: 1
Reputation: 57121
Think there are 2 issues, the first is that you need to make sure the data to send is an object and not just a value...
data: { textareaSubmitData: msg },
The second is that when you try and process the data, your first line is...
if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
So this is looking for some POST data in 'submit' - which you don't send. So as you (now) just send 'textareaSubmitData' - check if that is set...
if (isset($_POST['textareaSubmitData']) && $_SERVER['REQUEST_METHOD'] === "POST") {
Upvotes: 1