Use AJAX to attach an HTML document to an element

I have been working on this code with information from different online sources, but I'm stuck on the final step.

function loadajax (event) {
    event.preventDefault();
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange  = function(){ 
        if(xhr.readyState  == 4){
            if(xhr.status  == 200) 
                document.ajax.dyn="Received:"  + xhr.responseText; 
            else
                document.ajax.dyn="Error code " + xhr.status;
        }
    }; 

    xhr.open('GET', this.href, true);
    var content = document.getElementsByTagName('article')[0];

    content.innerHTML = xhr.responseText;
}

The code seems to be functioning well until it comes to adding content to my page. When I use

content.innerHTML = xhr.responseText;
, nothing is returned. I am receiving a basic HTML file - how can I display it on my page? What mistake am I making?

I appreciate any assistance you can provide!

Answer №1

Remember, ajax calls are asynchronous in nature. To ensure it functions properly, make sure to relocate the line

content.innerHTML = xhr.responseText;
within the onreadystatechange function as shown below:

function handleAjaxResponse(event) {
    event.preventDefault();
    var xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange  = function() { 
        if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                document.ajax.dyn = "Received: " + xhr.responseText;
                content.innerHTML = xhr.responseText;
            } else {
                document.ajax.dyn = "Error code " + xhr.status;
            }
        }
    }; 

    xhr.open('GET', this.href, true);
    var content = document.getElementsByTagName('article')[0];
}

Answer №2

Ensure that your content.innerHTML is placed within the status 200 condition block.

Do not assign a value to content before it has been retrieved by the ajax request from the server.

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

Tips for personalizing the error message displayed on Webpack's overlay

Is there a way to personalize the error overlay output message in order to hide any references to loaders, as shown in this image: https://i.sstatic.net/ESFVc.png Any suggestions on how to remove the line similar to the one above from the overlay output? ...

Utilizing React Hooks and Firebase Firestore onSnapshot: A guide to implementing a firestore listener effectively in a React application

SITUATION Picture a scenario where you have a screen with a database listener established within a useEffect hook. The main goal of this listener is to update a counter on your screen based on changes in the database: (Utilizing the useEffect hook without ...

Unusual activity discovered when using JavaScript addClass and removeClass methods

While experimenting with animate.css, I created a custom Javascript function to initiate animation events. This simple function, triggered by an onClick event on a button, is only three (or four) lines long, but encounters a perplexing error. The anim fu ...

Is there a way to incorporate the req.setHeaders method with the res.redirect method in the same app.get function?

var express = require('express'); var app = express(); var PORT = process.env.PORT; app.get('/', function(req, res){ res.json('To search for images, enter your query parameters like this: https://api.cognitive.microsoft.com/bi ...

Tips for displaying a section of an image similar to the style seen on the website 9gag.com

Is there a way to display only a portion of an image (in this case, to hide the watermark) similar to how it is done on 9gag.com? I attempted to use clip in CSS, but it requires the image to be positioned absolutely, which is not ideal for me. Are there a ...

Attempting to rename the "like" button in Django Ajax, however encountering difficulties

My button is currently functioning, but it's embedded within a Django for loop. I want to move the JavaScript logic to a separate file, but before that, I need to rename it appropriately. Check out this excerpt from my code: {% for post in posts %} ...

Define class attributes within a TypeScript callback function

I have encountered an issue with my method involving a subscription to an event from a pub sub messaging service. The problem arises when I attempt to define a class property within the callback function, only to find that the property returns as undefin ...

Having trouble implementing uppercase text in Bootstrap editable modules

Recently, I implemented the bootstrap editable function in my application and it was functioning perfectly. However, I am now looking to have the editable text always display in uppercase format. Unfortunately, I am unsure of how to achieve this. Any sugge ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

an alternative method to function stacking in the realm of Javascript

I am searching for an improved approach to a common JavaScript task. How can I achieve this: // global namespace var PlexLib = PlexLib || {}; PlexLib = { FileName : "", ShowName : "", AddFileSelector_result : function (data,status,xhr) { ...

Guide to importing an ES module in Node.js without specifying a file extension

There's a common belief that when importing ES modules, you should always include a file extension. However, I stumbled upon certain Node projects that seem to import ES modules without an extension, as seen in this particular example. This has left ...

Ensure that the input field only accepts numerical values

Can anyone help me with an issue I'm facing in my plunker? I have an input text field that I want to accept only numbers. Despite trying normal AngularJS form validation, the event is not firing up. Has anyone encountered a similar problem or can prov ...

After an AJAX request is completed, the event.keyCode is not returning the key codes for the up and

I have a function that uses AJAX to autocomplete a text field. The results are added to a specific div element. I am trying to implement the functionality where users can navigate through the results using the up and down arrow keys. However, I am encoun ...

CSS / JavaScript Navigation Menu overshadowing Flash content in Firefox

On my website, I have a drop-down menu that was created using CSS and JavaScript. This menu drops down over a Flash animation. Interestingly, in Internet Explorer 6 and 7, the drop-down menus successfully appear over the Flash animation. However, in Mozill ...

What steps can be taken to resolve the dependency problem with npm installation?

Attempting to incorporate npm install react-material-ui-carousel --save into my react project has presented a challenge. Upon installation, I encountered a dependency tree issue. Even after deleting the lock and npm modules files, followed by running npm ...

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 ...

Ways to repair a website iframe malfunction

Whenever I visit this specific URL : (note: using an Ad-blocker is recommended) The link to the webpage loads properly, with no issues. However, attempting to load the same page through an iframe in my HTML code triggers an error: Here is my HTML code : ...

Pressing JavaScript buttons to trigger another button

I am looking to develop a script that generates a button which then creates another button. The subsequent button will be assigned an id attribute by incrementing from 1 to infinity. This feature should apply to all buttons (original button and the newly ...

What is the method to adjust the duration of a transition for an element using JavaScript?

If I have an element with the following CSS properties: .element{ /* some css properties */ transition-duration:1.5s; transition-delay:.1s; } When triggering it by hovering over another element, I want it to enter with the specified duration and d ...