I have a situation where I am utilizing AJAX to send mouse movement data to a Django view every 10 seconds for saving in the server. The issue arises when I receive a 500 error message whenever the data sending function is executed. Upon attempting to use fetch, I encountered the following error:
POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
My research suggests that this problem might be related to data type compatibility, but I am uncertain about how to identify and rectify it. Any assistance with troubleshooting this problem would be greatly appreciated.
Below is the JavaScript function being used:
var target_id = '';
var eventsLog = {"mouse": []};
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds();
var insert = [start_time, target_id];
(eventsLog.mouse).push(insert);
}
var timesPerSecond = 5;
var wait = false;
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
const post_url = server_url;
function sendMovement() {
/* fetch(post_url, {
method: 'POST',
body: JSON.stringify(eventsLog),
credentials: 'include',
headers: {'Content-Type': 'application/json'}
}).then(res => res.json()).then(response => {
console.log('POST response:', response);
}).catch(error => {
console.log('POST error:', error);
}); */
$.ajax({
type: "POST",
url: server_url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(eventsLog),
dataType: "json",
success: function () {
},
error: function (req, textStatus, errorThrown){
console.log('Oops, something happened: ' + textStatus + ' ' +errorThrown)
}
});
Here is the corresponding code in my Django view:
movement = json.loads(request.body.decode('utf-8'))
Upon checking the received data type in Django, I confirmed that it is indeed a dictionary.