I need help figuring out how to pause a function that relies on an AJAX call to finish before moving on with a loop

Hi, my name is Dan and I am still a bit new to working with Javascript. I have some code where I want each div.extractedGroup to send its .html() through $.ajax and then wait for the response before moving on to the next group in the loop.

I think I may be making this more complicated than it needs to be. Can anyone help me figure out how to modify my code to achieve this?

So far, I've attempted to use a variable that changes between true and false based on the status of the ajax call (beforeSend and success), along with a setTimeout function within the success handler. I also tried wrapping the $.ajax call in a setTimeout function but haven't had any luck with either approach.

Here's the javascript code snippet:

$('#processGroup').on('click', function(event) {
event.preventDefault();
$('.extractedGroup').each(function(index, el) {
    data = $(this).html();
    request = $.ajax({
        url: 'wait.php',
        type: 'POST',
        dataType: 'json',
        data: {
            urlstoparse: data
        },
        beforeSend: function() {
            console.log('sending: ' + data);
            // Next in $.each should wait until success before processing the next group
        },
        success: function(res) {
            console.log(res);
            // Now the next group in $.each can be processed
        }
    })
        .done(function() {
            console.log("success");
        })
        .fail(function(res) {
            console.log(res);
        })
        .always(function() {
            console.log("complete");
        });
});

});

And here is the corresponding HTML:

<div id="responseResult" style="">
<div class="extractedGroup">www.pinterest.com/pin/504262489497532154/,www.pinterest.com/pin/355080751843289362/,www.pinterest.com/pin/294704369339289320/,www.pinterest.com/pin/300685712590894312/,</div>
<div class="extractedGroup">www.pinterest.com/pin/555068722796876871/,www.pinterest.com/pin/69805862945258757/,www.pinterest.com/pin/94575660900159173/,www.pinterest.com/pin/521221356846916476/,</div>
<div class="extractedGroup">www.pinterest.com/pin/197173289911047820/,www.pinterest.com/pin/413486809511385544/,www.pinterest.com/pin/355080751843289327/,www.pinterest.com/pin/53691420527287022/,</div>
<div class="extractedGroup">www.pinterest.com/pin/135882113732404986/,www.pinterest.com/pin/464222674063278838/,www.pinterest.com/pin/339318153145966062/,www.pinterest.com/pin/31103053648675435/,</div>
<div class="extractedGroup">www.pinterest.com/pin/414542340674052776/,www.pinterest.com/pin/65583738298561215/,www.pinterest.com/pin/497718196292156699/,www.pinterest.com/pin/101753272800833432/,</div>
<div class="extractedGroup">www.pinterest.com/pin/421157002626993183/,www.pinterest.com/pin/43628690112051613/,www.pinterest.com/pin/414542340674052770/,www.pinterest.com/pin/220957925438000313/,</div>
<div class="extractedGroup">www.pinterest.com/pin/462322717970755136/,</div>

If anyone has any suggestions or can point out what I might be doing wrong, your help would be greatly appreciated. Thank you!

Answer №1

After receiving guidance from jfriend00, I discovered that there is no built-in pause and wait feature in JavaScript. This led me to restructure my code as follows:

var groups = $('.extractedGroup');
var index = 0;
fetchData(index, groups);

function fetchData(index, groups) {
    var count = groups.length;
    if (index < count) {
        var request = $.ajax({
            url: 'wait.php',
            type: 'POST',
            dataType: 'json',
            data: {
                urlstoparse: groups.eq(index).html()
            },
            beforeSend: function() {
                console.log('Sending data: ' + groups.eq(index).html());
            },
            success: function(response) {
                console.log(response);
                index++;
                fetchData(index, groups);
            }
        })
        .done(function() {
            console.log("Request successful");
        })
        .fail(function(errorResponse) {
            console.log(errorResponse);
        })
        .always(function() {
            console.log("Request completed");
        });
    }
}

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

Getting the total number of child elements in a web page using Selenium web-driver with Node.js

I've been looking everywhere, but I can't seem to find the answer Here's my HTML code: <form id="search_form_homepage" > ... <div class="search__autocomplete" style="display: block;"> &l ...

Is it possible to use a hashtag and exclamation mark in URLs as a folder designation?

Can anyone guide me on how to make my pages look similar to the ones on Grooveshark, like this example: ? I'm looking for a tutorial or resources on implementing this layout using jQuery or JavaScript. ...

Top IDE for web development with HTML5, JavaScript, CSS, and JQuery compatibility, alongside user-friendly GUI design capabilities

