I have a browser app which, on the load of a particular page, makes an ajax request to the server to get some JSON data. Upon return the ajax request is handled and all is fine.
The server I'm calling is currently having some annoying intermittent issues, one in particular is randomly causing the response from my ajax call to return nothing instead of JSON. The usefulness of this particular page is relying on the data being returned from this ajax call correctly, therefore the fact that in some cases it's not being returned as expected is causing my users (and hence, me!) issues.
Now, if I make the exact same call again, immediately after the initial call returns the wrong response, then the server will return the correct response!
I don't want to get into the server issues, they're currently being worked out but I've not got a timescale for when that might be finished yet. So while the server issues are being worked out, I'd like to put some kind of catch into my ajax request to handle the times when the server returns the wrong response, and then immediately make the exact same call again. Note, this is only a short term fix to stop my users complaining, until the server issues are sorted!
What I currently have is similar to this:
$.ajax({
type: "GET",
data: data,
success: function(data, textStatus, jqXhr){
// Do stuff...
}
});
When the server throws a wobbly, data
is coming back as undefined. So what I really want to do is test whether data
is undefined
and if so, re-make the same call to the same ajax request (every test I've done shows the correct response is received the 2nd time round!).
So, to me this feels like a good use case for a Goto
statement (gasp, shock, horror!!!) within the undefined test but, I'm not even sure you can do that in JS and also, I know their use is considered pretty bad practice.
I know there are a couple of ways around it e.g:
I could put the call inside a
while(wasAjaxCallSuccessful){}
loop, setting my ajax request to synchronous and only setting thewasAjaxCallSuccessful
variable to true ifdata
comes back as notundefined
. But that feels just as bad as using a Goto statement (if that were even allowed).Another option would be to repeat the call to the ajax request inside my
data == undefined
test. But again, that just feels wrong too.
So I wondered what would be considered the most appropriate way to handle this, albeit pretty unusual, scenario?