Data in JSON format is not sourced from a text file

My latest project involved creating two new files within a folder titled "hello". These files are named index.html and jsontext.txt.

The contents of index.html look like this:

<!DOCTYPE html>
<html>
<head>
    <title>Experiment</title>
</head>
<body>
    <p id="demo"></p>
<script>
    var a="";
    var b="";
    var xmlhttp=new XMLHttpRequest;
    var url="hello/jsontext.txt";
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4&&xmlhttp.status==200){
            var values=JSON.parse(xmlhttp.responseText);
            a=values.name;
            b=values.pwd;
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    document.getElementById("demo").innerHTML=a+" "+b;
</script>
</body>
</html>

Now, let's take a look at the content of jsontext.txt:

{"name":"Prasad","pwd":"123"}

After completing these steps, I decided to move the entire "hello" folder to the tomcat webapps directory. Once Tomcat was up and running, I attempted to access the page by typing localhost:8080/hello/index.html. However, despite the page loading successfully, the values were not being displayed. Can anyone provide guidance on how to properly retrieve data from JSON using JavaScript?

I understand that this issue may seem trivial to some, but as a beginner in coding, every step is part of the learning process. Any assistance would be greatly appreciated.

Edit

<!DOCTYPE html>
<html>
<head>
<title>Track Page</title>
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap"
    async defer></script>
  <script>
  var http=new XMLHttpRequest();
  var url="jsontext.txt";
  var marker;
  var user_lat,user_lng;
  function initMap() {

        http.onreadystatechange = function(){
        if(http.readyState == 4 && http.status == 200){
            var coordinates=JSON.parse(http.responseText);
            user_lat=coordinates.latitude;
            user_lng=coordinates.longitude;
            var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: user_lat, lng: user_lng},
            zoom: 8
            });
                marker = new google.maps.Marker({
                map: map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                label:'Driver1',
                position: {lat: user_lat, lng: user_lng}
            });
            marker.addListener('click', toggleBounce);
        }
     }
     http.open("GET",url,true);
     http.send();
  }
  function toggleBounce() {
    if (marker.getAnimation() !== null) {
        marker.setAnimation(null);
      } else {
      marker.setAnimation(google.maps.Animation.BOUNCE);
    }
  }

  </script>
</body>

Answer №1

When working with AJAX, it's important to remember that it is asynchronous in nature. Make sure you are handling the response properly by placing your code within the callback function. In this case, make sure to set the values of variables a and b after the AJAX response has occurred.

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState==4&&xmlhttp.status==200){
        var values=JSON.parse(xmlhttp.responseText);
        a=values.name;
        b=values.pwd;
        document.getElementById("demo").innerHTML=a+" "+b;
    }
}

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

JavaScript - Error: The '}' token was unexpected

Every time I attempt to move <div id="test">this should go down</div> downwards using: <div onclick="(".test").slideDown(800);">close it</div> I encounter an error whenever I click 'close it' SyntaxError: Unexpected to ...

The Jquery Datatable fails to display the accurate number of rows based on the selections made in the dropdown

I am working on an ajax call that returns a table. In the success method, I am using $("#tableID").dataTable();. Although it shows paging and the number of rows in the dropdown, it is displaying all rows instead of only the number of rows selected in the d ...

Every page on Nextjs displaying identical content across all routes

I recently deployed a Next.js app using docker on AWS infrastructure. While the index page (/) loads correctly, I've noticed that the content of the index is also being loaded for every other route, including api routes, as well as the JavaScript and ...

After restarting, Nuxt 3 runtime configuration values do not get updated with environment variables

Encountered a challenge with updating variables in runtimeConfig that rely on environment variables. When the application is built with values from the .env file like: API_URL=localhost:3000 The console displays localhost:3000. However, upon stopping th ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Is it feasible to assign a PHP $_SESSION variable to a JavaScript variable?

In my computing class, I am working on a game where the user needs to adjust settings for their robot before starting to play. I have created a separate PHP file for users to customize their robot's settings. I am curious if there is a way to assign ...

How to convert jQuery data into JSON format

I am dealing with data in the following format: ID=300573&CarNo=1&Account=AAAA&AccountingDate=3%2F21%2F2013&Description=NewCar&CheckAmount=666666&ClearedAmount=-3446.5&ClearedDate=4%2F9%2F2013&Sent=S&SentDate=4%2F4%2F20 ...

Is there a way to run only one instance of puppeteer.launch() and simply forward pages to it in Node.js?

I have a concern regarding the code snippet below. It appears to be launching the browser on every request, potentially causing server issues on Heroku. I would like to modify it so that puppeteer is launched as a Singleton instance, where it only needs ...

The Link Element Does Not Appear Properly When Styled Using nth-of-type Selector

https://codesandbox.io/s/damp-worker-k7fj6y?file=/src/App.js Can anyone help me understand why the fourth .content <Link/> is not displaying when using the given CSS styling? Could it be a bug in the code, or am I overlooking something important? ...

The acceleration of the ThreeJS scene intensifies with each passing moment

My friend and I have been collaborating on a university assignment - creating a basic Pacman clone using ThreeJS (which is a requirement). From the start, we've encountered a persistent issue. As our scene continues to run, it progressively speeds up ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

Tips for displaying subtotal in a Vue application using Firebase Realtime Database

I am currently troubleshooting a method in my Vue app that is designed to calculate the total value of all items sold. Despite seeing the correct values in both the database and console log, the calculation seems to be incorrect. Could there be an issue wi ...

Tips for modifying AJAX behavior or restricting requests in Wicket

I am looking to prevent updates based on a specific JavaScript condition using AjaxSelfUpdatingTimerBehavior. WebMarkupContainer messagesWmc = new WebMarkupContainer( "messagesWmc" ) ; messagesWmc.setOutputMarkupId( true ) ; messagesWmc.add( ...

Using jQuery and CSS to choose a specific set of elements

My goal is to choose a specific set of anchor elements using the nth-child pseudo selector. However, I am facing an issue because nth-child only works with child elements, and my structure looks like this: <div> <a>first link> </div> ...

Troubleshooting: Issues with Angular form validation functionality

I am completely new to Angular and attempting to create a signup form. Despite following tutorials, the form I've built doesn't seem to be validating properly. Below is the code that I have been using: <div class="signup-cont cont form-conta ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Unlocking full content access on newapi.org is just a few simple steps away

Currently, I am in the process of building a website using the newsorg API. After sending a request to the API, below is the sample output that I received: "articles": [ -{ -"source": { "id": null, "name": "Hind ...