Currently, I am working on a project that involves using the RGraph HTML5 canvas package for graph drawing. In addition to this, I also need to create a visually appealing GUI. While experimenting with Netbeans, I found that it lacks the necessary featur ...

The data is encoded in UTF-8, and some characters are being displayed incorrectly by Ajax

After extensive searching on the internet, I have not been able to find a solution that works for my specific situation. I recently converted my MySQL database from latin1 to UTF-8 and re-imported the data. All pages are set to use UTF-8 in the meta tags: ...

What benefits does sending data in JSON offer when using JQuery Ajax?

I created a form that sends the input values using ajax: var data = { id : $("#tabs").tabs('option', 'selected'), title : $('#name').val(), csrf_token : $("input[name=csrf_token]").val() }; Wh ...

Retrieve Header information when making a cross-domain AJAX request

I've been working on a way to validate image URLs by using an AJAX call to check if the image is still available. The challenge I'm facing is that the image server is on a different domain, so I included the crossDomain: true attribute in my AJAX ...

Tips for preventing alert from being shown repeatedly

The webpage features an UpdatePanel containing a grid view with checkboxes on each row, as well as a couple of buttons all belonging to the "cssUpdateEM" class. Additionally, outside the update panel is another button labeled "btnExportToExcel" also utiliz ...

Identify specific zones on an image map

While working on my website, I utilized the services of a site called to generate an image map. However, I faced an issue where there was no visual indication that the continents were clickable links. My aim is to have an icon overlaid on each continent t ...

Is it possible for jQuery to fail within an object method?

Consider this scenario: function Schedule (foo) { this.foo = foo; this.bar = function() { $.ajax({ url: '/something/', method: "GET", dataType: "JSON" }).done (function(data){ ...

Determine whether the function name in a given string matches a JavaScript or PHP

I am currently attempting to highlight code and eventually sanitize the HTML, but I am encountering an issue with my regex not matching just the function name and parameters. Regex is not my strong suit and can be quite confusing for me. Additionally, when ...

Tips for altering the contents of a state in react by toggling items in and out

Here's a challenge I'm facing: I need to display products based on the checkboxes toggles. If none of the checkboxes are toggled, the product array should be empty. If the men's checkbox is toggled, only men-related products should be shown, ...

Storing information from a CSV file in a universal variable (fast-csv/papaparse)

I am a newcomer to JavaScript and I'm attempting to parse a CSV file in the backend using node.js. I have an array of states where I intend to store data from a specific column of the CSV. The code I have written using fast-csv seems simple enough, b ...

implementing ajax with json data type

I am in the process of converting my AJAX script, which previously used text as its datatype, into JSON format. The datatype:"text" was functioning correctly, so I attempted to modify it to this updated script: Within the PHP code: header("Content-type: ...

Do you think React hooks will totally take over the role of creating class-based components?

Are React hooks poised to entirely replace class-based component creation? Will companies quickly integrate React hooks in the future? Is it worth learning React hooks? ...

Creating Nested Arrays in Angular: A Step-by-Step Guide

I'm struggling to create an array of arrays and I can't seem to figure out what's wrong with my code. Here's the snippet: c.push({ id: data[0]["id"], title:data[v]["title"], date:data[v]["date"], text:data[v]["text"], favorit: ...

JavaScript for returning a boolean output

I have been tasked with creating a webpage based on the requirements below Here is the current code that I am working with function validate() { var form = document.getElementsByTagName('form')[0]; if (form.tickets.value <= form.childr ...

Utilizing Vuejs and ElementUi to enhance slot filtering capabilities

I am facing an issue with a table where one of the columns is using slot-scope, and I am struggling to include that column data into the filters option. Code Component filter input <el-input v-model="filters[0].value" placeholder="Type t ...

Getting the most out of geometry vertices with Threejs: mastering partial transforms

In my current project, I am working with a mesh that consists of approximately 5k vertices. These vertices have been merged from multiple geometries into a flat array. Initially, I was able to modify individual vertices successfully by setting the flag `ve ...

Is there a way to duplicate various "Input fields" in JavaScript by clicking on different buttons or icons?

Project Description: I am working on a simple project that involves multiple input fields, each with its own unique "Copy icon" for copying text. However, I am facing an issue where only the first input field is being selected and copied when I click on th ...

Whenever I execute the 'ng serve' command, I encounter an issue with ineffective mark-compacts close to the heap limit, resulting in an allocation failure and a JavaScript

I'm currently using Angular 9 and Node.js 12. When I input ng serve, I encounter the following problem: C:\Users\homz\my-app>ng serve 93% after chunk asset optimization SourceMapDevToolPlugin vendor.js generate SourceMap <--- ...