Reputation: 742
i'm doing a simple php chat application that sends the message input to the server via ajax and saves it in a text file. Now after it retrieves all data in the text file and sends it to the client in an array form via ajax. Now what i want to do is populate a div called "chat-box" with the contents of the array as html but nothing happens and ii don't get any errors in firebug apart from ": undefined".
This is the code:
<script type="text/javascript">
// setInterval(function(){alert("Hello");}, 5000);
$(document).ready(function() {
function getchat(messages)
{
var chat = $(".chat-box").html();
for (var i=0; i < messages.length; i++)
{
var msg = messages[i].split(':');
var name = msg[0];
var post = msg[1];
$(".chat-box").html(chat + "<div class='bubble'>" + name + " : " + post + "</div>");
}
}
$("#btnPost").click(function() {
var msg = $("#chat-input").val();
if (msg.length == 0)
{
alert ("Enter a message first!");
return;
}
var name = $("#name-input").val();
var chat = $(".chat-box").html();
//$(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");
var data = {
Name : name,
Message : msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(chat) {
getchat(chat)
}
});
});
});
</script>
Upvotes: 0
Views: 221
Reputation: 5930
Try this instead for updating the chat box:
var index = messages[i].indexOf(':');
var name = messages[i].substring(0, index);
var content = messages[i].substring(index + 1);
var $newMessage = $('<div>')
.addClass('bubble')
.text(name + " : " + content);
$(".chat-box").append($newMessage);
If this doesn't work, check if the messages returned by the server are correct by using console.log(messages)
.
Upvotes: 1
Reputation: 37506
You said the div is called chat-box. Perhaps it's this:
$(".chat-box")
maybe you intended to write it as $("#chat-box")
Upvotes: 0