retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem to be functioning as expected. I suspect the problem lies within the section of the code where I attempt to output the XML data using a for loop.

Sample XML data:

<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>

Javascript

<script language="javascript">

// JavaScript Document

var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;

function startChat() {
    getOnlineMembers();
}   

// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
    return new XMLHttpRequest();
}
else if(window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
} else{
        document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}

function getOnlineMembers(){
    if(getMember.readyState == 4 || getMember.readyState == 0){
        getMember.open("GET", "get_chat.php?get_member", true);
        getMember.onreadystatechange = memberReceivedHandler;
        getMember.send(null);
    }else{
            setTimeout('getOnlineMembers()', 1000);
    }
}

function memberReceivedHandler(){
    if(getMember.readyState == 4){
        if(getMember.status == 200){

            var chat_members_div = document.getElementById('chat_members');
            var xmldoc = getMember.responseXML;
            var members_nodes = xmldoc.getElementsByTagName("member"); 
            var n_members = members_nodes.length;
            for (i = 0; i < n_members; i++) {
                chat_members_div.innerHTML += '<p><a href="' + members_nodes[i].childNodes.nodeValue + '">' + members_nodes[i].childNodes.nodeValue + '</a></p>';
                        chat_members_div.scrollTop = chat_members_div.scrollHeight;
                    }

            mTimer = setTimeout('getOnlineMembers();',2000);

        }
    }   
}


</script>

HTML page

<body onLoad="javascript:startChat();">

  <div id="chat_members">


  </div>

</body>

I'm still learning about AJAX and any assistance with this would be greatly appreciated. Thank you!

Answer №1

When encountering issues:

-- Utilize an HTTP analyzer such as HTTP Fiddler to inspect the communication process. Ensure that your page is connecting with the server and receiving the expected code without any HTTP errors.

-- Verify the correctness of your IF statements by checking if they are properly bracketed. For instance, instead of:

