This code executes post.php
:
function SubmitForm() {
var input = $("#input").val();
var user = "anon";
$.post("post.php", {input: input, user: user}, function(data) {});
alert("hello");
}
But if I remove a line, this doesn't:
function SubmitForm() {
var input = $("#input").val();
var user = "anon";
$.post("post.php", {input: input, user: user}, function(data) {});
}
Seems irrational, but why is this happening?
The PHP which the JS should call inserts some values into the database:
<?php
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
// Create connection
$con = mysqli_connect($dbhost, $dbuser, $dbpass);
// Check connection
if (!$con) {
die("Database connection failed: " . mysqli_error());
}
// Select database
$db_select = mysqli_select_db($con, $dbname);
// Check selection
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$message = $_POST["input"];
$user = $_POST["user"];
echo $message;
echo $user;
$query = "INSERT INTO posts (user, message) VALUES ('$user', '$message')";
mysqli_query($con, $query);
?>
Your problem is that this function is being called in an onsubmit
/onclick
event handler. AJAX is asynchronous, meaning it runs in the background. When you call $.post
, the code continues on and the callback is called at some point in the future.
What is happening is that the form is being submitted, so the page is being redirected. This is happening before the AJAX call finishes. The alert
pauses the browser, so it gives the AJAX call a chance to finish.
You need to block browser from performing the "default" action.
<input type="submit" class="button" id="button_post" value="POST" onclick="SubmitForm(); return false;">
P.S. I suggest that you bind event handlers in JavaScript versus inline handlers.
<input type="submit" class="button" id="button_post" value="POST">
<script>
$(function(){
$('#button_post').click(function(e){
e.preventDefault();
SubmitForm();
});
});
</script>
It probably does work (or the POST
is failing in both cases).
To see whether it really works, your alert should be inside of the callback - as that is the code that will run if the request succeeds.
function SubmitForm() {
var input = $("#input").val();
var user = "anon";
$.post("post.php", {input: input, user: user}, function(data) {
alert(data);
});
}
It is always worth firing up your browser's developer tools to see the network request and check that it works.
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