Error: SyntaxError encountered - JSON input unexpectedly ended

Below is a script that handles AJAX requests:

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (JSON.parse(ajax.responseText).result == 'error') {
        console.log('error')
        $.each(JSON.parse(ajax.responseText).response, function(key, value) {
            console.log(key)
            $('.contact_form_' + key).css('display', 'block')
            $('.contact_form_' + key).prev().css("border", '1px solid #FD7900')
            $('.contact_form_' + key).text(value)
        })
    } else {
        location.reload();
    }
}

This script is designed for handling an AJAX request to the server. The expected response from the server is JSON data, which can sometimes be empty.

An error message may occur:

Uncaught SyntaxError: Unexpected end of JSON input

The error is usually associated with this line of code -

if (JSON.parse (ajax.responseText) .result == 'error') {

Here are some examples of the JSON responses that could be received:

if contact_form.is_valid():
    contact_form = contact_form.save()
    return JsonResponse({})
else:
    response = {}
    for k in contact_form.errors:
        response[k] = contact_form.errors[k][0]
    return JsonResponse({"response": response, 'result': 'error'})

Here is a log screenshot for reference:

https://i.sstatic.net/h2Hbs.png

Answer №1

Your issue lies in the fact that you are triggering your function on every state change of the XMLHttpRequest request, when not all state changes indicate a completed response has been received.

For reference, here is a list of the different state changes for an XMLHttpRequest object. Only the DONE state is relevant for parsing the response accurately.

During other states, your function will attempt to parse an empty responseText or may already have parsed a responseText at an earlier stage.

According to the documentation, it is recommended to listen for the 'load' event when working with XMLHttpRequest objects.

Answer №2

I made a modification

res.status(204).json({ user });

To this instead

res.status(200).json({ user });

Surprisingly, it worked perfectly!

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

Sending an Ajax POST request to a PHP file from a Node.js Express server, using an Nginx reverse proxy on

Recently, I embarked on the journey of setting up a nodejs web server using express and configuring a reverse proxy through nginx on my raspberry pi. As a newbie to web servers and routing, I am diligently navigating through this process. Firstly, I instal ...

Switching back and forth between different rows within a table

Currently, I am just starting out with AngularJS (1.5) and I have come across a challenge that I am hoping to get some assistance with. I have a table that is generated dynamically and for each row, I need to add a down arrow in the first column. Based on ...

Implementing local date JSON binding using the Yasson implementation on a WildFly server allows for seamless

When I use the LocalDate type in my entity class, I encounter an error when sending a POST request: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exi ...

Steps for sending a form with jQuery's submit method1. Start

Below is the jquery code that I have written: $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(e ...

Utilizing $routeParams to dynamically generate the templateUrl with AngularJS

Our platform offers a 2-level navigation system. We are looking to utilize AngularJS $routeProvider to dynamically load templates into an <ng-view />. Here is the approach I am considering: angular.module('myApp', []). config(['$route ...

Storing form data in a JSON file using JSP-Servlet technology

I successfully created a registration form in jsp and utilized a servlet to retrieve the values inputted by users. Within the servlet, I implemented code to generate a file and attempted to save the data in json format within that file. Despite my effort ...

Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way. My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code sn ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

The alignment of inline divs is off and they are not forming a straight row

From my understanding, adding display:inline to divs with a relative position should align them (left to right) similar to float:left. I attempted both methods but with no success. Below is an example of my latest try with inline displaying. My goal is to ...

Options for Ajax in jQuery UI combobox are customizable

I am looking to personalize the dropdown options of the combobox widget created using jQuery UI Autocomplete. The current options are either predetermined from the SELECT tag OPTIONS or sourced from a JSON array. //getter var source = $( ".selector" ).aut ...

A guide to displaying JSON information within a data list element (dl)

I am facing an issue while trying to iterate through a multidimensional json data array. Each time I loop through the array, only the last element gets printed. var data = [ [{ "id": "67", "name": "Baby & Toddler Clothing ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Printing a webpage through an FGL printer (Boca System) step-by-step guide

I am currently developing a ticketing system website that requires admins to print tickets using a Boca printer. The issue I am facing is that the Boca printer utilizes FGL (Friendly Ghost Language) as a standard for ticket printing. Is there a "secret" m ...

Instruct npm to remove dependencies that are no longer necessary

After adding a few libraries to my package.json file, I realized that they are no longer needed. Is there a command line parameter for npm install that can be used to remove unnecessary packages from node_modules directory that are not in package.json anym ...

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...

When accessing ASP.NET Web API at localhost:xxxx/api/product, the default page is displayed instead of returning JSON or XML data

I'm currently attempting to retrieve data from my SQLEXPRESS database via API for my UWP client app. Below is the code I have implemented: API controller: [Route("api/product")] public class ProductController : ApiController { // GET: api/prod ...

SailingSmooth and JSONP Integration

I am currently working on a project that aims to establish a connection with Hudson CI server and other Hudson-compatible CI servers. While I initially thought that CruiseControl offers a JSONP API similar to Hudson's, I have been unable to find any d ...

Exploring Vue.prototype attributes and utilizing them

I'm facing a challenge while attempting to globally set a property using Vue.prototype. This is what I currently have: microsoftTeams.initialize(); microsoftTeams.getContext((context) => { Vue.prototype.$teamsContext = true; }); new Vue({ ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...

How to dynamically insert li elements into a ul list using the .after() method

After trying to add an li element to the ul list, I noticed that my DOM wasn't updating when checking the page source. Even attempting to delete elements with the delete button didn't seem to work as expected. Here is the code snippet below. ...