Matteo Guglielmetti Matteo Guglielmetti - 7 months ago 25
PHP Question

Ajax POST request, parseerror

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 . "\n");
break;
case 'getMsg':
$log = array();

if(file_exists('chat.txt')) {
$usr_count = $_POST['line_count'];
$srv_msg = explode("\n", 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

Answer

parseerror just means that you're not getting JSON back from the server. It could be PHP throwing an error and printing the error markup before the json.

check the console to see what is actually being returned from the server.

you may alos want to check is_writable() before attempting to write to a file. it could be a simple permissions issue.