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();

?>
3
  • 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. Commented May 8, 2015 at 18:15
  • your right. I put the AJAX requests in 2 functions showMessages() and submitMessage(). Everything works fine now :) Commented May 8, 2015 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 api.jquery.com/submit as it will also be fired when you submit your form by code. Commented May 8, 2015 at 18:31

2 Answers 2

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");
    });
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks I read about it and understood it before but this was the first time I faced a challenge in my code
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")
        })

    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.