Attempting to send a JSON object to the Django framework results in a 500 error code

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.

Answer №1

Obtain csrf token from cookies and include it in the request header. Utilize setInterval() function to send the request every ten seconds. While you can also use Fetch API, I incorporated jQuery for sending an AJAX as you were already using it in your movement function.

get_mouse_movement.html (just the script part)

<script>
    var target_id = '';
    var eventsLog = {"mouse": []};
    var timesPerSecond = 5; 
    var wait = false;

    function getCookie(name) {
        ...
    }

    function logMouse(event){
        target_id = event.target.id;
        currDate = new Date()
        start_time = currDate.getHours() + ':'
            + currDate.getMinutes() + ':' 
            + currDate.getSeconds() + ':' 
            + currDate.getMilliseconds();

        console.log([start_time, target_id])
        eventsLog.mouse.push([start_time, target_id]);
    };

    $(document).on('mousemove', function (event) {
        if (!wait) {   
            logMouse(event);
            wait = true;
            setTimeout(function () {
                wait = false;
            }, 1000 / timesPerSecond);
        }
    });

    function sendLog() {
        $.ajax({
            type: "POST",
            url: '/your/url/',
            headers: {'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'application/json'},
            data: JSON.stringify(eventsLog),
            success: function(data) {
                console.log(data.message);
                eventsLog.mouse = [];
            },
        });
    };

    setInterval(function(){
        sendLog();
    }, 10000);
</script>

views.py

import json
from django.http import JsonResponse

def mouse_movement(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print(data)
        return JsonResponse({'message': 'log is saved'})
    return render(request, 'get_mouse_movement.html')

.loads() accepts, str, bytes or bytearray. There's no need to decode it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effective ways to retrieve API response data in React JS

I am working on a Spring Boot project which includes an API for user login. When the user name and password are sent through this API, it checks the database for the information. If the data is found, it returns a successful login message; otherwise, it ...

Encountering error #426 in NextJs when the app is loaded for the first time in a new browser, but only in a

Encountering a strange error exclusively in production, particularly when loading the site for the first time on a new browser or after clearing all caches. The website is built using nextjs 13.2.3 and hosted on Vercel. Refer to the screenshot below: http ...

Step-By-Step Guide on Creating a Data Post Using HttpUrlConnection

Here is an AJAX code snippet I have: $.ajax({ url: 'http://www.whoisxmlapi.com/whoisserver/WhoisService', dataType: 'jsonp', type:'POST', data: { domainName: 'domaindomanin.com', outp ...

Explore the power of using Math.pow in JavaScript with UIWebView in iOS

Seeking guidance on how to evaluate a JavaScript string within iOS using the code snippet: [self.webView stringByEvaluatingJavaScriptFromString:formula] The current code in question: NSString *formula = @"( 1.5 * Math.pow(2, 3) ) / 12"; formula = [NSStr ...

Automate table column width adjustments in HTML using Selenium WebDriver

As of now, I am working on automating the process of increasing the width of an HTML table column using Selenium WebDriver. I discovered that I can retrieve the coordinates of x and y by using findElement(By.cssSelector("<Css locator>").getLocation( ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

Is there a way to execute a PHP script using Ajax without needing any return values?

Currently, I am attempting to execute a php script with ajax without needing any output or echos. Is there a method to achieve this? Below is the approach I have taken: $('button')[1].click(function () { $.ajax({ met ...

Experiencing difficulty receiving a full response from an ajax-php request displayed in a div

Having trouble getting a response in a div from an ajax request triggered by an onclick event in a form and a PHP page. Here's the code: <html> <head> <script language="javascript"> function commentRequest(counter) { new Ajax. ...

Best practice for structuring a JSON payload and sending it to a server using Volley

Currently, I am working on implementing the Safe Browsing API by Google to verify if a web link is blacklisted. To achieve this, I need to send a request within a JSON object to the following endpoint: POST https://safebrowsing.googleapis.com/v4/threatMat ...

Creating unique page styles using global styles in Next.js

I am facing a dilemma in my NextJS app. On the /home page, I need to hide the x and y overflow, while on the /books page, I want the user to be able to scroll freely. The issue is that Next only allows for one global stylesheet and using global CSS selec ...

Focusing solely on the data table by performing a lookup using the keyword "list"

Looking to extract specific ranking numbers from certain districts listed in the json data. I'm having trouble with the syntax, can anyone provide assistance? Here is a snippet of the code: staedte_id= list("02000", "09162", "05315", "06412", "08111", ...

The signup controller encountered a malfunction with illegal arguments: an undefined value and a string

I recently started learning MERN through a tutorial and encountered an issue with my database. I have successfully created a function to send data to the database, but for some reason, I can't see the data in the database. Below is the code snippet: ...

Utilize the Link_to function within a Rails jQuery script

Trying to incorporate link_to (<%= link_to 'address' , boat_path("'+boat_id+'") %>) within my jQuery code has presented a challenge due to concatenation issues preventing it from functioning as intended. Below is the jQuery code ...

What is the process of linking MongoDB with a server?

My attempt to retrieve data from mongoDB while connecting to the server has led me to insert a value into mongoDB in the following manner: > use abc switched to db abc > db.ac.insert({name:"naveen"}) WriteResult({ "nInserted" : 1 }) > show coll ...

Ordering MySQL based on `field`, parameters 1, 2, 3 from a JSON array

I'm trying to create a MySQL query: select * from `table` order by field(`column`, "param1", "param2", "param3") The parameters param1, param2, param3 are coming from a JSON array ["param1", "param2", "param3"]. When I hardcode these parameters in t ...

Creating a vibrant and mesmerizing inward spiraling rainbow of colors on canvas using JavaScript

After coming across an image that caught my eye, I was inspired to recreate it using canvas: https://i.stack.imgur.com/fqk3m.png I've attempted drawing arcs starting from the center of the screen, but I'm struggling with getting their paths acc ...

numerous sections within a solitary webpage

I need to implement multiple tabs on a single page, how do I modify the code to make this possible? Take a look at the codepen for reference. Here is the jquery code I have written so far: var tabs = $(".tabContainer ul li a"); $(".tabConten ...

What steps should I take in order to ensure that NPM commands run smoothly within Eclipse?

I have a functional workflow that I'm looking to enhance. Currently, I am developing a JavaScript library and conducting smoke tests on the code by using webpack to bundle the library and save it to a file that can be included in an HTML file for test ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

Script in Powershell for converting multiple .csv files to .html format and managing the conversion process

I need to create a script that can merge the content of various .csv files and output them into a single .html file. The objective is to display all filenames as clickable buttons which, when expanded, will show the corresponding content. However, I am fa ...