Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function only works if there's an alert

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);
?>
like image 761
Sebastian Avatar asked Jan 28 '14 20:01

Sebastian


2 Answers

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>
like image 91
Rocket Hazmat Avatar answered Oct 13 '22 00:10

Rocket Hazmat


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.

like image 20
Fenton Avatar answered Oct 12 '22 23:10

Fenton