Have you ever wondered why your server doesn't deliver the 'correct' response on the first attempt? Or as NuclearGhost pointed out, why does it provide varying responses for the same request?
To achieve what you're seeking, recursion is necessary. It's not possible to simply do this in a loop due to the asynchronous nature of the response. However, if you define a function, you can call that function within the success handler like so:
function retrieveJSONUsingRecursion(maxRetries, count) {
if(!count) count = 1;
if (count > maxRetries) {
alert('Giving up after '+count+' retries.');
return;
}
$.getJSON('http://www.mysite.com/doit.php?', function(data) {
if(!data || !data.contents || data.contents.indexOf('seasonEpisode') == -1) {
retrieveJSONUsingRecursion(++count, maxRetries);
} else {
$('#output').html(data.contents);
}
})
}
You can then invoke this function like this:
retrieveJSONUsingRecursion(5);
I highly suggest including the count parameter to prevent stack overflow if the correct response never arrives. If you are trying to avoid a server timeout or overload issue, consider placing the recursive call inside a setTimeout function, such as:
if(!data || !data.contents || data.contents.indexOf('seasonEpisode') == -1) {
setTimeout(function() { retrieveJSONUsingRecursion(++count, maxRetries)}, 5000);
// etc.
This approach adds a 5-second delay between calls, reducing the risk of overwhelming your server and ensuring your getjson requests are paced appropriately.