The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute. I placed a breakpoint at the Registration function, but it does not get triggered, resulting in the grid not refreshing. Any suggestions on how to resolve this problem?

     $("#lnkAddAttachment").click(function (e) {
        if (document.getElementById("txtFile").files[0] != null) {
            oFiles = document.getElementById("txtFile").files[0];
            nFiles = oFiles.size;

            var selectedFile = document.getElementById("txtFile").files[0];

            var xhr = new XMLHttpRequest();
            var fd = new FormData();
            var url = '@Url.Content("~/")' + "ESignature/getFile";

            fd.append("file", document.getElementById('txtFile').files[0]);
            $("#loadingwrapper").fadeIn();
            xhr.open("POST", url, true);
            xhr.send(fd);
            xhr.addEventListener("load", function (event) {
                var url = '@Url.Content("~/")' + "ESignature/Registration";
                $('#gridAttachments').load(url + ' #gridAttachments');
                $("#loadingwrapper").fadeOut();
            }, false);
            $('#txtDescription').val('');
            $('#txtFile').val('');

            return false;
        } 
    });

Answer №1

In Firefox, the "addEventListener" method is fully supported; however, it may not work in IE. To handle the event of completing a request, you should use "onreadystatechange" instead. Remember to set up your "onreadystatechange" handler before calling "send", as the request to the server could finish before the handler is ready.

For more information on XMLHttpRequest properties, visit: here

Answer №2

If you're already utilizing jQuery, my recommendation would be to utilize $.ajax instead of directly using XMLHttpRequest, as it is likely to resolve the issue at hand.

However, if you have a specific reason for sticking with using XMLHttpRequest directly, it's probable that you'll need to utilize readystatechange instead of load. It's possible that IE11 doesn't support load, or does not support it in the compatibility setting being applied to your page. If your page is loading under an older compatibility mode, the addEventListener won't be available on the XMLHttpRequest object.

Since you are not sharing the XMLHttpRequest instance with anyone else, here's a straightforward approach to address both potential issues:

xhr.onreadystatechange = function () {
    if (xhr.readystate === 4) { // Additionally, verify 'status'
        var url = '@Url.Content("~/")' + "ESignature/Registration";
        $('#gridAttachments').load(url + ' #gridAttachments');
        $("#loadingwrapper").fadeOut();
    }
};

And as mentioned by Chris, ensure to place this code before calling .send.

Once again: You have a library that can handle these tasks more efficiently. Make use of it.

Answer №3

After making some adjustments to the URL, I was able to get it working. The issue was that Internet Explorer was caching the URL and not hitting the Registration function. To solve this, I added a new variable called 'check' to the URL with a unique value every time, ensuring that the Registration function is always accessed.

var url = '@Url.Content("~/")' + "ESignature/Registration?check=" + new Date().getTime();

Here's the complete code:

$("#lnkAddAttachment").click(function (e) {
    if (document.getElementById("txtFile").files[0] != null) {
        oFiles = document.getElementById("txtFile").files[0];
        nFiles = oFiles.size;

        var selectedFile = document.getElementById("txtFile").files[0];

        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        var url = '@Url.Content("~/")' + "ESignature/getFile";

        fd.append("file", document.getElementById('txtFile').files[0]);
        $("#loadingwrapper").fadeIn();
        xhr.open("POST", url, true);
        xhr.send(fd);
        xhr.addEventListener("load", function (event) {
            var url = '@Url.Content("~/")' + "ESignature/Registration?check=" + new Date().getTime();
            $('#gridAttachments').load(url + ' #gridAttachments');
            $("#loadingwrapper").fadeOut();
        }, false);
        $('#txtDescription').val('');
        $('#txtFile').val('');

        return false;
    } 
});

A big thank you to T.J. Crowder and Chris for their valuable contributions.

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

steps for setting up babel-cli and babel-preset-react

I attempted various methods of installing babel-cli babel-preset-react Here's what I tried: npm install --save-dev babel-cli babel-preset-react However, when I run babel -h An error message appears saying The program 'babel' can be found ...

Step-by-step guide on installing both Angular and Nodejs within a single folder

I'm diving into the world of NodeJs and Angular, and I recently created a simple NodeJS application following instructions from this link. However, I encountered an issue when trying to install Angular alongside NodeJS. After running ng new angular-cr ...

Crafting artistic shapes using the Canny Edge Detection technique on Canvas

Can someone provide some guidance on using Canny Edge Detection to generate shapes in Canvas? ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

Transforming Color with JQuery on the Fly

Check out this Jquery script that gradually changes the color of an object from (0, 0, 0) to (255, 255, 0). $(document).ready(function(){ var r = 0; var g = 0; changeColor(r, g); }); function changeColor(r, g){ var newColor = "(" + r + ", ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Reactive property cannot be defined on an undefined, null, or primitive value within the context of Bootstrap Vue modal

Can someone please assist me with this error message? It says "app.js:108639 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value." I encountered this error while working with a Bootstrap Vue modal. Here is a snippet of my code: ...

Load a webpage with two dropdown menus in JavaScript/jQuery that have the same selection option pre-selected

I am facing an issue with two dropdown menus that should display the same value when the page loads. These dropdowns are used for filtering products on a WooCommerce website based on the selected vehicle. Initially, the user selects the Make, Model, and Se ...

Utilizing AngularJS directives with the power of string formatting

Looking at this JSON structure {textTemplate:"Name:{0},Phone:{1}",controls:[{id:1,Name:"Name",type:"text"},{id:2,Name:"Phone",type:"text"}]} I'm unsure how to utilize the directive for converting strings into HTML controls This is what I&apos ...

Using setInterval on a batch of freshly generated div elements

I am interested in creating a small website where I can display multiple clocks for various time zones. However, I have encountered an issue with the setInterval function. Below is the code snippet: function addClock () { $("#container").append('& ...

Truncating decimal points in JavaScript

In this scenario, if the number after the decimal point is 0, then the zero should be removed. Otherwise, the number should be displayed as it is. Here are some examples of what I am aiming for in vue: 100.023 => 100.023 1230.0 => 1230 ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

Show the elements of an array (that have been read and processed from a text file) on separate lines using JavaScript

Hello, I have the code below where a user can upload a text file. I attempted to display the output in a div after splitting it using the @ character. The array elements stored in variables are correctly displayed with new lines in an alert, but they are p ...

Conceal the div element if the value exceeds 0

I'm looking for a way to display a div when the number of remaining days is less than 0. I got it working on jsfiddle, but for some reason, it doesn't work anywhere else. if ($('.daysrem&a ...

Typescript implementation for structuring JSON response data from API calls

As a beginner in Typescript, I am eager to create a straightforward weather application using Firebase functions. One of the initial steps involves making an API call to fetch the current temperature of a particular city. Upon making the API call, the JSO ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

Spin a child element by clicking on its parent component

I am looking to create a unique animated effect for the arrows on a button, where they rotate 180 degrees each time the button is clicked. The concept involves rotating both sides of the arrow (which are constructed using div elements) every time the con ...