Managing error responses while fetching a blob through AJAX

Is it possible to execute an AJAX call that has the potential to return either a blob or a text string based on the server's response?

My current task involves using AJAX to transform a user-provided video into an audio blob that can be utilized within an <audio> tag. The conversion process is functioning properly, however, it is plausible that there could be issues with the video. In such scenarios, the server will respond with an HTTP status code of 500 along with an error message in plaintext format. In such situations, I require access to the plaintext response, but attempting to retrieve it using responseText triggers the following error message:

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

Below is a simplified version of my existing code:

function convertToAudio(file) {
    var form = new FormData();
    form.append("Video", file, file.name);

    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if(request.readyState == 4 && request.status == 200) {
            console.log(typeof request.response); // should be a blob
        } else if(request.readyState == 4 && request.responseText != "") {
            console.log(request.responseText);
        }
    };
    request.open("POST", "video_to_audio", true);
    request.responseType = "blob";
    request.send(form);
}

In other parts of my code, I am utilizing jQuery (therefore, jQuery solutions are acceptable). However, to the best of my knowledge, jQuery does not support blob handling.

Answer №1

Update the responseType during the second stage of readyState.

It is possible to modify the responseType value before the readyState hits 3. When the readyState is at 2, you can analyze the response headers to determine the appropriate course of action.

Revised code snippet:

function convertVideoToAudio(file) {
    var formData = new FormData();
    formData.append("Video", file, file.name);

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if(xhr.status === 200) {
                console.log(typeof xhr.response); // should return a blob
            } else if(xhr.responseText !== "") {
                console.log(xhr.responseText);
            }
        } else if(xhr.readyState === 2) {
            if(xhr.status === 200) {
                xhr.responseType = "blob";
            } else {
                xhr.responseType = "text";
            }
        }
    };
    xhr.open("POST", "convert_video_to_audio", true);
    xhr.send(formData);
}

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

What could be causing my JavaScript loop to replace existing entries in my object?

Recently, I encountered an issue with an object being used in nodejs. Here is a snippet of the code: for(var i = 0; i < x.length; i++) { var sUser = x[i]; mUsers[sUser.userid] = CreateUser(sUser); ++mUsers.length; ...

Struggling to vertically align elements within iron-pages

Struggling to vertically center the content within iron-pages (nested in a paper-drawer-panel). Check out the code snippet below: <paper-drawer-panel id="drawerPanel" responsive-width="1280px"> <div class="nav" drawer> <!-- Nav Conte ...

Show the chosen value from the dropdown menu on all JSP pages

I have a header.jsp file containing a dropdown box labeled "Role". This header.jsp is designed to be included in all other JSP files using a directive. Once a user logs in, they are directed to a homepage where they must select a value from the dropdown ...

Is it possible to change XML using Ajax technology?

Is it possible to update a value in an XML file using JavaScript/Ajax? I've managed to access the XML file with Ajax and utilize its values in my script. Now, I want to send any updates made by the script back to the XML file on the server using Ajax ...

Implementing a separate detail view in Vuejs

I am currently working on a page with multiple cases. When I click on a case, the details for that case appear on the same page. Here is a screenshot of how it looks: https://i.sstatic.net/Y9S4J.png As you can see in the screenshot, there are two cases li ...

What are the best techniques for streamlining nested objects with Zod.js?

As a newcomer to zod.js, I have found that the DataSchema function is extremely helpful in verifying API data types and simplifying the API response easily. However, I'm curious if there is a way to streamline the data transformation process for myEx ...

Nested views within nested views in UI Router

Exploring the capabilities of angular-ui and specifically experimenting with the ui-router module to create nested views. I'm running into an issue where a partial isn't rendering within another partial: The structure of nesting looks like this: ...

Tips on obtaining checkbox value in an AJAX request

I need to retrieve the value of a checkbox using Ajax in order to store it as a user preference in the database. This task is new to me, and I'm feeling a bit overwhelmed. Here is my JavaScript file: $(document).ready(function() { E.accounts.chang ...

Can you explain the distinction between using $.ajax and $.post in jQuery?

Within my project, there are both calls made using $.ajax as well as some utilizing $.post. I am under the impression that these two types of calls are essentially identical! Can anyone confirm if this understanding is accurate? ...

Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to pla ...

I have been struggling to get AJAX to work properly with Load and selector, but no matter what I try, the scripts just won

Yesterday, with the assistance provided here, I discovered how to load AJAX'ed content and maintain the page structure. However, I encountered an issue where the script tags were not loading. Upon further investigation, it appears that when using a se ...

Creating a fantastic Image Gallery in JavaScript

As I work on creating a basic gallery page with html and css, everything seemed to be running smoothly. However, upon testing it in Google Chrome and IE, the onmouseover function is not responding as expected. The idea is for a larger image to display in t ...

What is the best way to display nested JSON in JSX within a React Native application?

I need help with rendering nested JSON inside my JSX. Below is the JSON response: [{ "data": { "total_students": 13, "seats": "", "categories": [{ "id": 28, "name": "Economy", "slug": "econom ...

Is there a way to alter the variant or background of a clicked button exclusively through reactjs? If so, how can I make it happen?

My goal is to change the variant of a Material UI button from outlined to contained or simply change its background color when it is clicked. I am unable to use the onFocus property due to conflicts with another component. Here is my current method, but ...

Creating a draggable element in JavaScript using React

I've been attempting to create a draggable div element, but I'm encountering some perplexing behavior. The code I'm using is directly from w3schools and it functions correctly for them, however, in my implementation, the div always shifts to ...

How to create a donut chart in Highcharts without an inner pie section?

I've been scouring the internet in search of a solution to create a basic donut chart using the Highcharts library. Most examples I come across show donut charts with both an inner pie and outer donut (see here). Is there a way to remove the inner pi ...

Passing data from React component to JavaScript page or function

I am trying to pass a variable called "pokemon" from Cell.js to Detail.js. Cell.js creates buttons, each representing a different pokemon. When clicked, it should navigate to a detailed page about the specific pokemon. Therefore, I need to send the pokemo ...

Threejs file exporter from Blender generating corrupted files

My Blender model seems to be causing issues: After using the threejs exporter in Blender 2.7, the exported json file contains numerous null or 0 values: { "metadata": { "formatVersion" : 3.1, "generatedBy" : "Blender 2.7 Exporter", ...

Getting just the outer edges of intricate BufferGeometry in Three.js

Currently, I am immersed in a project that involves zone creation and collision detection using Three.js. The primary objective is for my application to effectively manage collisions and produce a BufferGeometry as the final output. My aim is to visually r ...

"Dilemma: Why won't the AJAX form post load inside the

Apologies for the simple question, but I'm experiencing an issue where nothing happens when the button is pressed. Any assistance would be greatly appreciated. AJAX $(document).on("ready", function(){ //Form action $("#wbForm").on("submit", function( ...