Reputation: 3662
When using the jQuery Ajax function, when specifying error and success handlers, you would expect invalid files and 404 errors to be caught by the designated error handler function, but for some reason my code does not.
Code:
// using jQuery 3.4.1
// this code has been taken from a larger function, but the issue can be replicated by pasting
// the following code into the JS Console.
var scriptPath = 'http://mywebserver.localhost/application/invalid.js';
jQuery.ajax( {
async: false,
type: 'GET',
url: scriptPath,
crossOrigin: false,
data: null,
global: false,
cache: true,
success: function() {
debugger;
// do some stuff
onResult();
},
error: function( jqXHR, textStatus, errorThrown ) {
debugger;
Lib.showNetworkErrorAlert( jqXHR, textStatus, errorThrown );
},
dataType: 'script'
} );
This results in:
Uncaught Error From: ~unknown~
Error: Uncaught SyntaxError: Unexpected token '<' in: http://mywebserver.localhost/........ line: 1
Just to clarify, I have looked at the SO questions out there already, but the ones I found tended to focus on the cause of the error. I know what the error 'Unexpected token < in ...' is, its simply JS trying to parse the target as JS, but instead its given a 404 error html file, so the < from the first tag triggers the error.
What I am trying to find out and understand, is why this error appears instead of the normal error handler that is specified. At the very least I would have thought setting the dataType to script would make it give a slightly better error to realise, hey this is a HTML 404 error file, not a script.
Any help and insight greatly appreciated.
Update: Here's the Network tab from Dev Tools showing it is returning a 404.
Upvotes: 1
Views: 969
Reputation: 3662
Turns out this is actually a bug in jQuery - rather than me using it incorrectly - which was reported back in 2018, but the fix was only earmarked for inclusion in jQuery 4.0.0
.
However that might be a while away, so I have now reported the bug again for inclusion in more current versions, and the admins have since discussed this and decided to include it as a fix in 3.5.0
.
Normally, using the dataType:script
attribute tells jQuery's Ajax function "I'm supplying a script, please execute the JavaScript once it has loaded."
The problem was that regardless of the response status code, the file (or whatever was returned) would be evaluated as JavaScript (even if not JavaScript), which of course is going to cause errors if a 404 error returns a 404 Error HTML page.
The solution to this can be seen on Github (Just so I dont explain it incorrectly here), but in simple terms it should no longer execute scripts for unsuccessful HTTP responses.
Upvotes: 1