XHR Upload Progress claims immediate completion - javascript

Ok, I've tried everything I can think of and perused all the existing questions, but none of them have any actual answers.
I have an angularjs front end and java/REST backend, running on Tomcat.
I have an XMLHttpRequest and a progress event listener that looks like this:
xhr.upload.addEventListener('progress', function(e) {
console.log(e.loaded);
console.log(e.total);
}, false);
If I'm uploading a 100MB file, the progress event listener fires repeatedly, but reports 100% within the first second. The xhr then returns that it's loaded roughly 30 seconds to a minute later, as would be expected. I have tried setting different headers, using sendAsBinary() instead of send, and a number of other techniques that I cannot recall off the top of my head. The angular app is running on localhost, the Tomcat app server acts the same way whether I use my local dev instance or a hosted dev instance.
I'm looking for any ideas I can get, whether they be Tomcat settings, code changes, or anything else. I know that the problem is not in the java backend code itself because the progress event has stopped firing at 100% done before the file processing code even begins running. This happens on Chrome 40/FF 35/Safari 6.

Related

How can I cancel consecutive requests to my server? [duplicate]

What would cause a page to be canceled? I have a screenshot of the Chrome Developer Tools.
This happens often but not every time. It seems like once some other resources are cached, a page refresh will load the LeftPane.aspx. And what's really odd is this only happens in Google Chrome, not Internet Explorer 8. Any ideas why Chrome would cancel a request?
We fought a similar problem where Chrome was canceling requests to load things within frames or iframes, but only intermittently and it seemed dependent on the computer and/or the speed of the internet connection.
This information is a few months out of date, but I built Chromium from scratch, dug through the source to find all the places where requests could get cancelled, and slapped breakpoints on all of them to debug. From memory, the only places where Chrome will cancel a request:
The DOM element that caused the request to be made got deleted (i.e. an IMG is being loaded, but before the load happened, you deleted the IMG node)
You did something that made loading the data unnecessary. (i.e. you started loading a iframe, then changed the src or overwrite the contents)
There are lots of requests going to the same server, and a network problem on earlier requests showed that subsequent requests weren't going to work (DNS lookup error, earlier (same) request resulted e.g. HTTP 400 error code, etc)
In our case we finally traced it down to one frame trying to append HTML to another frame, that sometimes happened before the destination frame even loaded. Once you touch the contents of an iframe, it can no longer load the resource into it (how would it know where to put it?) so it cancels the request.
status=canceled may happen also on ajax requests on JavaScript events:
<script>
$("#call_ajax").on("click", function(event){
$.ajax({
...
});
});
</script>
<button id="call_ajax">call</button>
The event successfully sends the request, but is is canceled then (but processed by the server). The reason is, the elements submit forms on click events, no matter if you make any ajax requests on the same click event.
To prevent request from being cancelled, JavaScript event.preventDefault(); have to be called:
<script>
$("#call_ajax").on("click", function(event){
event.preventDefault();
$.ajax({
...
});
});
</script>
NB: Make sure you don't have any wrapping form elements.
I had a similar issue where my button with onclick={} was wrapped in a form element. When clicking the button the form is also submitted, and that messed it all up...
Another thing to look out for could be the AdBlock extension, or extensions in general.
But "a lot" of people have AdBlock....
To rule out extension(s) open a new tab in incognito making sure that "allow in incognito is off" for the extention(s) you want to test.
In my case, I found that it is jquery global timeout settings, a jquery plugin setup global timeout to 500ms, so that when the request exceed 500ms, chrome will cancel the request.
You might want to check the "X-Frame-Options" header tag. If its set to SAMEORIGIN or DENY then the iFrame insertion will be canceled by Chrome (and other browsers) per the spec.
Also, note that some browsers support the ALLOW-FROM setting but Chrome does not.
To resolve this, you will need to remove the "X-Frame-Options" header tag. This could leave you open to clickjacking attacks so you will need to decide what the risks are and how to mitigate them.
Here's what happened to me: the server was returning a malformed "Location" header for a 302 redirect.
Chrome failed to tell me this, of course. I opened the page in firefox, and immediately discovered the problem.
Nice to have multiple tools :)
Another place we've encountered the (canceled) status is in a particular TLS certificate misconfiguration. If a site such as https://www.example.com is misconfigured such that the certificate does not include the www. but is valid for https://example.com, chrome will cancel this request and automatically redirect to the latter site. This is not the case for Firefox.
Currently valid example: https://www.pthree.org/
A cancelled request happened to me when redirecting between secure and non-secure pages on separate domains within an iframe. The redirected request showed in dev tools as a "cancelled" request.
I have a page with an iframe containing a form hosted by my payment gateway. When the form in the iframe was submitted, the payment gateway would redirect back to a URL on my server. The redirect recently stopped working and ended up as a "cancelled" request instead.
It seems that Chrome (I was using Windows 7 Chrome 30.0.1599.101) no longer allowed a redirect within the iframe to go to a non-secure page on a separate domain. To fix it, I just made sure any redirected requests in the iframe were always sent to secure URLs.
When I created a simpler test page with only an iframe, there was a warning in the console (which I had previous missed or maybe didn't show up):
[Blocked] The page at https://mydomain.com/Payment/EnterDetails ran insecure content from http://mydomain.com/Payment/Success
The redirect turned into a cancelled request in Chrome on PC, Mac and Android. I don't know if it is specific to my website setup (SagePay Low Profile) or if something has changed in Chrome.
Chrome Version 33.0.1750.154 m consistently cancels image loads if I am using the Mobile Emulation pointed at my localhost; specifically with User Agent spoofing on (vs. just Screen settings).
When I turn User Agent spoofing off; image requests aren't canceled, I see the images.
I still don't understand why; in the former case, where the request is cancelled the Request Headers (CAUTION: Provisional headers are shown) have only
Accept
Cache-Control
Pragma
Referer
User-Agent
In the latter case, all of those plus others like:
Cookie
Connection
Host
Accept-Encoding
Accept-Language
Shrug
I got this error in Chrome when I redirected via JavaScript:
<script>
window.location.href = "devhost:88/somepage";
</script>
As you see I forgot the 'http://'. After I added it, it worked.
Here is another case of request being canceled by chrome, which I just encountered, which is not covered by any of answers up there.
In a nutshell
Self-signed certificate not being trusted on my android phone.
Details
We are in development/debug phase. The url is pointing to a self-signed host. The code is like:
location.href = 'https://some.host.com/some/path'
Chrome just canceled the request silently, leaving no clue for newbie to web development like myself to fix the issue. Once I downloaded and installed the certificate using the android phone the issue is gone.
If you use axios it can help you
// change timeout delay:
instance.defaults.timeout = 2500;
https://github.com/axios/axios#config-order-of-precedence
For my case, I had an anchor with click event like
<a href="" onclick="somemethod($index, hour, $event)">
Inside click event I had some network call, Chrome cancelling the request. The anchor has href with "" means, it reloads the page and the same time it has click event with network call that gets cancelled. Whenever i replace the href with void like
<a href="javascript:void(0)" onclick="somemethod($index, hour, $event)">
The problem went away!
If you make use of some Observable-based HTTP requests like those built-in in Angular (2+), then the HTTP request can be canceled when observable gets canceled (common thing when you're using RxJS 6 switchMap operator to combine the streams). In most cases it's enough to use mergeMap operator instead, if you want the request to complete.
I had faced the same issue, somewhere deep in our code we had this pseudocode:
create an iframe
onload of iframe submit a form
After 2 seconds, remove the iframe
thus, when the server takes more than 2 seconds to respond the iframe to which the server was writing the response to, was removed, but the response was still to be written , but there was no iframe to write , thus chrome cancelled the request, thus to avoid this I made sure that the iframe is removed only after the response is over, or you can change the target to "_blank".
Thus one of the reason is:
when the resource(iframe in my case) that you are writing something in, is removed or deleted before you stop writing to it, the request will be cancelled
I have embedded all types of font as well as woff, woff2, ttf when I embed a web font in style sheet. Recently I noticed that Chrome cancels request to ttf and woff when woff2 is present. I use Chrome version 66.0.3359.181 right now but I am not sure when Chrome started canceling of extra font types.
We had this problem having tag <button> in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button inside the form.
So if you realy want to use button instead of regular div or span on the page, and you want to send form throw js - you should setup a listener with preventDefault function.
e.g.
$('button').on('click', function(e){
e.preventDefault();
//do ajax
$.ajax({
...
});
})
I had the exact same thing with two CSS files that were stored in another folder outside my main css folder. I'm using Expression Engine and found that the issue was in the rules in my htaccess file. I just added the folder to one of my conditions and it fixed it. Here's an example:
RewriteCond %{REQUEST_URI} !(images|css|js|new_folder|favicon.ico)
So it might be worth you checking your htaccess file for any potential conflicts
happened to me the same when calling a. js file with $. ajax, and make an ajax request, what I did was call normally.
In my case the code to show e-mail client window caused Chrome to stop loading images:
document.location.href = mailToLink;
moving it to $(window).load(function () {...}) instead of $(function () {...}) helped.
In can this helps anybody I came across the cancelled status when I left out the return false; in the form submit. This caused the ajax send to be immediately followed by the submit action, which overwrote the current page. The code is shown below, with the important return false at the end.
$('form').submit(function() {
$.validator.unobtrusive.parse($('form'));
var data = $('form').serialize();
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
if ($('form').valid()) {
$.ajax({
url: this.action,
type: 'POST',
data: data,
success: submitSuccess,
fail: submitFailed
});
}
return false; //needed to stop default form submit action
});
Hope that helps someone.
For anyone coming from LoopbackJS and attempting to use the custom stream method like provided in their chart example. I was getting this error using a PersistedModel, switching to a basic Model fixed my issue of the eventsource status cancelling out.
Again, this is specifically for the loopback api. And since this is a top answer and top on google i figured i'de throw this in the mix of answers.
For me 'canceled' status was because the file did not exist. Strange why chrome does not show 404.
It was as simple as an incorrect path for me. I would suggest the first step in debugging would be to see if you can load the file independently of ajax etc.
The requests might have been blocked by a tracking protection plugin.
It happened to me when loading 300 images as background images. I'm guessing once first one timed out, it cancelled all the rest, or reached max concurrent request. need to implement a 5-at-a-time
One the reasons could be that the XMLHttpRequest.abort() was called somewhere in the code, in this case, the request will have the cancelled status in the Chrome Developer tools Network tab.
In my case, it started coming after chrome 76 update.
Due to some issue in my JS code, window.location was getting updated multiple times which resulted in canceling previous request.
Although the issue was present from before, chrome started cancelling request after update to version 76.
I had the same issue when updating a record. Inside the save() i was prepping the rawdata taken from the form to match the database format (doing a lot of mapping of enums values, etc), and this intermittently cancels the put request. i resolved it by taking out the data prepping from the save() and creating a dedicated dataPrep() method out of it. I turned this dataPrep into async and await all the memory intensive data conversion. I then return the prepped data to the save() method that i could use in the http put client. I made sure i await on dataPrep() before calling the put method:
await dataToUpdate = await dataPrep();
http.put(apiUrl, dataToUpdate);
This solved the intermittent cancelling of request.

Event listener works in on context but not another - code identical, and no errors observed. Possible causes?

I'm bamboozled. I use a select2 widget on a web page, implemented by django-autocomplete-light, and I attach an event listener to the it as follows:
const game_selector = $("#"+id_prefix+"game");
game_selector.on("change", switchGame);
Works a charm. I select a new game in the select box and the switchGame function is called.
That is running on Django development server with manage.py runserver. And I can see how groovy this is in Chrome's debugger:
There it is, switchGame(event) is the handler. And it all works too. No drama.
But I publish the code to my webserver and suddenly it doesn't work. The event listener never fires. switchGame is never called.
It's serving the self same code, looks the same in the client and in Chrome's debugger. All fine. I can even see the event listener is attached, albeit the order is different:
Served by the development server there there is a select2 handler above switchGame in the list and served from the production server the same select2 handler is listed below the switchGame handler.
Can the order matter? And why would the order differ?
In the end I am looking at the same binding code above, and I can set a breakpoint inside switchGame and cI can confirm served by the django runserver switchGame runs when I select a new game, but served from the production server it does not.
Suspect some jquery issue I even changed the listener binding to:
const game_selector = $("#"+id_prefix+"game");
//game_selector.on("change", switchGame);
game_selector.get(0).addEventListener("change", switchGame);
But the behaviour is the same. Bamboozles me how Javascript might function differently based on the server context? leads me to suspect different Javascript being served, but every check I have made speaks against that, as in I can make an edit, publish and reload web page from productions server and the changed javascript is there and visible in Chrome's debugger.
I wonder if anyone has ever experience such bizarre behaviour before and is in a position to comment or to suggest further diagnostic directions.
This is a nasty side effect of loading the jQuery library twice.
I was loading it explicitly and a widget I was using loaded it again implicitly. A bug!
Discussed in depth here:
github.com/yourlabs/django-autocomplete-light/issues/1079
and not yet fixed, but workaround is that I don't load jQuery explicitly any more. And the issue disappears.
Sadly this does not explain the symptoms very well but it does provide a solution to what was being experienced. The same code was running in two contexts working in one and not the other. Remove the jQuery reload and it works in both.

Aborting/Cancelling an AJAX request not working in IE

I have an application where a user is allowed to upload and download documents. In the download area, the user can select multiple files (all pdf), and do a merge and download.
Great.
There is a modal window that pops up during the merge process, that shows the status of the merge, with a progress bar using SignalR. This works fine across all browsers, and the download happens.
Problem: There is a Cancel Merge and Download button on this modal. It stops the SignalR hub, and sends an abort() request to the AJAX call. This works in Safari, Chrome, and FF - but not IE.
When I look at Fiddler, Chrome stops the server side method in it's tracks. In IE, it tries to send that request to SignalR. The result in IE is that the modal window goes away as expected, but a few seconds later you receive the prompt that the file has been downloaded (actual processing never stops). Note the difference where the abort is called in the Fiddler session below.
Fiddler (Chrome - working):
Fiddler (IE - not working):
Javascript:
$('#cancelDownloadMerge').on('click', function () {
$.connection.hub.stop();
XX.Documents.DocumentsView.download.abort();
XX.Documents.DocumentsView.mergeCancelled = true;
XX.Documents.DocumentsView._isMerging = false;
});
The AJAX call that gets fired when Merge And Download is initially clicked is lengthy and proprietary, however, cache: false and crossDomain: true (since currently running localhost) are set as such, yet the problem still persists. I do not think the AJAX call is so much relevant as this is very much isolated to IE, but I can try and post more if needed.
I suspect this has something to do with the fact that Chrome and FF are using ServerSentEvents whereas IE is using forever frame (SSE not supported).
I'm stuck on this one, any help is greatly appreciated.
The problem was due to the fact that SignalR was always defaulting to using Forever Frame in IE. Adding the below restriction forced SignalR to use Long Polling in IE.
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] });

