0

I'm using this code to get a JSON file stored in the same folder.

var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}


function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}

The file looks like this:

{"total": 3}

It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).

When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.

I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.

Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?

2
  • 1
    What does the console.log(jsonObj) show ? Does it show a dropdown of Object in the console or does it show {"total":3} ? Commented Feb 3, 2017 at 5:33
  • 1
    Have you tried printing request11.response's content to the console? It looks suspicious that you set onload callback after you send() the request (I'm not sure how JavaScript is prone to race conditions of this kind). Do you use some kind of web server? Is there anything on the "Network" tab of "Developer console" (exists in Chrome/Firefox, opened by pressing F12)? Commented Feb 3, 2017 at 5:34

1 Answer 1

2

You need to parse the JSON string into an object before you try and access the total field.

var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.