What is the best way to keep making getjson calls until a non-empty response is received?

Hey there, I have a question about handling the response from a getjson call. I'm looking to check if the siteContents response is empty or missing a required string (specifically, looking for seasonEpisode=). If it's not as expected, I want to make another getjson call. Is it possible to call getjson again from within the original call? My ultimate goal is to ensure I receive the correct response from getjson. Any help would be greatly appreciated. Thank you!

$.getJSON('http://www.mysite.com/doit.php?value=55?', function(data){
    //$('#output').html(data.contents);

 var siteContents = data.contents; 

Answer №1

Give this a shot:

let handlerFunction = function(data){
   //$('#output').html(data.contents);
   let siteContent = data.contents; 
   if (!siteContent) { 
       $.getJSON('http:/...', handlerFunction);
       return;
   }
   // handle siteContents
}

$.getJSON('http://...', handlerFunction);

Note: the code above may lead to excessive server requests if it repeatedly checks for empty site content, potentially causing an infinite loop and increased server load. To improve this situation, consider implementing the following two enhancements:

1) Keep track of how many consecutive failed attempts occur due to empty site content. After reaching a certain threshold (e.g., 20 attempts), halt the loop with an appropriate error message.

2) Utilize

setTimeout(function() { $.getJSON(...) },  delay)
to introduce a delay between retries. Specify a time in milliseconds for the delay parameter.

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

Verify the Javascript for file upload in ASP.NET folder prior to uploading it

Struggling with this problem for days now, I could really use some fresh perspective. My setup includes Windows Server 2012, IIS 8.0, and ASP.NET 4.5. I'm new to both IIS and ASP.NET, so please bear with me. The website I'm working on involves f ...

Best practice for injecting dynamic HTML using .ajax() call

Here is an example of a successful JSON Facebook Graph API request that retrieves data objects and displays their page-id pictures inside `img` tags within the `#results` div. success: function(res){ console.log(res); ...

What is the process of editing a webpage to affect the display on a different webpage?

I am currently working on creating two webpages. One will serve as a customization page where users can upload images and input text, which will then be displayed on another page. I am wondering if it is possible to achieve this functionality using CSS and ...

Ajax is updating the information stored in the Data variable

Recently, I reached out to tech support for help with an issue related to Ajax not executing properly due to Access-Control-Allow-Origin problems. Fortunately, the technician was able to resolve the issue by adding a file named .htaccess with the code Head ...

AngularJS $http.post() response function not executing in the correct sequence

When calling a function from my angular controller to make a $http.post() request, the code below the function call is executing before the successFunction(), preventing the code inside the if block from running. How can I ensure the if block executes wi ...

Using the useQuery() function in a Next.js React app successfully fetches data from the API on the client side, yet the same API call fails to work when implemented in getServerSideProps on

I am attempting to retrieve data from the backend server using React Query within Next JS getServerSideProps. Here is the function used to fetch the data: export const getGoogleAuthUrl = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC ...

Guide to showcasing Laravel Eloquent information using jQuery "Ajax" tooltips?

I am new to Laravel and currently working with an index.blade.php file that contains data in table form: <table class="table table-striped"> <thead> <tr> <td>ID</td> < ...

Getting the height of a div in a Nuxt.js application results in an error alert being displayed

Trying to retrieve the height of a div within a grid in a Nuxt application. <template> <div class="grid grid-cols-3"> <client-only> <Item v-for="( item, itemIndex ) in ItemsArray" ...

In React Native, the conversion from ReadableNativeMap to Double does not allow for direct casting of value for value

I've been working on creating a cool animation effect for the text ams with the help of react-native-reanimated. Although I suspect the issue lies within the Animated component, I'm struggling to identify a solution. https://i.sstatic.net/SYl19. ...

Center Vertically Using CSS Flexbox

Hey there, I'm currently facing an issue with aligning my website's logo vertically in the middle with my navigation link list. I have attempted to use "vertical-align: middle" on my div columns but it doesn't seem to be working. Right now, ...

ways to change date format in a React.js application using JavaScript

<b>Choose Date and Time</b><br/> <DateTimeField onChange={this.clockevent} format={"x"}/> clockevent=(newDate)=>{ var dateVal ="/Date("+newDate+")/"; var date = new Date(parseFloat(dateVal.substr(6))); console.log( ...

Selecting an option from the dropdown menu to automatically fill in a textbox within

I've run into a small hiccup with some javascripts/AJAX and could really use some guidance in the right direction. My issue involves populating the per-carton-price-field using collection_select within a form. This form is meant to generate an entry ...

Is there a way to execute a condition in a Vue component before rendering the HTML in the template?

Here is an example of my Vue component: <template> <div id="modal-transaction" class="modal fade" tabindex="-1" role="dialog"> ... <div class="modal-header"> <h4 class="modal ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Creating MongoDB queries on-the-fly in a NodeJS environment

Upon receiving a POST argument structured as follows: sort: [ { field: 'name', dir: 'asc', compare: '' }, { field: 'org', dir: 'asc', compare: '' } ] } It is necessary ...

ng-include not functioning properly within ng-table

In the table, there is a data structure <tr ng-repeat="question in $data" ng-include="'/views/partials/questionList.html'"></tr> Within the questionList.html file: <td class="top-td" data-title="'ID'" sortable="&ap ...

Creating markers for every value in a table using Google Maps API v3

Looking for some guidance here. I have a table with multiple values that I need to process using a function. Could someone help me with a suitable loop in jQuery or JavaScript that can achieve this? I'm still learning the ropes of these languages. My ...

How can we trigger an AJAX function for every checkbox depending on its current state?

My jquery function has a peculiar behavior. Whenever I interact with the checkboxes, whether checking both, unchecking both, or checking one and unchecking the other, only the last checkbox edited triggers the method. In other words, it only 'removes& ...