Javascript debugging difficult as browser doesn't refresh the scripts!

I'm trying to debug a Javascript written in the Mootools framework. Right now I am developing a web application on top of Rails and my webserver is the rails s that boots WEBrick.
When I modify a particular tree.js file thats called with in one a mootools init script,
require: {
css: [MUI.path.plugins + 'tree/css/style.css'],
js: [MUI.path.plugins + 'tree/scripts/tree.js'],
onload: function(){
if (buildTree) buildTree('tree1');
}
},
the changes are not loaded as the headers being sent to the client are Last Modified: 10 July, 2010..... which is obviously not true since I just modified the file.
How do I get rid of this annoying caching. If I go directly to the script in my browser (Chrome) it doesn't show the changes until I hit refresh, but this doesn't fix my problem when I go back to my application and hit refresh, it still loads the pre-modified script.
This has happen to me also in FF, I think it is a cache header sent by the server or the browser itself.
Anyway a simple way to avoid this problem while in development is adding a random param to the file name of the script.
instead of calling 'tree/scripts/tree.js' use 'tree/scripts/tree.js?'+random that should invalidate all caches.
As frisco says, adding a random number in development does the trick but you will likely find that the problem still affects you production. You want to push new JavaScript changes to your users but can't until their browsers stop caching the file. In order to do this, just get the files mtime and add that as the random string. This will only change when the file is modified and so the JavaScript will be loaded from cache if it has not been changed or it will be loaded from the server, if it has.
PHP has the function filemtime but as I'm not familiar with Ruby, I'm afraid I can't help you further in that direction (sorry!). However, this answer seems to accomplish what you want.
Try the Ctrl+F5 trick. To avoid hitting browser cache.
More info here:
What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Where in JavaScript is the request coming from?

