1

I am writing a Shoutbox. The HTML file has 2 buttons: refresh - refreshes all the messages and submit - submits message and refreshes page messages.

Everything works perfectly but one issue. When I click submit, the page doesn't refresh with latest message. But everything works fine afterwards.

HMTL file:

<head>
        <link rel="stylesheet" href="css/style.css" type="text/css" />
        <meta charset="utf-8" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">    </script> 
        <script src="script.js"></script>
</head>

<body>
<div id="wrap">
    <div id="input">
    <form>
        <input type="text" name="name" id="name" placeholder="Enter a name">
        <input type="text" name="message" id="message" placeholder="Enter a message">
        <input type="button" id="refresh" value="Refresh">
        <input type="button" id="submit" value="Submit">
    </form>
</div>
<div id="messages">
        <ul id="messageList"></ul>
</div>
</div>

</body>
</html>

JavaScript File

$(document).ready(function() {
    $('#refresh').on('click', function(){
        $("#messageList").load( "messages.php");
        event.preventDefault();
    });
});

$(document).ready(function() {
    $('#submit').on('click', function(){
        var name = $("#name").val();
        var message = $("#message").val();
        var dataString = 'name='+ name + '&message='+ message;

        $.post( "newmessage.php", dataString );

        event.preventDefault();

        $("#messageList").load( "messages.php");

        event.preventDefault();
    });
});

messages.php:

<?php
//error_reporting(0);
include 'database.php';

//Create Select Query
$query = "SELECT * FROM shoutbox ORDER BY time DESC";
$shouts = mysqli_query($con, $query);


   while($row = $shouts->fetch_object()) { 
            $time = $row->time;
            $name = $row->name;
            $message = $row->message;

            echo "<li>".$time." - <b>".$name.": </b>".$message."</li>";
}

$con->close();

?>

newmessage.php:

<?php
//error_reporting(0);
include 'database.php';

if(isset($_POST['name']) && isset($_POST['message']))
{
    $name = '"'.$_POST['name'].'"';
    $message  = '"'.$_POST['message'].'"';

    $datum = new DateTime();
    $timeStamp = $datum->format('Y-m-d H:i:s');

    $insert_row = $con->query("INSERT INTO shoutbox(name, message) VALUES($name, $message)");
}

if($insert_row) {
} else {
    die('Error : ('. $con->errno .') '. $con->error);
}

$con->close();

?>
jimbo123
  • 289
  • 3
  • 7
  • 13
  • 1
    AJAX calls are asynchronous if i see your code first thing i notice is that you call both post as load in the same function call my first guess would be that the load is done quicker then the post. – melvin May 08 '15 at 18:15
  • your right. I put the AJAX requests in 2 functions showMessages() and submitMessage(). Everything works fine now :) – jimbo123 May 08 '15 at 18:24
  • Good to hear. Just a small other point i see you use $('#submit').on('click',. This will work only when you click the button. Consider to use https://api.jquery.com/submit/ as it will also be fired when you submit your form by code. – melvin May 08 '15 at 18:31

2 Answers2

1

From this answer:

I'd recommend strongly that you take the time to understand the nature of asynchronous calls within JavaScript

Please follow the link, there's more info there.

To your code to work:

$(document).ready(function() {
  $('#submit').on('click', function(event){ // << event was missing
    var name = $("#name").val();
    var message = $("#message").val();
    var dataString = 'name='+ name + '&message='+ message;
    event.preventDefault();
    $.post("newmessage.php", dataString, function(){
      // this function is a callback, called on AJAX success
      $("#messageList").load( "messages.php");
    });
  });
});
Community
  • 1
  • 1
Pedro Sanção
  • 1,328
  • 1
  • 11
  • 16
  • thanks I read about it and understood it before but this was the first time I faced a challenge in my code – jimbo123 May 08 '15 at 19:46
0

This should do the job. Make sure if you are using event.preventDefault(), you pass the event variable to the function. This can also test if the message was posted successfully

$('#submit').on('click', function(event){
        event.preventDefault();
        var name = $("#name").val();
        var message = $("#message").val();
        var dataString = 'name='+ name + '&message='+ message;

        var posting=$.post( "newmessage.php", dataString );

        posting.done(function(data){
              $("#messageList").load( "messages.php");
        });
        posting.fail(function(){
            alert("Something is not right with your message. Please Try Again")
        })

    });
Raj Nandan Sharma
  • 3,694
  • 3
  • 32
  • 42