Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly.

However, if there's an error on the webpage, instead of returning a JSON string with an error message embedded in it, it actually returns an error string that JavaScript does not recognize as valid JSON. As a result, when checking for response, it comes back as null. In this scenario, I want to view the response string and identify what the error message entails.

var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("POST", "/someEndpoint");
xhr.send();
xhr.onload = function() {
    console.log(xhr.response);
}

(Here's a fiddle where you can reproduce the issue.)

If /someEndpoint returns legitimate JSON, xhr.response displays a JavaScript object. However, if it doesn't return valid JSON (such as when the endpoint responds with an error message), then I receive an empty object within xhr.response. Unfortunately, I encounter difficulties accessing the invalid-JSON error response because trying to access xhr.responseText triggers the following error:

Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json')

The challenge lies in reading the original HTTP response after conducting the request with responseType="json"; since responseText remains inaccessible due to how it was set up.

Answer №1

It's clear that the current code will not function correctly based on the error message provided:

Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json').

This issue can be confirmed through the following example:

var xhr = new XMLHttpRequest();
//xhr.responseType = "json";

xhr.open("POST", "/echo/json/");
xhr.send("hello world");

xhr.onload = function() {
    console.log(xhr.response);
    console.log(xhr.responseText);
}

If you set the responseType to JSON, the object will not have a responseText property. It's advisable to omit setting the responseType and treat the response as a text string when parsing it (parseJSON). Failing to do so may cause issues with JSON parsing. This aligns with how jQuery handles Ajax requests, which leads us to the next point...

Why struggle with handling the native XMLHttpRequest browser object when jQuery offers a more seamless solution for Ajax functionality? jQuery has established consistent practices over the years for handling AJAX requests in a cross-browser manner with an API that includes callback functions like 'always', making it a suitable choice for your requirements.

To sum up, consider using jQuery to simplify your coding process and avoid unnecessary complications.

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

Transmitting information securely and remotely between two online platforms

I own two websites and another at When a user clicks on something on example1.com, I want it to trigger a popup from example2.com. Then, I need to send some data back to example1.com using GET parameters and be able to detect it using jQuery or JavaScrip ...

Stable and persistent popup window that remains at the forefront in a Chrome extension

Currently developing a Google Chrome extension and seeking assistance in creating a popup window that remains fixed in one corner while staying on top of all other windows. Here is a reference image for clarification: https://i.stack.imgur.com/IPw7N.jpg ...

Switching the mouse cursor when the mousedown event occurs

I'm trying to implement a feature where holding down the mouse will change the cursor to an image, and when releasing the mouse it should revert back to its default. However, the code I have isn't working properly - you have to right click then l ...

I am having trouble displaying images with Material UI CardMedia

I'm currently using CardMedia to display images on my webpage, but unfortunately, the image is not appearing as expected. After researching a similar issue on Stack Overflow, I discovered that the suggested solution involved importing the image and t ...

What process is involved in implementing TCO (Tail Call Optimization) for a recursive anonymous function in ES5?

Is there a way to optimize an anonymous recursive function for tail call optimization, similar to how a named recursive function can be optimized? If such a method exists, please provide explanations on how to achieve it. Below is an example of a recursi ...

Use Jquery to retrieve the innerhtml content

Hey there! I'm currently in the process of learning Jquery and have encountered an issue with accessing form elements. My script is designed to open a div and then fill it with a predefined HTML form. To achieve this, I'm using ajax to fetch the ...

Using jQuery, retrieve the "select" element within a specific row of a

I am working on a table row that has the following HTML structure: When the user interacts with the "Name" field, I trigger the "select" event and pass it to the nameDropChanged function. Once I have a reference to this select element, I need to change th ...

Error: Cannot access property 'tb' of an undefined value

While running the Application, I encountered an error in the declaration of constants.ts file where I was assigning data from a json file to constant variables. In the json file named object.json, I had some data structured like this: { "furniture": { ...

Is there a way to convert a button into clickable text that performs the same function as the original button?

Seeking a solution to transform a button into clickable text with the same functionality. Explored resources like Google, StackOverFlow, and Youtube for answers. This is the current code snippet representing the button: <button onclick="mainApp.l ...

What is the best way to make an HTML table with a static header and a scrollable body?

Is there a way to keep the table header fixed while allowing the table body to scroll in an HTML table? Any advice on how to achieve this would be greatly appreciated. Thanks in advance! ...

Getting a string array from a JSON object within the deserialize method

I am working with a JSON object that looks like this: { "name": "John", "age": 29, "bestFriends": [ "Stan", "Nick", "Alex" ] } In my code, I have created a custom implementation of JsonDeserializer: public class CustomDeserializer im ...

Issues encountered with AngularJs filter search functionality

Why am I having trouble adapting this search filter from here? This is what my code looks like: controllers.js angular.module('starter.controllers', ['starter.services']) .controller('AppCtrl', function($scope, $ionicModal ...

Ways to identify the active anchor within an li element

Below is the code snippet I am currently working with: <li> <a href="<?php echo base_url()?>home/promos/call" class="promo-call active-call"></a> </li> <li> <a href="<?php echo base_url()?>home/promos/text ...

JavaScript is throwing an error stating that the requestData is undefined, even though the

Hello, I am attempting to retrieve weather information based on the country and city using the openweather api. JSON is a new concept for me in coding, so please bear with me through this learning process. Below is the code snippet that I have been workin ...

Switch out the name of multiple elements with mootools

Is there a Moo tool that can replace multiple element IDs? I currently have the following code: $$('myelement').each(function(el){ var get_all_labels = el.getElements('label'); var get_label_id = get_all_l ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

Turning spring form data into a JSON object via automation (with a mix of Spring, jQuery, AJAX, and JSON)

Recently, I've set up a spring form that utilizes ajax for submission. Here's an overview of my form... <form:form action="addToCart" method="POST" modelAttribute="cartProduct"> <form:input type="hidden" ...

Determine if the user has clicked on the Save or Cancel button within the print dialog box

Hello everyone, Can anyone help me figure out how to determine which button was selected by the user in a print dialog box? Thank you! ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...

Is there a program available that can efficiently convert or translate JSON objects into TypeScript types or interfaces?

Can anyone recommend a tool that can easily convert a JSON object into a TypeScript type or interface? An example input would be something like this: I'm hoping to paste the JSON object into the tool and receive an output structure similar to: expor ...