I am debugging a large, complex web page that has a lot of JavaScript, JQuery, Ajax and so on. Somewhere in that code I am getting a rouge request (I think it is an empty img) that calls the root of the server. I know it is not in the html or the css and am pretty convinced that somewhere in the JavaScript code the reqest is being made, but I can't track it down. I am used to using firebug, VS and other debugging tools but am looking for some way to find out where this is executed - so that I can find the offending line amongst about 150 .js files.
Apart from putting in a gazzillion console outputs of 'you are now here', does anyone have suggestions for a debugging tool that could highlight where in Javascript requests to external resources are made? Any other ideas?
Step by step debugging will take ages - I have to be careful what I step into (jQuery source - yuk!) and I may miss the crucial moment
What about using the step-by-step script debugger in Firebug ?
I also think that could be a very interesting enhancement to Firebug, being able to add a breakpoint on AJAX calls.
You spoke of jQuery source...
Assuming the request goes through jQuery, put a debug statement in the jQuery source get() function, that kicks in if the URL is '/'. Maybe then you can tell from the call stack.
You can see all HTTP request done through JavaScript using the Firebug console.
If you want to track all HTTP requests manually, you can use this code:
$(document).bind('beforeSend', function(event, request, ajaxOptions)
{
// Will be called before every jQuery AJAX call
});
For more information, see jQuery documentation on AJAX events.
If its a HTTPRequest sent to a web server, I would recommend using TamperData plugin on Firefox. Just install the plugin, start tamper data, and every request sent will be prompted to tamper/continue/abort first.
Visit this page at Mozilla website
Just a guess here, but are you using ThickBox? It tries to load an image right at the start of the code.
First thing I would do is check whether this rouge request is an Ajax request or image load request via the Net panel in Firebug.
If it's Ajax, then you can overload the $.ajax function with your own and do a strack trace and include the URL requested before handing off to the original $.ajax.
If it's an image, it's not ideal, but if you can respond to the image request with a server side sleep (i.e. php file that just sleeps for 20 seconds) you might be able to hang the app and get a starting guess as to where the problem might be.

Categories

Resources