I'm trying to make a web chat room, but when I send a post request to the server, with this code:
var line_count = 0;
$.ajax({
type: 'POST',
url: '../scripts/engine.php',
data: {'method': 'getMsg', 'line_count': line_count},
dataType: 'json',
error: function(request, error) {
alert('Error: '+error);
},
success: function(data) {
$.each(data.messages, function(i, val) {
$('.messages').append(val);
});
line_count = data.srv_count;
}
});
And:
<?php
$method = $_POST['method'];
switch($method) {
case 'postMsg':
$sender = $_SESSION['username'];
$message = $_POST['message'];
$time = $_POST['time'];
fwrite(fopen('chat.txt', 'a'), '<div class="time">[' . $time . ']</div><div class="nickname">' . $sender . '</div>' . $message . "
");
break;
case 'getMsg':
$log = array();
if(file_exists('chat.txt')) {
$usr_count = $_POST['line_count'];
$srv_msg = explode("
", file('chat.txt'));
$srv_count = count($srv_msg);
$log['srv_count'] = $srv_count;
if($usr_count < $srv_count) {
$i = 0;
while(list($key, $val) = each($srv_msg)) {
if ($i > $usr_count) {
$log['messages'][i] = $val;
}
$i = $i+1;
}
}
} else {
$log = false;
}
echo json_encode($log);
break;
}
?>
Then I get this error message from ajax error function: "Error: parseerror". I checked the code many times, but I don't see where's the issue. Thanks in advance
Thanks everybody for the fast answers
I checked returned value from the server, and I undertood it was a server-side problem. returnded value:
Warning: explode() expects parameter 2 to be string, array given in X:\wwwoot\scripts\engine.php on line 17
{"srv_count":0}
I just edited my code into:
$usr_count = $_POST['line_count'];
$srv_msg = explode("
", file_get_contents('chat.txt'));
$srv_count = count($srv_msg);
$log['srv_count'] = $srv_count;
if($usr_count < $srv_count) {
$i = 0;
while(list($key, $val) = each($srv_msg)) {
if ($i > $usr_count) {
$log['messages'][$i] = $val;
}
$i = $i+1;
}
}
And now It's working fine.