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

Challenges with sending JSON encoded Arrays from WordPress to PHP results in empty or NULL responses

My Plugins site has multiple Inputs that I need to gather values from and push them into an array. Then, I utilize the jQuery.post method to send this data to my PHP script. Javascript: var json = JSON.stringify(output); // output is an array with multip ...

Exploring best practices for transmitting JavaScript objects and arrays via forms to servers (JSON/??)

I would like to understand what would be the most effective approach to achieve this: Based on a user selection, generate a list of "selected items" in the following format: {items {categoryString {tag_id1 {[fr]=>itemFR, [en]=>itemEN} {c ...

Troubleshooting: Why is $watch failing to track changes on factory variables in Angular

I have created a factory named SharedService as shown below: angular.module('Fms').factory('SharedService', function() { var userdetails=false; return userdetails; }) Below controllers utilize this factory: angular.mod ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Compare the current return value to the previous value in the success callback of an Ajax request

I am currently running an Ajax request to a PHP DB script every 3 seconds, and I need to make a decision based on the result returned. The result is a timestamp. Let's say the ajax request is fired two times. I want to compare the first result with th ...

What steps should I take to fix the error message "Uncaught TypeError: Class constructor m must be called with 'new'" that occurs while attempting to access a polymer v2.0 application?

Is there a way to resolve this error that occurs when attempting to open a Polymer v2.0 app on Safari in iOS? Uncaught TypeError: Class constructor m cannot be invoked without 'new' from custom-elements-es5-adaptor. The Polymer v2.0 starter k ...

Newbie's guide: Saving information in Ruby on Rails

In my Rails 4 application, I am looking to save questions and answers either in a document or database. Once stored, I want to showcase them on a specific webpage for users to respond. For instance, I envision having a page titled /questions where a quest ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Client-side rendering for NextJS server components is also supported

I am currently working with Material UI v5.11.16 in a nextjs environment using v13.3.0. I followed the official documentation setup for my nextjs project which can be found here. So far, I have successfully integrated Material UI components without having ...

Incorporate a personalized JavaScript code segment during the Vue build process

I am currently working with Vue CLI and I need to include a custom javascript section in the default template when I release my project. However, I do not want this section to be included during the debugging phase. For example, I would like to add the fo ...

What is the best way to identify when the soft-keyboard is hidden in the Android browser

Having trouble with the Android Webkit browser and need to manually detect when the soft-keyboard is hidden by pressing the button in the top right corner. https://i.stack.imgur.com/x11Vp.jpg In the image above, pressing the button hides the soft keyboar ...

What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animati ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

"Optimizing navigation with dynamic link routing in AngularJS

I am working on a list of apartments displayed using ng-repeat. I need each apartment to be a clickable link that directs the user to view more details about that specific apartment. However, I am facing an issue where the links are not being repeated dyna ...

JavaScript function overriding allows a subclass to provide a specific implementation of

I have a JavaScript file with two methods: var DBProcessing = function() { console.log("ok") ... } var DBProcessing = function(str) { console.log(str); ... } When calling DBProcessing(), I am only getting an output of undefined. Is there a way to expli ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

Is it possible to disable a function by clicking on it?

I currently have a website that is utilizing the following plugin: This plugin enables an image to be zoomed in and out through CSS transforms, with default controls for zooming in and out. My goal is to incorporate a reset button that returns the image ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...

fabricJS: clicking on various buttons with the mouse

I have successfully created multiple canvases on the same page based on the number of PDF pages. However, I am facing an issue where some buttons to add different canvases are not working as expected. What I am attempting to do is add text on mouse down fo ...