0

EDIT: This question has been substantially edited in response to comments.

I use window.onerror to catch syntax errors in my JS scripts. I made an Ajax call (unimportant in itself) which returned an empty response:

$.ajax({
  url:"../php/ajax/outdated-ajax.php",
  method:"POST",
  data:{"getusers" : JSON.stringify(gMetaData)},
})
.done(function(response) {  // response = ""
  var incoming = JSON.parse(response);
  ...

I would have expected window.onerror to flag the fault in JSON.parse caused by the empty response, but I got the unhelpful "Script error", (perhaps implying some CORS issue), rather than the expected "Uncaught SyntaxError: Unexpected end of JSON input" or similar. I've tried putting in the fully qualified url but this makes no difference.

All my JS scripts and PHP functions are on the same domain. Could the "Script error" response be something to do with the error occurring within a promise?

Why this error and how can I avoid it?

magnol
  • 344
  • 3
  • 15
  • if outdated-ajax.php doesn't exists, http response is 404, so it depend on how your code handle errors. Did you implement .fail function or .always function? If yes, probably the error is there. .done function is not executed in case of protocol error. you should add some details about the error you got. – Lety Sep 04 '21 at 12:37
  • The script outdated-ajax.php exists but the Ajax call parameter doesn't. See edited question. – magnol Sep 04 '21 at 13:21
  • it could be that gMetaData has not a valid json data, you should try to send parameter using, for example: data: { name: "John" } just to see if php receives it, if yes, the problem is in gMetaData. here is a useful link: https://262.ecma-international.org/7.0/#sec-serializejsonobject – Lety Sep 04 '21 at 18:27
  • @Lety: The gMetadata is valid. I haven't explained this very well. The error triggering window.onerror is the empty return value in the variable 'response'. The issue is why window.onerror is returning "Script errror", implying a CORS problem, instead of "Uncaught SyntaxError: Unexpected end of JSON input". – magnol Sep 04 '21 at 21:06
  • the error you got it is probably related to a js you include from other domain. this is a useful link https://stackoverflow.com/questions/5913978/cryptic-script-error-reported-in-javascript-in-chrome-and-firefox. If this is your case, probably the error is not related to your code, except if your js is loaded from a domain different from the domain of the page that run your code. – Lety Sep 05 '21 at 11:25
  • @Lety: Thanks for your reference. Very useful. However, all my JS scripts are hosted locally as is the PHP script. I'm guessing it has something to do with the error occurring within a promise. Any thoughts, anyone? – magnol Sep 06 '21 at 08:02
  • did you check if your server send Access-Control-Allow-Origin? It could be an error in its configuration. – Lety Sep 06 '21 at 10:10

0 Answers0