The retrieval of data using an Ajax call to a servlet from a JavaScript function is not successful in returning a value

My goal is to load a map with markers on a website. When I trigger the servlet from JavaScript code outside a function, I successfully retrieve the values (coordinates for marker display). However, when I encapsulate the servlet call within a function and then create the map, I encounter an issue where the map appears blank without any visible places or markers. It seems like a completely empty map because even though it loads, all I can see is a mouse pointer resembling a hand as in Google Maps.

The problem lies in the fact that while the map gets loaded, the function responsible for calling the servlet to fetch coordinates does not get executed. This contrasts with the scenario where I place the servlet call directly outside of a function, in which case it works properly. To debug, I utilize the console.log() method to display the array of values fetched from the servlet, but I only see an empty array: [].

I suspect that the issue may lie with the xhr.open() method not being invoked. Admittedly, my experience with JavaScript is limited to just a few days, so I'm uncertain about how to troubleshoot this problem. Any assistance would be greatly appreciated.

function initMap() {
    xhr = new XMLHttpRequest();

    getLocation(xhr); // calling the function that retrieves location data from the servlet

    var bounds = new google.maps.LatLngBounds();
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv);
    map.setCenter(new google.maps.LatLng(latArray[0], lngArray[0]));
    map.setZoom(18);
    console.log(deviceId);
    console.log(latArray);

    latArray.forEach(function(lat, i) {
        var infoWindow = new google.maps.InfoWindow({
            content: '<div id="content">' + '<p style="color:#000000">DeviceID:<p>' + '<p>' + deviceId[i] + '</p>' + '</div>'
        });

        marker = new google.maps.Marker({
            map: map,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            position: new google.maps.LatLng(latArray[i], lngArray[i]),
            icon: "phone6.png"
        });

        marker.addListener("click", function() {
            placeMarker(this.map, this.marker, latArray[i], lngArray[i]);
        });
    });

}

function open() {
    xhr.open('POST', 'GetLocationFromDB', true);
    xhr.send();
}

function getLocation(xhr) {
    xhr.onreadystatechange = function() {  
        if (xhr.readyState == 4) {
            data = JSON.parse(xhr.responseText);
            for (i = 0; i < data.length; i++) {
                if (!((i + 1) % 3 == 0)) {
                    latArray.push(data[i]);
                    lngArray.push(data[i + 1]);
                    i = i + 2;
                    deviceId.push(data[deviceIdLoopCount]);
                    deviceIdLoopCount += 3;
                }
            }  
        }

    }
}

Edit:

Upon further research, I discovered that you cannot directly call the xhr.onreadystatechange function itself – instead, it's more of a reference. Despite attempting to execute onreadystatechange(), I found it unsuccessful. As a workaround, I passed xhr.onreadystatechange to a variable before invoking the function. How should I proceed in executing it correctly?

Answer №1

You haven't invoked the open() and send() methods of the XMLHttpRequest (xhr) object.

function getLocation(xhr) // Function to retrieve coordinates array from servlet
{
    xhr.open('POST', 'GetLocationFromDB', true);
    xhr.send();
    xhr.onreadystatechange = function() {
        ....
    }
}

For more information, please check here

EDIT 1:

Create a function that handles everything related to your map functionality:

function createMap(){

    var bounds = new google.maps.LatLngBounds();
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv);
    map.setCenter(new google.maps.LatLng(latArray[0], lngArray[0]));
    ..
}

Then call:

getLocation(xhr);
setTimeout(function(){ createMap() },200)

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

Exploring the issue of the next input not functioning properly and finding a solution for submitting the form when the user is on the final

There are 6 text fields, each with a maxlength of 1 set. I have implemented a script where users can only enter numbers. Upon entering a number in each field, the cursor automatically moves to the next field. When the cursor reaches the last field, an AJAX ...

What is the method for closing an <iframe> element directly?

A web page called room.html contains a table with an onclick function named place(): function place() var x = document.createElement("IFRAME"); x.setAttribute("src", "loading.html"); document.body.appendChild(x); } What is ...

Obtaining the chosen options from a dropdown menu

