Reputation: 9393
I want to create a chat box and I have found some snippets on internet but they look too big to understand. I have got a basic way to approach it after reading all those stuff:
I am a beginner in AJAX and in webdesigning, to be honest I just know to get data and post data using AJAX but my question is: how do I update chat box when some user posts something?
I know how to post the message when user clicks send button but how to update it to the other user without clicking any button?
Is there a way to detect a event like post_event
that user posted data into database so that we can do some action whenever user posts something?
We have many events in JavaScript as far we know, please help me with these.
I have been using AJAX more, is it a good practice or bad one? One of my friend said running a chatbox application in a website costs more than the normal website is it true? If a website has a chat app does it cost more, even though its traffic is less?
Upvotes: 3
Views: 879
Reputation: 1936
Most easier way:
To update your chat window you have to pass request to the server (with Ajax), and post received data to some textarea (with id "TextAreaId" for example):
<script type="text/javascript">
function updateChat() {
$.ajax({
url: "your_url",
type: "POST",
success: function (data) {
$("#TextAreaId").value = data;
}
});
}
</script>
Server side should return some amount of messages (last 20 for example).
To update your chat window with some period you can use:
<body onload="setInterval('updateChat()', 1000)">
To post some message it ajax to:
<script type="text/javascript">
function postMessage() {
$.ajax({
url: "your_url",
type: "POST",
data: "message = " + Message + "&user = " + User, // pass message and user name
success: function (data) {
updateChat();
}
});
}
</script>
And process your ajax requests on server side with PHP or ASP.
I think is better to use some text file rather than database. It reduces server loading.
There you can find a mechanizm that can help you to get reponse from server Ajax.Request
Here you can find chat example.
Here most easier example that I find.
Upvotes: 2
Reputation: 1082
You need a timer
this.ajaxError(function (event, request, settings) {
//code to set timer
});
Then you need a jquery function to retrieve all the messages since the last update
getMessages = function () {
clearTimer();
var postData = getPostData();
postData.ChatMessage = '';
$.post(url, postData, applyData, settings.dataType);
}
Where PostData is variables for lastupdated, chatroom id, etc.
Upvotes: 1