Result being returned from XMLHTTPRequest function

I've been experimenting with an XMLHttpRequest and managed to get the basic code functioning properly. However, I'm struggling to create a function that will return a boolean variable indicating whether it has worked or not:

var xhr = new XMLHttpRequest();
var success = false;

xhr.open('HEAD', sourceurl, true);
xhr.send();
xhr.onreadystatechange=function(){
    if (xhr.readyState === 4){   //if complete
        if(xhr.status === 200){  //check if "OK" (200)
            //success
            console.log('success');
            return true;

        } else {
            // fail
            console.log('fail' );
            return false;

        }
    } 
};

Although the console logs display the correct messages, when attempting to wrap this code within a function, no feedback is provided on its success or failure.

I would greatly appreciate any assistance with this!

EDIT: This is not a duplicate issue, as I am unable to utilize jQuery in my case and the existing solutions do not apply to my situation.

Answer №1

When using the onreadystatechange function, it operates asynchronously and does not return to anything. To manage this, consider utilizing callback functions within an outer function. Essentially, you would call a function that will process the result of the HTTP request.

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

Issue with inheritance from Angular ModalCtrl to ServiceCtrl not functioning as expected

I've been working on linking models to services in order to update global models throughout my app, but it doesn't seem to be functioning as expected. Recently, I delved into AngularJS and I suspect that I may have misunderstood my code. From wh ...

How can one use jQuery to target elements that have names that are in an array format?

Is there a way to retrieve the values of these elements and send them as an array using ajax? <input type="checkbox" name="Broadcast[m]"/> Members <input type="checkbox" name="Broadcast[i]"/> IATA agencies <input type="checkbox" name="Bro ...

Having trouble getting jQuery click event to work with Express for loading a Handlebars page

My jQuery on click function is not working properly in conjunction with Express to route to a handlebars page and display the passed information. I have attempted different solutions such as changing the HTTP method from GET to POST, not using handlebars ...

Using Laravel - Executing a controller method through AJAX with jQuery

I have multiple controller functions that are currently functional, but I would like to transition some of them to be triggered via AJAX for better usability. Below is the jQuery code I am using: $.ajax({ method: 'GET', url: $(t ...

Submitting form data triggers an AJAX request that retrieves and displays the desired content within a

When it comes to opening search results in a specific form on a webpage using Ajax, many developers may face certain challenges. Here is an example of how it can be implemented: <form id="searchForm" method="GET" > <INPUT TYPE="text" N ...

Production environment experiencing issues with Stripe functionality due to element remaining mounted

When making a payment in development mode, everything goes smoothly. However, when I switch to production, I encounter the following error message: v3:1 Uncaught (in promise) IntegrationError: We could not retrieve data from the specified Element. Please e ...

Using a JSON key as a parameter in a function

Would it be achievable to specify the key of an object as a function parameter? For instance, if I were to develop a filter function that could sort multiple map markers by marker.element.country or marker.element.population? This approach would allow me ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...

Audio playback is being disrupted by simultaneous ajax requests

Whenever my chatbot responds, I want to play an audio file. I have set up an API where the audio file is stored and called using AJAX on each response. It works fine with a single response, but when there are multiple responses, the audio gets overlapped - ...

The ng-token-auth plugin in combination with the ui-router resolver leads to a blank

I have been referring to the ng-token-auth documentation here in an attempt to implement a resolver for authentication using the validateUser function. However, when I add the code snippet provided in the documentation to my app.js file under the "home" st ...

When attempting to display an identical image on two distinct canvas elements in Angular 6

I am facing an issue where the image is only rendered on the second canvas instead of both canvases. I need assistance in finding a solution to render the same image on both canvases. Below is a screenshot demonstrating that the image is currently only re ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...

Invoke a component and initiate a click event from within the App.vue component

Within my template, there is a click event: <span v-on:click="showGalery()"> This event is linked to the following method: export default { name: 'osaka', data: function () { return { galery: false, } }, methods: { ...

Using JavaScript and HTML, create a click event that triggers a drop-down text

Can anyone help me with creating a dropdown feature using JavaScript, HTML, and CSS? I want to be able to click on the name of a project and have information about that project show up. Any suggestions on how I can achieve this? Thanks in advance! ...

JavaScript multi-click navigation menu

I'm relatively new to JavaScript and I've been struggling with using multiple onClick attributes. While I have some code that works, I feel like there might be a simpler and cleaner solution to my problem. What I'm trying to achieve is a na ...

Displaying validation feedback upon submitting a form using AJAX in ASP.NET MVC

In my ASP.Net MVC project, I am trying to display a loading image using jQuery when a form is submitted and the next action method is called. The reason for this is that after logging in, there is a delay in loading the next page. I have experimented with ...

Mysterious dual invocation of setState function in React

My component is designed to display a list of todos like: const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, ]; ...

In Angular, the ng-click directive that assigns the value of tab to $index does not seem to be functioning properly

I encountered an issue within my app <li ng-repeat="name in tabs track by $index" ng-class="{selected: tab==$index}" ng-click="tab = $index">{{name}}</li> After clicking on each item, the selected class remains enabled and switching to anothe ...