I am facing an issue with retrieving values from dropdown menus on a webpage that are used to filter a list. Despite trying various methods, I am not getting any values returned in my function. Here is what I have attempted: - var browserVal= document.ge ...

Ways to showcase flair in PHP code such as this

I currently have this code snippet: <h2 class="index-single">Tech Categories</h2><?php $args2 = array( 'cat' => 11 , 'posts_per_page' => 9 , 'paged' => $paged ); $the_query2 = new WP_Query( $args2 ); ...

Experiencing duplicate execution of $onChanges in AngularJS version 1.6

I might be overthinking this, but that's why I'm seeking help. :) Note: In the example below, the controller alias for the component is "ctrl". var ctrl = this; Imagine we have a component with two bindings, one of which is optional: bindings: ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

Is there a way to swap out values in a JavaScript Object for new ones?

I need to update the initial values of myObject with new names: let myObject = [ { name: 'X0', values: 'FALSE,TRUE' } , { name: 'X1', values: 'NORMAL,LOW,HIGH' } , { name: 'X2', values: ' ...

Which library should be connected in order to utilize JSONLoader, OrbitControls, and AnimationAction?

When looking for a Three.js library that supports JSONLoader, OrbitControls, and AnimationAction simultaneously, the choice can be challenging due to the variety of options available. The code snippet below showcases an attempt to incorporate these three f ...

Using a plain JavaScript React component within a TypeScript React project: A step-by-step guide

A coworker of mine used Typescript for a frontend React project. With their departure, I have been tasked by management to take over the project and deliver results from Day 1. While they are open to me using Javascript in the project, I am unsure how to i ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Comparing AngularJS controller and template encapsulation to Angular components: a breakdown

I've set up a state in my angularjs app called homeInside, complete with its own controller and template. Within that layout, I have various elements including a button with an ng-click event tied to the function doSomething. Additionally, there is an ...

What are the steps to retrieve JSON data and display it using an unordered list in an HTML document?

My JSON data structure looks like this: { "fID": "00202020243123", "name": "John Doe", "List": ["Father", "Brother", "Cousin"] } When I render this JSON element in my model and view it in the HTML, everything works fine. However, when I try t ...

Using a hashtag in the URL to open an HTML <div> element

I have a website with two tabs labeled as Home and Action. When I hover over the Action tab, the URL changes to include #tab_action: https://i.sstatic.net/OOD5S.png Then, when I click on it, the related tab content opens: https://i.sstatic.net/JdcGG.pn ...

Is there a way to automatically apply a class named "bottom" to the element with the ID "sidebar" when it reaches the bottom of its container?

I have implemented code that adds a CSS class called fixed to the element with ID #sidebar once it reaches a specific distance from the top of the webpage, depending on the page type (e.g. home, single, or page). In a similar manner, I am looking to add a ...

Having numerous sections condensed into one cohesive page

Currently, I am working with backbone.js to develop a single-page application that takes inspiration from the functionality of trello.com. I am interested in learning how to display multiple pages on top of the original page and effectively structure the ...

using a variable object to load, access data, and handle errors through mutations

element, I have incorporated two distinct mutations in a single react component: const [get_items, { error, loading, data }] = useMutation(GET_ITEMS); const [add_to_cart] = useMutation(ADD_TO_CART); To streamline and access both components' error, ...

The method is called after the focus is removed from the element

Currently, I am working on a project involving textboxes arranged in a grid to represent each day of the week. Alongside these textboxes is a drop-down list displaying the dates for that week, as well as a text area designated for specific comments related ...

Should Q.all be nested inside another Q.all?

Here's a snippet of my code: let tasks = []; tasks.push(MyModel.update({ _id: 50 }, { Test: 5000 }).exec()); return Q.all([ myPromise, Q.all(dbTasks) ]); I'm wondering if it is appropriate to nest Q.all inside another Q.all. Will the prom ...

Retrieving users by their Id's from MySql database using NodeJS

Goal: I aim to gather a list of users from a table based on the currently logged-in user. I have successfully stored all user IDs in an array and now wish to query those users to display a new list on the front end. Progress Made: I have imported necessa ...