Kenth Mirta
Kenth Mirta

Reputation: 55

jQuery .ajax calls success function before sending request

I am trying to make a chatbox for my website. Basically, the user types their chat into the textarea with id chat-input. When the user clicks on the Enter button, it calls the sendChat() function. This function sends the request to a php file on the server which adds the user's chat to the chatlog (a text file on the server). On success, the javascript is supposed to call the update() function which performs a get request to the chatlog.txt file on the server and load it into the div with id prev-chats. The problem is that the javascript calls update() before the server responds, and so the prev-chats is not updated until the page is refreshed. I can tell this because
a) the chats are not updating until I refresh the page, and
b) In Google Chrome, after pressing F12, the network tab shows the GET request for chatLog.txt before the POST request for submitting the chat.

Here is my HTML code

            <div id="prev-chats" class="well"></div>
            <textarea id="chat-input"></textarea>
            <button class="btn btn-default" onclick="sendChat()">Enter</button>
            <button class="btn btn-default" onclick="update()">Update</button>
            <script type="text/javascript">

                function sendChat(){
                    var message = $("#chat-input").val();
                    var datavar = {"message": message};
                    console.log("Sending message to server");
                    $.ajax({
                        type: "POST",
                        async: "false",
                        url: "chatResponse.php",
                        data: datavar,
                        success: update()
                    });
                    console.log("Message sent to server");
                };
                function update(){
                    $("#prev-chats").load("chatLog.txt");
                    console.log("chat updated");
                }

                update();
            </script>

And here is my PHP code

<?php
$chatLog = fopen("chatLog.txt","a+") or die("Eror loading chat... Please try again later");
$chat = htmlspecialchars($_POST['message']);
fwrite($chatLog, $chat . "<br>");
fclose($chatLog); 
?>

Here is what appears in my console

(index):85 chat updated
(index):72 Sending message to server
(index):85 chat updated
(index):81 Message sent to server

Upvotes: 4

Views: 1120

Answers (2)

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

Try using

success: update

instead of

success: update()

Upvotes: 5

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

Change your ajax like this

$.ajax({
                    type: "POST",
                    async: "false",
                    url: "chatResponse.php",
                    data: datavar,
                    success:function(){ update()}
                });

Upvotes: 0

Related Questions