I have a PHP chat application that automatically get messages from database and displays it, currently everything works fine but page must be manually reloaded to display new messages .. How do I implement JQuery ajax to get the messages or silently refresh the specific messages list div without refreshing the whole page? Here is my code (not the full code on the page but the main PHP part I want to use ajax on)
Some answers I read online specified that the PHP code must be on a separate file but Some of the functions and variables in the code below depends on the main file holding this code therefore making it useless if put in a separate file.
<?php // Attempt select query execution global $db; $id = $_GET["id"]; $sql = "SELECT * FROM msg WHERE id='$id' "; if ($result = $db->query($sql)) { if ($result->rowCount() > 0) { while ($row = $result->fetch()) { echo '<div class="chat-messages-item ' . chattype($row['sender']) . '">'; echo '<div class="chat-avatar chat-avatar-lg circle"><img src="' . senderpic($row['sender'], 'thumbnail', '100', '100') . '" alt=""></div>'; echo '<div class="chat-messages-content">'; echo '<div class="chat-messages-bubble ' . $msg_visibility . '">'; echo '<p>' . $row['message'] . '</p>'; echo '</div>'; echo '<ul class="chat-messages-info">'; echo '<li>'; echo '<div class="chat-time chat-seen"><span>' . $row["time"] . '</span>'; echo '</li>'; echo '</ul>'; echo '</div>'; echo '</div>'; } unset($result); } else { echo "<p class='lead'><em>No Chat</em></p>"; } } else { echo "ERROR: Could not able to execute $sql. " . $mysqli->error; }
Thanks
[EDIT]
What i’ve tried : 1. Moving the code above into a separate PHP file and using jquery to to get the page with the following js code but nothing appears and no errors displayed. if i open the page in browser it displays the list of all messages
function update() { $.get("aj/messages.php", function(data) { $("#allmessages").html(data); window.setTimeout(update, 10000); }); }
here is the page structure – Message.php (the main message page that displays other chat information like contacts, messages list, messages, send message input etc)
- aj/msg.php (a php page that gets all the messages from database and wraps it in style/css/html which is also the php code above and expected to be inside a div with the id=”allmessages” located inside Message.php)
Advertisement
Answer
As you mentioned, it is a good practice to separate your PHP Code and your HTML/JavaScript Code. Yes, this may mean you have to write more PHP Code, yet if PHP Scripts must use the same code snippet, this is where PHP include
and include_once
can be used so that you can store specific functions in one script and them import them to other scripts. Please see:
https://www.php.net/manual/en/function.include.php
Currently, there is not enough of an example to be able to properly answer your question. I would suggest that you either create a more functional PHP Script that can accept new Chat input or another that can show the current chat transcript from the Database.
In this use case, each member of the chat must send new data to the database and then periodically get/refresh their view of the transcript. You can send new data to the database at any time and then based on a specific refresh rate, look for differences in the transcript. So your JavaScript will have a few function. Something like
- startChat()
- sendMessage()
- getMessages()
- endChat()
These will send data to the PHP Script and the PHP Script may give a response. This can all be done with AJAX. AJAX is the use of HTTP GET or POST along with JavaScript. This is basically how a Client Side Script language like JavaScript can talk to a Server Side Scripting language like PHP. PHP is processed when the HTTP request is handled by the Web Server and once the data is sent to the browser, PHP can no longer interact with it, this is why it’s a pre-processor. JavaScript can only run in the browser and is processed after all the data from the server is received by the browser.
So if you have some HTML like:
<div class="chat-window"> <div class="transcript"> </div> <div class="user-input"> <input type="text" /> <button>Send</button> </div> </div>
You can use JavaScript to perform tasks when the User types in text and clicks the button. One of those tasks can be to collect the text entered by the User and send it to the PHP Script to be added to the Database. Another task can be to update the field if there are any new messages in the Database since the last time the script checked.
Using jQuery Framework for JavaScript, it might be something like:
function sendMessage(user, txt){ $.post("chat_input.php", { u: user, msg: txt }); }
This creates a HTTP POST call to a PHP Script with a payload of info, such as the User and some Text. You’ll need to collect this information from the HTML based on a specific Event.
$(".user-input > button").click(function(){ sendMessage("jsmith", $(this).parent().find("input").val()); });
This bit of jQuery binds a anonymous function as a callback to the click
event. When the User clicks the button, it runs that code in the function.
The PHP Code might be something like:
<?php $user = $_POST['u']; $txt = $_POST['msg']; include_once 'db_conn.php'; $stmt = $mysqli->prepare("INSERT INTO 'chat' VALUES (?, ?)"); $stmt->bind_param("ss", $user, $txt); $stmt->execute(); $stmt->close(); ?>
As you can see, this is very rudimentary and will not answer your overall question. You must do a lot of research and I would advise you find example PHP/jQuery Chat example that you can learn from or begin taking some JavaScript/jQuery Tutorials.
See More:
- https://api.jquery.com/jQuery.post/
- https://api.jquery.com/click/
- https://api.jquery.com/category/selectors/
Update
If your PHP Code is setup to collect some data and “send” it back to an AJAX script, then you would prepare it like any other PHP Page, and output the data to the page in some fashion.
<?php $results = new array(); /* Assuming connection to DB */ /* Assuming SQL Query and result set is now in $results */ header('Content-Type: application/json'); echo json_encode($results); ?>
When you navigate to this page, you will see the collected data in JSON format. Something like:
[ { "sender": "jsmith", "message": "Hello World!", "time": "12/27/2019 10:28:01" }, { "sender": "ssmith", "message": "shut up john", "time": "12/27/2019 10:28:12" } ]
When AJAX sends a request to this script, it will get the data back and can then iterate each item in the array, create HTML for it as needed. You can use HTML or Text or XML too, I just use JSON when possible.
In jQuery, this function might look like:
function getMessages(){ var lastMessage = $(".chat-messages-item:last .chat-time").text().trim(); $.get("chatmessages.php", function(data){ $.each(data, function(i, msg){ if(lastMessage < msg.time){ var newMsg = $("<div>", { class: "chat-messages-item " + chattype(msg.sender), }).insertAfter($(".chat-messages-item:last")); var av = $("<div>", { class: "chat-avatar chat-avatar-lg circle" }).appendTo(newMsg); $("<img>", { src: senderpic(msg.sender, 100, 100), class: "thumbnail" }).appendTo(av); $("<div>", { class: "chat-messages-content" }).html("<p>" + msg.message + "</p>").appendTo(newMsg); } }); }); } setTimeout(getMessages, 10000);
This is just an example based on your code.