Using a for-each loop to wait for the completion of an Ajax process

for (var i = 0; i < theTagNames.length; i++) {
    var url = baseURL + "?" +
        "jsoncallback=?" +
        "&method=flickr.photosets.getPhotos" +
        "&format=json" +
        "&api_key=" + api +
        "&photoset_id=" + theTagNames[i].id;
    tagID = theTagNames[i].id;
    console.log('for: ' + i)

    $.getJSON(url, {}, function (data) {
        tmpSetName = theTagNames[tmpi].title._content;
        category = theTagNames[tmpi].description._content;
        tmpi += 1;
        keepTrack = 0;

        $.each(data.photoset.photo, function (z, item) {
            if (i == limit) return false;
            console.log('each: ' + z)

            var thumbURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_s.jpg';
            var largeURL = thumbURL.replace('_s.jpg', '_b.jpg');

            keepTrack = z

            if (keepTrack == 0) {
                $('#flickrImages').append('<div style="float: left;background-color: #102C53; color: #fff; width: 690px; text-align:left; font-weight: bold; padding: 3px;" id="title' + tmpSetName + '">' + tmpSetName +
                    '<span id="span' + tmpSetName.replace(/ /g, '_') + '" style="cursor: pointer; float: right;" onclick="clickedTitle(this);">' +
                    ' [Start Slideshow]' +
                    '</span>' +
                    '</div>');
            }

            if (keepTrack <= (displayLimit - 1)) {
                $('#flickrImages').append('<span align="left" style="float: left;" id="imgDiv">' +
                    '<a style="outline: none;" rel="' + tmpSetName.replace(/ /g, '_') + '" title="" href="' + largeURL + '" id="imgLink' + tmpSetName.replace(/ /g, '_') + i + '">' +
                    '<img id="img' + i + '" src="' + thumbURL + '" style="border: 1px solid #102C53; margin: 3px;" alt="' + tmpSetName + '" />' +
                    '</a>' +
                    '</span>');
            } else if (keepTrack == (displayLimit + 1)) {
                showMoreImages = true;
            } else {
                $('#flickrImages').append('<span align="left" style="float: left; display: none; visibility: hidden;" id="hidden' + tmpSetName.replace(/ /g, '_') + '">' +
                    '<a style="outline: none;" rel="' + tmpSetName.replace(/ /g, '_') + '" title="" href="' + largeURL + '" id="imgLink' + tmpSetName.replace(/ /g, '_') + i + '">' +
                    '<img id="img' + i + '" src="' + thumbURL + '" style="border: 1px solid #102C53; margin: 3px;" alt="' + tmpSetName + '" />' +
                    '</a>' +
                    '</span>');
            }
        });
    });
}
}

The code above is functional, but it has a flaw that causes images to appear out of order when the page is refreshed. It seems that the script is processing too quickly, resulting in incorrect pairings of image headings and content.

Sometimes, the images are displayed correctly, but often they are not in the correct order.

