Leveraging JavaScript for Triggering an Infinite Loop of 1 GET and 2 POST Requests

I don't have much experience with JavaScript, but I believe this can be achieved.

I require the script to perform 3 tasks:

  1. Make a GET request to https://example.com/test.php which will return this JSON:

    [{"user_id":"12345","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5b4a5c5b6f5b4a5c5b014c4042">[email protected]</a>","status":"active"}]

  2. Send a POST request to https://example.com/checker.php with parameters

    action=testing&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72171f131b1e4f0617010632061701065c111d1f">[email protected]</a>&status=active
    - the last two parameters are obtained from the first step. The responses to this request will vary.

  3. Send another POST request to https://example.com/verified.php with the parameter

    response=RESPONSE-FROM-STEP-2-HERE
    .

I need these 3 steps to repeat in an infinite loop as long as the visitor remains on the page (starting automatically upon page load).

It seems like in JavaScript, I can use xhttp.open for both GET and POST requests. The part I'm unsure about is how to utilize those responses in steps 2 and 3.

Answer №1

Could a solution like this be beneficial? You may also consider using await. However, this code snippet should provide you with some insights.

var getTestData = () => new Promise((resolve, reject) => {
  console.log('Requesting User IDs');
  return resolve([{"user_id":"12345","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="175075636175617067432e5559585055595840">[email protected]</a>","status":"active"}]);
});


var checkPost = (requestParams) => new Promise((resolve, reject) => {
  console.log('Requesting post check: ' + JSON.stringify(requestParams));
  return resolve({"step2response": "RandomResponse"})
});

var verifyPost = (requestParams) => new Promise((resolve, reject) => {
    console.log('Requesting post verification: ' + JSON.stringify(requestParams));
    return resolve({"step3Response": "step3Response"})
  });


getTestData().then((response)=>{
    checkPost(response).then((response)=>{
        verifyPost(response);
    })
})

Answer №2

function functionOne() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(1)
            resolve(1)
        }, 1000)
    })
}
function functionTwo() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(2)
            resolve(2)
        }, 500)
    })
}
function functionThree() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(3)
            resolve(3)
        }, 200)
    })
}

functionOne().then(data1 => {
    functionTwo().then(data2 => {
        functionThree().then(data3 => {
            console.log(data1, data2, data3)
        })
    })
})

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

Accessing Information from the Service

Here's the code snippet for my controller and service: var app = angular.module('myApp', ['ui.bootstrap']); app.service("BrandService", ['$http', function($http){ this.reloadlist = function(){ var list; $http.g ...

Convert a negative number to ASCII representation

Currently, I am attempting to extract the longitude and latitude of a user in order to utilize it in a Yahoo API query for obtaining the WOEID based on these coordinates. Subsequently, the WOEID will be passed through to a weather API call. My current pre ...

Retrieving Value from Dynamic Content Using jQuery `.keypress()` and `.delegate()`

I have encountered an issue with my code that is unable to retrieve the value of a specific ID on the .keypress function after using .delegate. The ID and other contents are generated dynamically through an AJAX call. $(document).delegate('.edit_ ...

Maintain authentication state in React using express-session

Struggling to maintain API login session in my React e-commerce app. Initially logged in successfully, but facing a challenge upon page refresh as the state resets and I appear as not logged in on the client-side. However, attempting to log in again trigge ...

Why is the "module" field used in the package.json file?

Recently, I came across certain npm packages such as vue that contain a module field in their package.json files. Interestingly, the official documentation for package.json does not mention the module field - is this some kind of convention being followed ...

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

The default choice vanishes once a non-empty option is chosen

Here is a simple example illustrating my issue: JSFiddle. Initially, I have an empty/default option, but when I select something else from the drop-down, this default option disappears. How can I keep this default option visible after making a selection? ...

“What is the process of setting a referenced object to null?”

Here is an example of the code I'm working with: ngOnInit{ let p1 : Person = {}; console.log(p1); //Object { } this.setNull<Person>(p1); console.log(p1); //Object { } } private setNull<T>(obj : T){ obj = null; } My objective is to ...

Why is jQuery not defined in Browserify?

Dealing with this manually is becoming quite a hassle! I imported bootstrap dropdown.js and at the end of the function, there's }($); Within my shim, I specified jquery as a dependency 'bootstrap': { "exports": 'bootstrap', ...

Utilize an AJAX call to fetch an array and incorporate it within your JavaScript code

Currently, I am in the process of building a live update chart feature. To access the necessary data, I created a separate file which contains the required information. Through AJAX, I sent a request from my main page to retrieve an Array and incorporate i ...

Is there a way to access the initial element of the array within this variable assignment?

When utilizing the element id 10_food_select: var id = $(sel).attr("id").split("_"); An array is generated as follows: ["10", "food", "select"] The desired outcome is to have id = 10 (or whichever value is in the first element). This can be achieved l ...

I keep getting redirected to a blank page by JS

I've created a JavaScript script that smoothly fades in the page when a user enters it and fades out when they click a link to another page. The script is working as intended, but I'm facing an issue with anchor links on the page. Whenever I clic ...

Removing children does not work properly; it only removes half of them

Why am I unable to remove all children if I delete half of them in this code? I keep getting an error saying child is not defined, even though I have declared it. Each node in my code has children spheres (nodes) and edges (lines), but when I try to dele ...

Is there a way to fetch API data selectively rather than all at once?

Hello everyone, I successfully managed to retrieve data from the Star Wars API in JSON format and display it on my application. Initially, I set the state as 'people.name' to obtain the name object. However, this also rendered unwanted data when ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Could the Redux store be used to access the state related to specific review comments?

I have a react class component that includes state variables. class NewComponent extends Component { state = { modalIsOpen: false, aa: true, bb: false, cc: false, dd: false, ee: 1, dd: [], cc: [], ff: [], gg: [], ...

Problems with Wordpress AJAX search functionality

I am currently working on implementing a search feature using AJAX to dynamically load posts. However, I am facing an issue where the results are not being displayed. This code snippet was adapted from another source and modified based on private feedback ...

Display a specific template in the detail grid of the Kendo Grid depending on certain conditions

I've been using the Kendo Grid and it's been working well for me. I have a requirement to check each row in my grid to see if it contains a specific value, and based on that, bind data using different templates. Is this feasible? Below is the cod ...

Guide on making a Key Object in Node.js

I've been struggling for the past few days to decode RSA base64 strings in a Node.js environment. Unfortunately, many of the available modules lack proper documentation, or I might be overlooking something crucial. The issue arises from the fact that ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...