Retrieve server responses in Javascript following a request initiated by Javascript

Can someone help me with my JavaScript function that sends a request to an aspx page? Here is the code:

 var xhr = ("XMLHttpRequest" in window) ? new XMLHttpRequest() : new ActiveXObject("Msxml3.XMLHTTP");
    xhr.open("GET", 'http://www.example.net/abc.aspx', true);
    xhr.send(""); 

After sending this request, I need to receive a response from the page and handle it on the client side. Can anyone guide me on how to accomplish this?

Answer №1

To receive the response asynchronously from XMLHttpRequest, you need to set the onreadystatechange property to a callback function in the open() method with the third parameter as true. This callback function will be executed once the response is ready in the browser:

xhr.open("GET", 'http://www.example.net/abc.aspx', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4)  { 
    var serverResponse = xhr.responseText;
  }
};
xhr.send(null);

For further information on this topic, feel free to refer to the following article:

  • AJAX Patterns: XMLHttpRequest Call

Answer №2

To ensure cross-browser functionality, a bit more effort is required. However, once accomplished, you will have a reusable function that does not rely on any external library.

// Here is how easy it is to make a call
ajax( "http://www.example.net/abc.aspx", function( data ){
    // Process the server's response here
    alert(data);
});

///////////////////////////////////////////////////////////////////////////////

function getXmlHttpObject() {
    var xmlHttp;
    try {
        // For Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // For Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!xmlHttp) {
        alert("Your browser does not support AJAX!");
    }
    return xmlHttp;
}


function ajax(url, onSuccess, onError) {

    var xmlHttp = getXmlHttpObject();

    xmlHttp.onreadystatechange = function() {
      if (this.readyState === 4) {

            // Execute onSuccess if status is 200 and it is a function
            if (this.status === 200 && typeof onSuccess == 'function') {
                onSuccess(this.responseText);
            }

            // Execute onError if it is a function
            else if(typeof onError == 'function') {
                onError();
            }

        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return xmlHttp;
}​

Answer №3

To receive the response, you will need to include a readystatechange event handler function. This function will be triggered once the response is available for reading:

xhr.onreadystatechange = function() {
    if (this.readyState !== 4) return; // not ready yet
    if (this.status === 200) { // HTTP 200 OK
        alert(this.responseText);
    } else {
        // handle server errors here
    }
};
xhr.open('GET', 'http://www.example.net/abc.aspx', true);
xhr.send();

Additionally:

("XMLHttpRequest" in window)

While using in is typically a good way to check for property existence, it's not ideal in this case.

The issue arises with IE7+ where, even if the ‘native XMLHttpRequest’ option is disabled, XMLHttpRequest remains as a property in window but with a value of null. In such cases, it's recommended to use a simple truth test for better compatibility and fallback options:

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHttp');

Answer №4

If jQuery is your preference, you can utilize the following code snippet for making ajax calls:

  const requestData = { item1: "Information", item2: "Details"};

  const urlRequest = "http://www.samplewebsite.com/data.php";

  $.ajax({
    type: "POST",
    url: urlRequest,
    data: requestData,
  })
    .done(function (response, status, xhr) {
      // Perform operations
    })
    .fail(function (response, status, xhr) {
      alert("Oops! Unable to connect to server at the moment :(");
    })
    .always(function (response, status, xhr) {});

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

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Encountering a "focus" error with React-Native-Phone-Input library, where the property is null

For my project, I decided to incorporate the react-native-phone-input library. Everything was going smoothly until I encountered an issue with their focus function. Initially, it worked perfectly fine, but subsequently, when I attempted to input a phone nu ...

Unable to dial phone numbers when clicking 'Click to call' link on Android devices

Within my Cordova android application, I have a link set up like this: <a href = "tel:011123456789">Click to Call</a> While this click-to-call functionality works smoothly in IOS, it seems to be hindered in Android by an issue such as: 11- ...

Attempting to retrieve an array within a Mustache JavaScript template

I'm attempting to retrieve data from a mustache array using this.location.coordinates.0: <div class="block"> <label>Location (longitude/latitude):</label> {{location.coordinates.0}}/{{location.coordinates.1}} </d ...

Unable to convert imported JSON file into an array

Looking to create an array from a file, the following code snippet serves the purpose: 'use strict'; const fs = require('fs'); let results = []; fs.readFile('myfile.json', (err, data) => { if (err) throw err; res ...

What is the best way to store and retrieve all the variable data from a .js file on a user's device?

I'm looking for a way to save and load multiple variables in JavaScript that determine a "save" state. These variables are stored in a file named "variables.js." Is there a simple method to easily save all the information in this file and then load i ...

Discovering if an ID already exists in a Firebase real-time database with React.js

https://i.sstatic.net/i1QVd.png Currently, I am engaged in a React inventory project. In order to avoid duplication when pushing data into the progress.json file, I need to ensure that the data is not already present by checking for the unique id associat ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Improve the efficiency of loading and utilizing data from the petition using $http

In my Ionic framework application, I am dealing with a large amount of data - around 10,000 records initially, with an additional 200 records being added every week. However, the loading time for this information is becoming a concern as certain sections o ...

NextJS rewrite retains URL search parameters

After a user clicks the button to access my website through email authentication, I need to verify if they have tokens. When they are redirected from Gmail to my page, there is a search parameter in the form of verification_token=**. If the user has alread ...

javascript execute while load

I'm having trouble initializing inputs with maps api autocomplete based on the number of inputs retrieved from the database. I'm trying to run a simple JavaScript function within a while loop, but it's not working as expected. Although the ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

The background color of the Bootstrap 5 navbar remains static and does not transition when scrolling

I'm currently developing an Angular application using Bootstrap 5. One of the features I am working on is a transparent navbar that should change to a dark color when the page is scrolled. However, I seem to be encountering an issue where the navbar r ...

Working with nested JSON data in Node.js independently

Here is an example of a JSON structure: { "username": { "A1": { "L1": "usernameL1", "V1": "usernameV1" }, "A2": { "L2": "usernameL2", "V2": "usernameV2" } }, "pass ...

An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined fu ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

Challenges with Material UI and Styled Components Overriding

When utilizing Material UI's Typography, everything was functioning perfectly: <Typography component="h1" variant="h5"> Sign in </Typography> However, I decided to transition to styled-components and attempted the foll ...