Optimizing JS functionality for documents loaded via AJAX without using any external libraries

My JavaScript code is not working when the document is loaded via AJAX.

Here's the AJAX code I'm using:

var xhr;

xhr = new XMLHttpRequest();

function xhrDocOpen(doc, placeID) {
    xhr.onreadystatechange=function(){
        if(xhr.readyState === 4 && xhr.status === 200){
            document.getElementById(placeID).innerHTML = xhr.responseText;
        }
    }
    xhr.open('GET', doc, true);
    xhr.send();
}

As you can see, this is pure JavaScript code and does not use jQuery. Some solutions I found online were using jQuery, but I prefer to solve the problem with only native JavaScript.

How can I accomplish that?

Answer №1

Not all browsers function the same way when using pure JavaScript. This is one of the reasons jQuery exists - to implement functions that work differently depending on the browser being used.

When creating an XMLHttpRequest (xhr) object to load a document, there are multiple approaches based on the browser:

xhr = new XMLHttpRequest()

xhr = new window.ActiveXObject("Microsoft.XMLDOM")

xhr = document.implementation.createDocument("", "", null);

It's important to consider these differences, especially if you need to load the file asynchronously or synchronously.

If you're looking to load a file from disk rather than a web server, keep in mind that there are at least two methods for handling ajax requests, varying by browser. If you don't want to deal with these complexities and continually adapt to new browser versions, it's advisable to use jQuery.

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

Difficulty sending a parameter to the onClick function of a React Button

I'm struggling with passing parameters to my callback function when clicking a material-ui button. Unfortunately, the following approach is not yielding the expected results. const fetchData = async (param) => { } <Button onClick={fetchData(&a ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making? This is the HTML file: <head> <script type = "text/javascript"> function ajax_get_json() { var h ...

The instance of the Javascript Object Prototype losing its reference

I'm currently developing a small Javascript Object that will attach click listeners to specific elements, triggering an AJAX call to a PHP function. Everything is functioning as expected, but I want to execute a function once the AJAX response is rece ...

What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server. The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I ...

Are there any JavaScript tools for adding notes to text?

I’ve searched online but haven’t had any luck. Is there a tool available that allows for annotating text selections, even those that overlap? The scenario is that multiple users will be given the same text and need to annotate different selections in ...

Is it possible to incorporate variables when utilizing NG-CLASS for an active link in Angular?

I am trying to create a navigation using a loop in my code. However, I keep encountering an error which says that it won't evaluate as a string. The idea is to loop through the $scope.navigation and use it to generate the navigation dynamically instea ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

Is there a way to retrieve the previous value in an input field's onChange event?

I am working with inputs in a React project and have assigned a function to their onChange event. While I have been able to access the current value, I am now looking for a way to retrieve the previous value as well. The reason I need the old value is bec ...

loop through an array and use splice to select items and modify the array

My current issue involves working with a pixabay array. Although I successfully retrieved the data from my array, it contains 20 random pictures when I only need 3 to be displayed on my website. I attempted to use a slice array for this purpose, but unfor ...

Looping through multiple ajax requests to track the most recent responses

Run a loop with the most recent response obtained from the previous ajax call. The current code is continuously displaying the same response. PHP outputs data in text format. Currently, the code fetches response text from the PHP file and appends it to a ...

How to Accurately Obtain Serial Numbers in Add, Remove, and Clone Operations Using My Calculation Method

How To Properly Calculate SrNo in the Add, Remove, and Clone Functions By clicking "Add" multiple times, deleting rows, and then adding again, the SrNo becomes incorrect. I want it to calculate properly with my custom function... <div id="button_pro" ...

I have attempted every possible solution to identify the reason behind this recurring error. Specifically, I keep encountering a CastError when trying to convert a

Struggling to figure out why this error keeps happening. It's so frustrating! I've been attempting to eliminate the cloudinary upload feature from my website. This should allow users to post on my blog without having to upload an image. Howeve ...

Having difficulties in deploying Node application on Openshift platform

I'm facing an issue while deploying my ExpressJS application on Openshift using the command line tools. Here is a debug trace of the error encountered: >npm info ok Preparing build for deployment Deployment id is 5e2abc99 Activating deployment HA ...

Exploring jQuery Mobile: When to Use document ready versus Page Events

I'm currently using jQuery Mobile, and I'm a little confused about the differences between traditional document ready and jQuery Mobile page events. Can you clarify the actual distinctions? Why is it preferable to use <!-- language: lang-j ...

Assess html code for Strings that include <% %> tags along with embedded scripts

Having a small issue with my code where I am receiving an HTML response from a web service as a java String. I need to display this String as HTML on my webpage, but the problem is that there are some script tags in the form of <% ... %> which are sh ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

Adjusting the height of the Iframe dynamically every 2 seconds

One issue I am facing is with the iframe height. When I load the iframe, it sets the height correctly and adjusts when content is loaded dynamically. However, if I reduce or delete content from the loaded page, the iframe height does not decrease (e.g., in ...

There is no overload that fits this call. The string type cannot be assigned to the Signals type

Lately, I've been utilizing Typescript for constructing a microservice and managing signals. The code was running smoothly until a few days back, but now it's throwing errors without any apparent fix. This is an excerpt of the code responsible f ...