Ways to analyze and contrast two ajax replies post parsing

Is there a different way to write code for making ajax calls for two pages within a single function? Also, I am looking for a method to compare the responses from both requests, specifically comparing objects y2 and y3.

function compareResponses() {
    alert('comp');

    // Getting object of ORIGINAL data
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            y = xmlhttp.responseText;
            alert(y);
            y2 = JSON.parse(y);
        }
    }

    xmlhttp.open("POST", "2.ashx", true);
    xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();

    // Getting object of another data
    if (window.XMLHttpRequest) {
        xmlhttp1 = new XMLHttpRequest();
    } else {
        xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp1.onreadystatechange = function () {
        if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
            y1 = xmlhttp1.responseText;
            //alert(y1);
            y3 = JSON.parse(y1);
        }
        xmlhttp1.open("POST", "1.ashx", true);
        xmlhttp1.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xmlhttp1.send();
    }

Answer №1

To handle situations where you are unsure of when or if both ajax calls will complete, using promises is essential.

Here is an example implementation that you can tailor to fit your specific scenario:

// Creating a promise to store future value
var futureValue = new Promise();

// Using .then() to create a new promise
var anotherFutureValue = futureValue.then();

// Defining handlers for the promise state (must be functions)
futureValue.then({

    // Function called when the promise is fulfilled
    fulfilledHandler: function() {},

    // Function called when the promise fails
    errorHandler: function() {},

    // Function called for progress events (not universally supported by all promise implementations)
    progressHandler: function() {}
});

For more detailed information on promises and deferred objects in JavaScript, you can visit this link.

Additionally, here is another useful resource from a blog that addresses similar issues as yours:

http://www.html5rocks.com/en/tutorials/es6/promises/

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

methods for converting and saving base64 image strings

I am using PHP to pull content from a table that includes a base64 image string. I would like to remove or drop the base64 string. Just so you know, the text and base64 image are coming from the Summernote WYSIWYG editor. I hope someone can assist me wit ...

What measures can I take to store data for a website user?

Check out my code on this website: If not, here is the HTML and JavaScript snippets: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> ...

The default selection in res.format is not being properly recognized

When I make a request with the accept header set as "application/json, text/javascript, */*; q=0.01", the response is always in HTML format instead of the default format specified. It seems like something is missing here. Given that the header does not spe ...

I am looking for a way to save a webpage as .html/.png format after entering text in the text box. Here is the code I have

Is it possible to download a webpage as .html/.png after inputting text in the text box? Here is my code: <div class="container"> <form> <div class="form-group"> <label for="link">Paste Website Link Below</label> ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

Newbie inquiries regarding the process of migrating a CRUD application to PhalconPHP

I have recently delved into using PhalconPHP 1.3.1 for an application related to my master's thesis. While it is still a work in progress, I am currently focusing on implementing CRUD functionality and refining the user interface. This endeavor marks ...

Determine the number of input tags within a div element by utilizing the closest property in jQuery

Sorry for the silly question, but I've been struggling to find a solution. Spent hours scratching my head. Here is my HTML structure: <div class= 'container'> <div class="someclass"> <input>some content</in ...

Angular 1 and Javascript offer a different approach than using lodash omit and the delete operator

I am facing an issue with a child component where I need to remove properties from an object. Normally, using Lodash, it should work with the following code snippet: this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSup ...

Is it possible to refrain from using the object variable name in an ng-repeat loop?

When utilizing an ng-repeat directive to loop through an array, the syntax requires ng-repeat="friend in friends". Inside the template, you can then use the interpolation operator like this {{friend.name}}. Is there a way to directly assign properties to ...

Assign a class to each offspring of a slot

I am currently in the process of setting up a component with a slot that, upon rendering, adds a specific class to each child within that slot. To simplify: <template> <div> <slot name="footerItems"></slot> </div> ...

Having trouble deciphering the code snippet in JavaScript

I'm having trouble grasping the execution of these code lines. What does `project(camera)` do and what is the significance of `screenVector` in this context? function labelBox(Ncardinal, radius, domElement) { this.screenVector = new T ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Navigating and retrieving information from JSON data

I'm working with JSON data that I have received: [{"pk": 7, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, ...

Can you create a single transition in an XState machine from each state?

Let's say I have a machine that has states from A to Z. If the machine receives the event { type: "END_OF_THE_WORLD" }, I want it to transition to state Z, regardless of its current state. Do I need to define this transition in each individual state ...

Dreamweaver seems to struggle to properly execute the identical code

There are times when I transfer javascript code from jsfiddle to Dreamweaver and find myself frustrated. Two documents with seemingly identical javascript don't function the same way. In document A, I have this code: <script> alert('test& ...

Visualize data from ajax call in tabular format

I want to display the results of an SQL query in a table using AJAX. I have written code that executes the query during the AJAX call, but when I try to display these values in a table, it shows null values on the div tag. What could be the reason for this ...

PDF Embed Whitelist

Is there a way to embed PDFs on a specific domain in a read-only format without allowing saving or downloading? While services like Scribd and Slideshare offer private options, I haven't found one that allows whitelisting for embeds on certain domains ...

Alerting Users Before Navigating Away from an Angular Page

I am looking to implement a feature in my app that will display a warning message when attempting to close the tab, exit the page, or reload it. However, I am facing an issue where the warning message is displayed but the page still exits before I can resp ...

Following the HTTP POST response, it is not possible to modify the headers once they have already been sent to the

My apologies for any typos, as I am from Brazil I checked the question mentioned below, but unfortunately it did not provide a solution to my issue ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client I have a method that I execut ...

Angular 2 - Changes in component properties not reflected in view

I'm currently delving into Angular 2 and as far as I know, interpolated items in the view are supposed to automatically update when their corresponding variable changes in the model. However, in the following code snippet, I'm not observing this ...