Reputation: 2740
I'm trying to create simple chat with ajax and PHP. From now i met a problem when i trying to show it in my HTML.
[
{"id_chat":1,"username":"admin","message":"ae","createddate":"2016-07-25"},
{"id_chat":2,"username":"admin","message":"aeaee","createddate":"2016-07-25"}
]
Here is my script
function buka_pesan()
{
var username = '<?=$this->input->cookie('cookie_webstore_user')?>';
$.ajax({
url: '<?=base_url();?>chat/show_chat',
success: function(data) {
$.each(data.data, function(k, v) {
$(".direct_add").append("<div class='direct-chat-msg right'> " +
"<div class='direct-chat-info clearfix'>" +
"<span class='direct-chat-name pull-left'>" + data.username + "</span>" +
"<span class='direct-chat-timestamp pull-right'>" + data.createddate + "</span>" +
"</div>" +
"<div class='direct-chat-text'> "+
data.message+
"</div>"+
"</div>");
});
}
});
}
$(window).load(function() {
buka_pesan();
var username = '<?=$this->input->cookie('cookie_webstore_user')?>';
$("#send_msg").click(function(){
if($("#pesannya").val() == '')
{
alert('Isi pesannya dulu kak');
}else
{
$.ajax({
url: '<?=base_url();?>chat/savechat',
data: {pesannya:$("#pesannya").val()},
type: 'POST',
dataType: 'JSON',
success: function(data) {
buka_pesan();
}
});
}
});
});
and here is my form
<div class="direct-chat-messages">
<div class="direct_add"> </div>
<div class="box-footer">
<form action="#" id="form_id" method="post">
<div class="col-sm-5"> <div class="input-group">
<input type="text" id="pesannya" name="pesan" class="form-control">
<span class="input-group-btn">
<button type="button" id="send_msg" onclick="buka_pesan();" class="btn btn-warning btn-flat">Send</button>
</span>
</div>
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
So, i want to show the recent chat. But no help. with my script above it's i only can see submit button. Any solution ?
Upvotes: 2
Views: 1024
Reputation: 32354
Change data
with v
$.each(data, function(k, v) {
$(".direct_add").append("<div class='direct-chat-msg right'> " +
"<div class='direct-chat-info clearfix'>" +
"<span class='direct-chat-name pull-left'>" + v.username + "</span>" +
"<span class='direct-chat-timestamp pull-right'>" + v.createddate + "</span>" +
"</div>" +
"<div class='direct-chat-text'> " +
v.message +
"</div>" +
"</div>");
});
Upvotes: 2