I'm creating a social network type deal and I want to add a chat feature.
Currently I have a home.php that has a friends list on it, the friends list is loaded via jQuery and PHP like so:
function LoadList() {
$.get("friends_feed.php",
function (data) {
$('div#friendsfeed').html(data);
}
);
}
For each friend that gets loaded into the list, I want to make it where when you click their name it creates a div that is fixed at the bottom of the screen, this div will be a chat box. I am hoping to be able to simply just load it in via PHP and Ajax. How to approach this?
EDIT: I only want the chat to be between the two people. The user and their friend.
Creating a chat system as you want isn't too hard but you do have to know what your doing. You will first need a file that will initially load the chat when you click a user.
function loadChat (userid) {
$.get("/ajax/getChat.php", {
userid: userid
}, function (data) {
//add the chat
});
}
Then you will need to be able to ping the chats so that you can receive new messages. I suggest using either web sockets or the easier approach, server-sent events. I don't suggest polling.
Server-sent events could look like:
var pinger = new EventSource("/ajax/pingMessages/" + userid);
pinger.onmessage = function (data) {
data = data.data;
// append messages
};
While SSE's have less support than just polling using AJAX, they work better and allow you to keep an open connection with the server which in the end saves resource. There are a few poly fills for SSE's out there that you can check out.
You will also need a send function.
function send (userid) {
$.post("/ajax/send.php", {
userid: userid,
message: $.trim($('.chat[data-id*="'+ userid +'"] input[type="text"]').val())
});
}
NOTE All of these request only take in the userid
. In the server-side you can take in consideration the current users id.
You should setup 1 table for the messages. Give the conversation an unique id
and go from there. You will need to do a lot more in the server end than in the actual JavaScript.
I've created a chat before using server-sent events and AJAX. Most of the logic was in the server side.
I'm not sure if this helped but I think this might give you a little idea.