Javascript function does not return a value

Having trouble retrieving a string value from this function:

function loadPage(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, true);
    xhttp.send();

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            //var html = xhttp.responseText
            var html = document.documentElement.outerHTML;
            return html
        }
    }
}

console.log(loadPage("http://stops.lt/vilnius/#trol/2/a-b"))

Although console.log(html) prints the correct results within the xhttp.onreadystatechange, I'm struggling to understand how to return loadPage(url). I've tried both return xhttp.onreadystatechange and

return xhttp.onreadystatechange()
, but neither of them seem to work.

Answer №1

The function loadPage has been updated to include an asynchronous feature, requiring the use of a callback function or Promise:

const retrievePage = (url, cb) => {
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.send();

    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === 200) {
            //const htmlContent = request.responseText;
            const htmlContent = document.documentElement.outerHTML;
            cb(htmlContent);
        }
    }
}
retrievePage("http://example.com/page", (html) => {
    console.log(html);
});

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

Optimal code structuring for a javascript plugin

Hey there, I came across some intriguing posts on this topic, but I believe it's a very personal question that requires a tailored answer. So, I'm reaching out to ask you: what is the most effective way to organize my code for a JavaScript plugin ...

Is it possible to adjust the height of the apprequests dialog?

I attempted the following code snippet: FB.UIServer.Methods["apprequests"].size = {width:600,height:320}; The width successfully adjusts, however, the height is restricted to a fixed value. Appreciate any help! ...

Tips for preventing redirection to the login page upon page refresh in a next.js application

I've been diving into user authentication and authorization using next.js. I managed to create a custom authguard hook that works well, except for one issue - when a user logs in and refreshes the page, they are redirected back to the login page. Aut ...

Using jQuery to prepend elements and then fade them in

Whenever a user makes a post, it should be displayed at the top of the feed page with a nice fadeIn effect. However, my current script seems to hide all the updates before showing them again. I only want this effect to apply to the latest status. What cou ...

The malfunctioning of dynamic className styling in React applications

Can someone assist me with an issue I'm having while coding along to a tutorial video? The dynamic styling of className isn't working as expected. I noticed that it works fine on regular CSS, but when using styled-components, I am not getting the ...

Merging object keys and values from JSON arrays based on their keys, using JavaScript

Is there a way to merge object keys' values from JSON arrays based on their key? json1 = [ {key:'xyz', value:['a','b']}, {key:'pqrs', value:['x','y']} ] json2 = ...

When the user clicks, position a div directly below another div

Can anyone help me figure out how to center a div underneath another one when a specific div is clicked using programming? I've tried multiple solutions but nothing seems to work. Below is the code snippet that I have written. You can also check out t ...

Retrieving object key value from an array using Underscore.js

Hey there, I'm facing a challenge where I need to extract the values of wave1 and wave2 from an array using underscore.js. array = [{"id":1,"name":"Monoprix", "pdv":16,"graph":[{"wave1":22,"wave2":11}]} ; I attempted the following: $scope.wave1 = a ...

Rails Unobtrusive JavaScript (UJS) does not seem to be connecting the data-remote

Version of Rails: 3.2.1 Version of Ruby: 1.9.3p125 Browser Used: Chrome 18.0.1025.162 Developers Operating System: Mac OS/X Lion Server's Operating System: CentOS 5 I am attempting to utilize :remote in my link_to call in order to request HTML co ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

`quill-emoji : The emoji fails to render properly`

Attempting to integrate quill-emoji with ngx-quill, but struggling to display the emojis in the pop-up or once inserted. It seems like a CSS inclusion may be missing (not mentioned in the documentation on GitHub). Check out this StackBlitz showcasing the ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

Storing data in the database using Laravel and Ajax

This is the content of my index.php file: <div class="container"> <h1>Enjoy a Cup of Coffee Today</h1> <hr> <h2>Coffee Orders</h2> <ul id="orders"> <p><li class="highlight"></ ...

How can scriptlets be used to dynamically create a properly functioning model?

Having trouble populating data into the modal form. I've tried placing the modal code inside a for-each loop, and while it successfully displays the details in the modal, the functionality of the close button and clicking outside the modal to close it ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

What causes the elements in my JSON file to load in a seemingly random order when clicked on?

Scenario in a simplified test case: I created a slider with 2 slides, each containing a 'video' link. When the link is clicked, a <div> is displayed with an array of objects (images). Issue at hand: Upon clicking the 'video' link ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

"AngularJS View Source Page: Unveiling the Power of Dynamic Metatags

Hey there, I have a requirement where I need to update the metatags content dynamically. I successfully updated the content in INSPECT ELEMENT, but I am unable to see the updated content in the view source page. I want to update the metatags in the view ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...