An elementary vanilla JavaScript AJAX spinner

I am currently working on creating a basic function that retrieves data from an ajax call. Below is the code I have written:

var mytext = "";

function fetchData(url){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send();
    xhr.onloadend = function(e){
        return xhr.responseText;
    }
}

var mytext = fetchData('window.html');

console.log(mytext);

I am facing a challenge in retrieving the data returned by the function. It seems like there's a nested function involved and I'm having trouble figuring it out. Can anyone help me with this?

Answer №1

If you're new to JavaScript, there are several methods you can use to achieve that goal. One approach is to begin with the concept of a callback:

function fetch(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.onload = function(){
        callback(xhr);
    };
    xhr.open('GET', url);
    xhr.send();
}

fetch('/', function (data) {
  console.log(data);
});

In this demonstration, the callback serves as a function, and we supply the xhr object as an argument when invoking it.

Answer №2

One effective approach is to utilize the Promise and fetch APIs for asynchronous tasks.

function ajax(options) {
  return new Promise(function (resolve, reject) {
    fetch(options.url, {
      method: options.method,
      headers: options.headers,
      body: options.body
    }).then(function (response) {
      response.json().then(function (json) {
        resolve(json);
      }).catch(err => reject(err));
    }).catch(err => reject(err));
  });
}

You can implement it as shown below:

  const ajaxResponse = await ajax({url: '/some/api/call', method: 'get'});

If you prefer not to use async functions, you can handle it in the following manner:

ajax({url: '/some/api/call', method: 'get'}).then(data => {
  // process data here
});

Clarification:

JavaScript operates on a single thread, causing operations to block execution. By utilizing the asynchronous capabilities of the XMLHttpRequest and fetch APIs, code can proceed while waiting for Ajax responses.

In your scenario, no response is obtained because the function continues executing before the Ajax call completes. Managing this asynchronous task with Promises allows JavaScript to handle the response once available.

The use of async functions simplifies reading async code by encapsulating the body within a Promise. Additionally, using await enables waiting for the completion of a preceding Promise.

Therefore, code written as:

const call = await ajax({ ... });
console.log(call);

is equivalent to:

ajax({ ... }).then(call => {
  console.log(call);
});

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

Create a search function utilizing React and TypeScript for enhanced filtering capabilities

Hey there! I could use some assistance with creating a search filter. My goal is to have an input field where I can type in some text, and then have the ul list filter out items that contain the same letters. interface ICrypto { id: s ...

Tips for creating a non-blocking sleep function in JavaScript/jQuery

What is the best way to create a non-blocking sleep function in JavaScript or jQuery? ...

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

Angular 2: Copious Errors in the Mix

Working on building an Ionic 2 app using the Angular 2 framework, I encountered a problem when trying to display a map on a page. I found a helpful guide at the following link: While the map was working fine, I started getting an error in my console: You ...

Formatting decimals with dots in Angular using the decimal pipe

When using the Angular(4) decimal pipe, I noticed that dots are shown with numbers that have more than 4 digits. However, when the number has exactly 4 digits, the dot is not displayed. For example: <td>USD {{amount| number: '1.2-2'}} < ...

The JavaScript function for clearing an asp.net textbox is not functioning properly

I am working on an ASP.net project and have encountered an issue with two textboxes. When one textbox is clicked on, I want the other one to clear. Below is the code I have for the textboxes: <asp:TextBox runat="server" ID="box1" onfocus="clearBox2()" ...

Extend the shelf life of cookies by utilizing AngularJS

I am currently implementing angularjs cookies in my project. https://docs.angularjs.org/api/ngCookies/service/$cookies Despite being aware of the security risks, I am using $cookies to store user credentials. I aim for the user to log in once and have th ...

Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below). I am in need of a RegEx that can transform JSON into an array containing all characters such as ...

The @input function in Vue.js is currently only triggered after the user has focused out, but I need it to be called while the user is

When working with @input on an input field in Vue.js, I am facing an issue where the assigned function is only called after the user has stopped typing and the focus is out of the input field. Essentially, it is triggered on onFocusout. What I actually wan ...

The value of the cookie is not set (version 2.0.6 of react-cookie)

I am encountering an issue with implementing react cookies version 2. I am using webpack-dev-server for testing. Below is the console log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is unde ...

Obtain Page Parameters within a Nested Next.js Layout using App Router

My Next.js App Router has a nested dynamic page structure using catchall routes configured like this: app/stay/ |__[...category] | |__page.js |__[uid] | |__page.js |__layout.js Within the 'layout.js' file, there is a con ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Updating a Vue component upon resolution of a promise and effectively passing props to its nested children

I have a scenario where I need to pass data from a parent component to a child component as props. The parent component's data is fetched via an ajax call. I have tried a couple of solutions, but they are not working as expected. Can you help me iden ...

Deactivate user connection using Jquery onunload

I need help figuring out how to disconnect a user when the "unload" event is triggered. $(window).bind('unload', function() { $.ajax({ url: "deconnexionUser.php", async: false }); }); The current solution works, but I want to ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

What is the most secure method for storing a password persistently on the client side between pages?

Is there a secure method to authenticate login credentials via AJAX on a Squarespace website without using PHP? I am currently trying to password protect certain pages on my website by validating login information stored in an external PHP script and datab ...

Loading identical items using jQuery Ajax

I have a situation where an ajax request is returning multiple URLs which I am using to create images like: <img URL="1" /> <img URL="1" /> <img URL="2" /> <img URL="1" /> <img URL="3" /> <img URL="2" /> and so on... ...

Leveraging JQuery within React applications

Within my React functional component, I have utilized JQuery to target nodes with a particular tag and class similar to CSS. However, I am curious if there is an alternative way in React without resorting to traditional JavaScript methods. For instance, if ...

Having difficulty in transferring an array index as props to a different component

My goal is to create an app where users can add cards to an array and then switch the positions of specific cards with the one on their left or right. I have written a function to handle switching cards, but I am facing issues debugging it as the index of ...

Using string.startsWith() with Wildcards or Regular Expressions

Currently in the process of refactoring code that relies on string.startsWith() in JavaScript. The documentation here does not mention the use of wildcards or Regular Expressions with this method. Is there an alternative approach I can take? ...