if(getMember.readyState == 4 || getMember.readyState == 0){

It would be clearer like this:

if( (getMember.readyState == 4) || (getMember.readyState == 0)){

While it may seem subtle, being precise is essential.

-- Insert some form of validation in your javascript conditions following the IF statement to ensure the program flow is functioning as intended. If a debugger is unavailable, opt for using an alert box for monitoring purposes.

Answer №2

The xmlhttp request should be sent before checking the response status:

function fetchOnlineUsers(){
        getUser.open("GET", "get_chat.php?get_user", true);
        getUser.onreadystatechange = userReceivedHandler;
        getUser.timeout = 1000; //set timeout for xmlhttp request
        getUser.ontimeout = userTimeoutHandler;
        getUser.send(null);
}

function userTimeoutHandler(){
        getUser.abort(); //abort the timed out xml http request
        setTimeout(function(){fetchOnlineUsers()}, 2000);
}

function userReceivedHandler(){
    if(getUser.readyState == 4 && getUser.status == 200){

            var chat_users_div = document.getElementById('chat_users');
            var xmlDoc = getUser.responseXML;
            var usersNodes = xmlDoc.documentElement.getElementsByTagName("user"); 
            var totalUsers = usersNodes.length;
            for (i = 0; i < totalUsers; i++) {
                chat_users_div.innerHTML += '<p><a href="' + usersNodes[i].childNodes.nodeValue + '">' + usersNodes[i].childNodes.nodeValue + '</a></p>';
                chat_users_div.scrollTop = chat_users_div.scrollHeight;
            }
            timer = setTimeout('fetchOnlineUsers();',2000); //Refresh our chat members in 2 seconds
    }   
}

To avoid caching of the response, you can append a random query parameter like:

getUser.open("GET", "get_chat.php?get_user&t=" + Math.random(), true);

Ensure the responseXML is not empty by logging it:

console.log(responseXML);

You may also need to select the root node of the XML response before selecting child nodes:

var usersNodes = xmlDoc.documentElement.getElementsByTagName("user"); //documentElement selects the root node of the XML document

I hope this information proves helpful.

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

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Executing the command `npm run jshint` yields the error message `script not found: jshint`

Currently, I'm attempting to run jshint on a few javascript files. However, I am encountering an issue where the local npm install of jshint is not functioning as expected. Upon checking, the package is indeed present: $ npm list --depth=0 <a hre ...

Combining ajax and jsp to fetch data for a servlet

In my JSP file, I have two text fields - signUp and post. I want the post text to be sent to a servlet using AJAX function while the signUp text should be sent in the usual way through request.getParameter(). Can these two functionalities be combined with ...

Prevent the bottom row from being sorted

I have implemented sortable table rows in my angular project, however the sorting functionality also affects some query-ui code elements. Now I am looking to exclude the last row from being sortable. HTML <div ng:controller="controller"> <ta ...

Retrieve the texture's color based on the UV coordinates

Currently, I'm working with version 73 of V. I am dealing with UV coordinates obtained from the intersection of a raycaster and a texture of an object. Is there a way to extract the color (RGB or RGBA) of the used texture at these specific UV coordina ...

Create a unique shader in Three.js that remains unaffected by the fog effect

I have implemented a custom shader to add glow to a sphere on my scene. However, I noticed that the fog in the scene affects the sphere but not the glow. When I zoom out, the sphere disappears but the glow remains visible. Is there a way to make the fog ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

Is there a Javascript tool available for creating a visual representation of the correlation between items in two separate

Does anyone have recommendations for an HTML/JavaScript/browser-based component that can map items in one list to another? Imagine a scenario where there is a list of items on the left-hand side and another list on the right, with the ability to click on a ...

After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functiona ...

What is the best way to show customized text from a data member within the :items object array for the item title in a v-select (Vuetify) dropdown menu

Currently, I am new to Vue and exploring Vuetify while working on building a dropdown using "v-select". If there is a simpler way to achieve this, it would be awesome! Otherwise, my plan is to create a new array, convert data for certain members into obje ...

MongoDB: Restrict the number of records returned to an increasing count within a specified range

Currently, I am working on a Node project that uses Mongoose. In my code, I have the following query: var query = Model.aggregate( { $match: { id: id } }, { $sort: { created: -1 } }, { $project: { name: ...

What is the process for including the Authorization HTTP header in a JSONP request?

I am attempting to make a GET request to the Yelp API. When I use the code below, I encounter a 401 error. From my research, it seems that setting the authorization in this manner is not possible when requesting JSONP data. However, when I attempt another ...

Why isn't my jQuery Flot Pie chart functioning properly when using $.Ajax and JSON?

I'm attempting to use JSON to generate a flot pie chart. It works perfectly with static data, but when I try to send data dynamically using JSON, nothing is displayed. Check out my code below: <script src="jquery-1.11.2.min.js"></script> ...

Looking for assistance with a simple Javascript program

My program needs to have a for loop and utilize existing input functions (name and number). Additionally, I need to calculate totals. Users should be able to CANCEL and proceed to doc.write where they can enter their name and number. Furthermore, users s ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

The impact of jQuery ajax on SVG data transmitted to a ColdFusion server appears to be significant

While using $.ajax() to send a string to a coldfusion server for storage in a table, I encountered an issue. Upon querying and attempting to use the data later on, an error message appeared stating "null Enclosed Exception: Invalid byte 2 of 3-byte UTF-8 s ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

Are we on the correct path for breaking down code using react JS?

As I work on creating reusable table components, each column comes with its own set of functionalities, which results in dealing with numerous components. To streamline the process, I have been separating every component piece into individual files and ex ...

Invoke a jQuery function in the parent page using regular JavaScript from an iframe

I have successfully created an iframe using regular javascript. Inside the iframe is a Jquery function along with JQuery itself and it functions correctly within the iframe. However, I am now looking to execute this function from the parent page instead of ...

Are your Express routes failing to function properly?

I recently embarked on creating a new Express app by following the tutorial from Code Magazine. Below are my app and the defined route for /img. https://i.sstatic.net/G6PUG.png Upon trying to access http://localhost:3000/img or http://localhost:3000/img/ ...