guarantee feature functions perfectly on Chrome and Firefox, yet encounters compatibility issues on IE Edge and IE11

I've created a function that seems to work well in Chrome and Firefox, but it's not functioning properly in IE Edge or IE 11:

async function getJSONDataWithHeaders(url, methodType, responseType) {
            return new Promise(async function (resolve, reject) {
                var xhr = new XMLHttpRequest();
                xhr.open(methodType, url, true);
                xhr.responseType = responseType;
                setHeaders(xhr);
                xhr.onload = await function () {
                    if (xhr.status == 200) {
                        resolve(this.response);
                    }
                }
                xhr.send();
            }).catch(function (err) {
                console.log(err);
            });
        }

This is how I am calling the function:

getJSONDataWithHeaders("https://jsonplaceholder.typicode.com/posts", "GET", "json").then(function (result) {
 console.log(result);
});

Answer №1

To include the `onload` as a parameter, you can do the following:

function fetchData(url, methodType, responseType, onloadFunction) {
    const xhr = new XMLHttpRequest()
    xhr.open(methodType, url, true);
    xhr.responseType = responseType;
    xhr.onload = onloadFunction
    xhr.send();
}

You can then use it like this:

fetchData('https://jsonplaceholder.typicode.com/posts', 'GET', 'json', function (progressEvent) {
    console.log(progressEvent.currentTarget.response)
})

Instead of a return value, a callback is utilized here. As mentioned by `sp00m`, the use of `async/await` is not compatible with IE. To address this, you may consider using this babel plugin. It employs a generator function to emulate `async/await`.

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

To customize or not to customize?

Lately, there has been a growing trend of people incorporating custom attributes into their HTML tags to add extra data for use in JavaScript code. I'm curious to hear thoughts on the practice of using custom attributes and what alternatives are avai ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

Animating components in React: A step-by-step guide to smoothly transition between rendered components

I am implementing a feature where a component changes at regular time intervals. Is there a way to incorporate an animation each time this change occurs? What would be the most effective approach? constructor (props) { super(props) this.state = { ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Trouble with clicking buttons in Java and Selenium web scraping

Hey everyone, Currently, I'm working on a Java Selenium script that automates clicking and filling forms for me. I've written a line of code that's causing me some trouble. The intention is to click on a button, but it's not happening ...

How can I convert a string into an array?

Is there a simple way to convert the following string into an array? "[[0.01,4.99,0.01],[5,14.95,0.05]]" I'm aiming for a result like this: var x = [[0.01,4.99,0.01],[5,14.95,0.05]]; ...

transform the stationary drawing to the top and left position at coordinate (0,0)

Exploring canvas has led me to encounter a puzzling issue with the translate method. While working on this fiddle http://jsfiddle.net/claireC/ZJdus/4/, my goal was to have the drawing move and bounce off all four walls. However, I noticed that it would no ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

Guide for utilizing a table value as a parameter in a mySQL query with PHP

My website features an HTML table that is filled with data pulled from a mySQL table using PHP. Each row in the table is clickable, and when clicked, it opens a modal that contains a form to update and submit data back to the database using a mysql update ...

*ngIf doesn't seem to be functioning as expected compared to other *ngIf directives

Encountering a peculiar issue with my *ngIf related to the isAdmin variable which determines whether the list of users in userList should be displayed or not. Strangely, it seems to behave differently compared to other *ngIf statements within the same comp ...

Using Javascript to construct objects using multiple iterations

I am seeking clarification on how to handle mock data that includes multiple reviews for each product. The review_id is incremented based on the primary key, while the product_id may have duplicate values due to multiple reviews being associated with the ...

Comparing Buffer and Uint8Array in Node.js

Exploring the documentation for the fs module 1, we come across the following regarding the writeFile method: const data = new Uint8Array(Buffer.from('Hello Node.js')); Further in the documentation 2, it states: With TypedArray now available, ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

Carousel Owl 2: The Perplexing Challenge of Caption Animation

I'm encountering difficulties with animating my captions in owl carousel 2. Here is the current code I have: $(document).ready(function() { $("#slider").owlCarousel({ margin:0, autoplay : true, lazyLoad : true, items : 1, au ...

Calculating variables in JavaScript

Explanation from Mozilla Documentation: console.log((function(...args) {}).length); // The result is 0 because the rest parameter is not counted console.log((function(a, b = 1, c) {}).length); // The result is 1 because only parameters before th ...

Using jQuery, what is the best way to conceal a Div while the scroll bar is in motion?

Is there a way to make the #menu fade when the scroll bar is in motion, creating a cleaner interface? I'm hoping to find code that will detect scroll bar movement, allowing the #menu to gradually fade out after 1 second of scrolling and come back aft ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

Choosing not to transmit the requested file

I've been attempting to retrieve the following: fetch("https://www.filestackapi.com/api/store/S3?key=MYKEY&filename=teste", { body: "@/C:/Users/Acer/Pictures/1 (2).jpg", headers: { "Content-Type": &quo ...

Webpack failing to load jQuery correctly

In the process of transitioning my application.js application into smaller page bundles using SplitChunks, I have encountered a situation in my users/show.html.erb page where I am utilizing the following tag to import the specific chunk. <%= javascript ...