Javascript function only works if there's an alert

function, javascript, jquery, post

Solution

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>

Problem

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); ?> ```

Original source

Related problems