Is there a way to pause the execution of for (var i = 0; i < theTagNames.length; i++) { until all images within $.each have been collected and appended to the flickrImages div?

Answer №1

To ensure that the value of i remains consistent in an asynchronous situation, it is recommended to place the entire

$.getJSON(url, {}, function (data) { ...
inside a separate function outside the for loop and then pass in i.

Furthermore, using a different variable name for the index parameter of your $.each function can help improve code clarity.

Therefore, the updated code structure would resemble the following:

for (var i = 0; i < theTagNames.length; i++) {
    // operations
    fetchFlickrData(data, i);
}

function fetchFlickrData(data, i){
    $.getJSON(url, {}, function (data) {
        //operations
    }
}

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

How to pass PHP echo to success parameter in jQuery AJAX commands

As I delved into learning ajax, I came across some code snippets online but struggled with passing values from PHP. Here is the snippet from my email.php file: $conn = mysqli_connect($servername, $username, $password, $db); $email = $_POST['email&apo ...

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Navigate back to the previous page upon form submission to a PHP file, with a div dynamically populated with targeted content

I'm facing a logic dilemma: I have a webpage with a div called #content, where I've embedded another page containing a form for submitting data* (there are other pages loaded into #content as well, but they are not active at the same time, one o ...

Using JavaScript, enter the value into the input field and then redirect the

I'm encountering a minor issue with my contact form and jQuery redirection based on input fields. Everything was working smoothly until I attempted to integrate the redirection into the form validation code. Redirection snippet: $("#signup").submit ...

deactivate a vessel, causing all of its contents to be rendered inactive

Hi there, I am in search of a container that has the ability to disable all elements within it, not just inputs but also images and other elements without the disabled property. I do not want to hide the container, but rather disable it. Do you know if suc ...

Executing ajax request with a generic class

Attempting a new method for calling an MVC controller through Ajax using a generic approach. For example, consider the following: url: '/ChartReporting/GetChartReportingResults' data: JSON.stringify({Type: 'Pie', some more properties.. ...

Using Python to retrieve .json data from Splunk

Here's the issue I'm facing: I uploaded a json file to splunk for my university project, and now I need to use it in python as a dataframe object. Code: import urllib3 import requests import json import pandas as pd urllib3.disable_warnings(u ...

Troubleshooting Issue: ASP.NET UpdatePanel Not Responding to jQuery

I am having difficulties invoking jQuery functions within an "asp:UpdatePanel". Despite the code provided below, my attempts to add a class to the div element ".popup-body" are unsuccessful. Interestingly, the "alert();" function works without any issues. ...

Storing Multidimensional Arrays in a Database Using Sequelize

My JSON file contains nested arrays with varying lengths, meaning each object has an array with a different number of objects. { "count": 200, "objects": [ { "id": "FIRST", "b": "two", ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...

What is the process for selecting and accessing a DOM element?

Looking to utilize jQuery selector for accessing deep within the DOM. HTML <table> ...more here <tr> <td class="foo bar clickable"> <div> <div class="number">111</div> //Trying to retrieve "111" ...

Enhancing Highcharts bar chart tool tip to display dynamic data

I am currently utilizing highcharts.js for my project. The goal is to customize the tooltip. I have created a Java method that returns output in JSON format like this: syList: [{ "value1": "Some Area", "value2": "1", "agrAcronym": "AB ...

Is it feasible to utilize the .fadeTo() function in jQuery multiple times?

I need some help with writing a script that will display a warning message in a div tag every time a specific button is pressed. I chose to use the fadeTo method because my div tag is within a table and I want to avoid it collapsing. However, I'm noti ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...

Guide on grabbing characters/words typed next to # or @ within a div element

Within a div element, I have enabled the contenteditable property. My goal is to capture any text input by the user after typing '#' or '@' until the spacebar key is pressed. This functionality will allow me to fetch suggestions from a ...

The JSON.Unmarshal function is not correctly decoding into the inner interface{} as expected

I am in the process of creating a new wrapper for the Telegram Bot API in Golang, as a way to enhance my learning experience. Within this project, I have defined a Response struct: type Response struct { Ok bool `json:"ok"` ErrorCode int64 `json:"erro ...

Execute JavaScript AJAX Request On Page Load

I am facing an issue with creating an onload event in which an AJAX function needs to be called and passed a value. The challenge lies in the fact that I have both my header and footer split into sections via PHP, therefore I cannot place it on the body ta ...

Discovering with jQuery

Can we actually change the background color of '.preview-inner' to yellow from "#change_color"? <div id = "form-container> <input class="color-picker" id="change_color" type="text"> <div class="replacer"> <div class= ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Utilizing jQuery to send an Ajax GET request for a JSON file

Recently I have begun delving into the world of jQuery and Ajax, attempting to utilize both technologies to retrieve a JSON FILE. Below is the structure of the file: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": f ...