I am creating a Chat application in php.
AIM: when a user1 invites user2, user2 want to get a alert or popup message that user1 has invites him.
What i have done is -
When user1 invites, the message is stored in database. In user side i u开发者_JS百科sed to check whether Database is updated or not. If database is update i used to show alert. This i done on php and javascript but not working all time.
Is this a good method? Any other method?
Use Ajax to send request to Server periodically. Response will contain any invites that user has. Response maybe in JSON which can be easily evaluated in JavaScript.
All the clients can use jquery and send following request periodically:
function checkIfIAmInvited()
{
jQuery.ajax({
type: "POST",
url: "some.php",
data: "name=currentUser&",
success: function(msg){
if(msg.indexOf('uninvited') !== -1 )
{
alert( "You have been invited by " + msg );
//Method to do stuff once I am invited
iAmInvitedMethod();
}
});
}
To call above code periodically you can use following code in jquery/javascript. This would be making periodic calls and getting the response back to you. As soon as the response come without containing "uninvited" string it gives an alert and also calls the post method function.
This can be repeatedly called with following code.
window.setInterval("checkIfIAmInvited()", 5000);
This will check every 5 seconds if there are any invitations. Alternatively for a more better control jquery plugins like Timer can be used to execute something repeatedly.
Using (at least) two database trips is a poor way to handle a real time chat. If you were doing some stored chat aka msging system it's fine. But considering you only need to hold on to the text for a second or two, I would either use SQL-Lite or another in memory solution only. It would be much faster and easier on your server.
For chat and instant messaging systems, you should investigate the use of a Push-based technology such as Comet. More info in this thread: an implementation with jquery.
精彩评论