The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www on ubuntu). While checking through Firebug, I noticed that the response code is good (4 & 200), but unfortunately, the contents of the file are not being displayed on the DOM. Here is the code snippet:

<!DOCTYPE html>
<html>
    <head>
        <script>
        var xmlhttp;
        var url = "http://192.168.0.5/ajax_info.txt";

        function loadXMLDoc(url, cfunc) {
            if (window.XMLHttpRequest) { 
                xmlhttp = new XMLHttpRequest();
            } else { 
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = cfunc;
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }

        function myFunction() {
            loadXMLDoc(url, function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            });
        }
        </script>
    </head>

    <body>
        <div id="myDiv">
            <h2>Let AJAX change this text</h2>
        </div>
        
        <button type="button" onclick="myFunction()">Change Content</button>
    </body>
</html>

I am facing some issues in deciphering what might be going wrong. The tutorial provided by w3schools has its limitations. Considering purchasing a book to delve deeper into this subject matter. However, I am keen on mastering these basic GET calls as they will set me on the right path. Any advice or suggestions would be immensely helpful.

Answer №1

function initiateAjaxRequest(data) {

            var request;

            if (window.XMLHttpRequest) {
                request = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                alert("Sorry, your browser does not support Ajax! ^_^");
            }


            if (request !== null) {
                request.onreadystatechange = function() {
                    if (request.readyState < 4) {
                        //document.getElementById('cnt').innerHTML = "Progress";
                    } else if (request.readyState === 4) {
                        //response received
                        var response = request.responseText;

                        document.getElementById('center_scrolling_div').innerHTML = response;
                        eval(document.getElementById('center_scrolling_div').innerHTML);
                    }
                };

                request.open("GET", data, true);
                request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                request.send();


            }

        }

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

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...

Working with JSON data in AngularJS: A guide to loading data onto a scope variable

I am in the process of developing my personal website where I want to be able to update content easily without having to mess with the HTML code. My approach involves loading and updating a JSON file to achieve this, however, I am currently struggling with ...

The AJAX call patiently pauses until the preceding request completes

I am attempting to showcase installation progress using AJAX. Here is what my PHP code looks like: if($method == "install"){ $_SESSION['progress']="step 1"; $obj->thisTakesAboutAMinute(); $_SESSION['progress']="step 2"; $o ...

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

Dropdown list remains open despite a selection being made

My problem arises when I attempt to select an item from the list, as the dropdown menu does not populate automatically and the list remains open. Here is the HTML code for the dropdown list: <label id='choose' for='options'>Sele ...

Removing a child element in ReactJS that was dynamically created based on a count

Currently, I'm working on a project with two React components: TrackSection (the parent element) and TrackItem (the child). The TrackSection contains a button that adds a new TrackItem every time it is clicked by incrementing the numTracks variable. W ...

Guide to presenting JSON data with ajax

I am trying to dynamically display data based on the selected value from a drop-down list using Ajax's GET method. The idea is to modify the URL by appending the selected item in order to retrieve relevant data from the server: Here is an example of ...

Error: Unable to execute workouts.map as a function in "React" due to a TypeError

This is the JSON data retrieved from the server: {workouts: Array(3)} workouts: Array(3) 0: {_id: 'idnumber1', title: 'pullup', reps: 40, load: '20', createdAt: '2022-07-20T18:06:39.642Z', …} 1: {_id: 'idnumb ...

Tips to retrieve an Angular `value` from outside the module

customConfig.js angular.module("steam") .value("customConfig", { baseurl: "http://dev-back1.techgrind.asia/" }); To access the value outside the module, replace the " .." with customConfig.baseurl apiTest.js var frisby = require("frisby"); fris ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

The update functionality of the p:commandButton seems to be malfunctioning when used within a ui:include

Looking to refresh part of a page using PPR (Partial Page Rendering). This section of the page needs updating: <h:panelGroup id="aggiungiAuto" rendered="#{!autoBean.operazioneOk}"> <ui:include src="../component/aggiungi_ ...

In Protractor, mastering the technique to extract multiple values simultaneously is crucial for efficiently handling applications that receive a large amount of push notifications

I am currently developing an automation test using Protractor for an application that receives a large volume of push notifications. The issue I am facing is testing a simple logic. expect(A + B).toEqual(C); The problem arises because A, B, and C are sou ...

The browser sends a request for a file, the server then downloads a pdf, and finally, the

Here is the process I am trying to achieve: 1) A browser sends an ajax request to the server, requesting a pdf file. 2) The server downloads the pdf file and returns it for display. 3) The browser then displays the downloaded pdf in an existing iframe. Be ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Scrolling to a specific element using jQuery after a specified delay has

On my website, I have a page with an autoplaying video located at . My goal is to implement a feature where once the video completes playing after a specific duration, the webpage will automatically scroll down to the text section. This scroll action sho ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Having trouble attaching a function to a button click event

My viewModel includes a function: function resetForm(){ loanSystem("lis"); status(""); processor(""); fileType("funded"); orderDate(""); loanNumber(""); team(""); borrower(""); track ...

Encountering an issue with React JS Array Filtering: running into the error message "

I am encountering an error stating that includes is not a function, and the record.id is not being recognized in VS Code. I'm not sure where the problem lies? import React, { Component } from 'react' import axios from "axios" export de ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...