-1

I am new to Javascript and Ajax. I was trying to write some code wherein I parse the JSON response of a HTTP request and then access different elements within the response object. But I keep running into 2 different errors. I tried looking through various solutions on stack overflow, but i havent been able to get them to work. Any help would be greatly appreciated.

 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
     var json = JSON.parse(this.responseText);
       document.getElementById("lola1").innerHTML = json;
       initMap(json);
     }
 };

I want to pass in only the results array from the response object. However if I do this, The page display is " [object Object] "

When I try to do JSON.parse within the initMap method, then i get a syntax error on JSON.parse

SyntaxError: JSON Parse error: Unexpected identifier "undefined"

if (this.readyState == 4 && this.status == 200) {
  var json = this.responseText;
  initMap(json);
}


function initMap(response_val) {  

    // Process input results
    document.getElementById("lola1").innerHTML = JSON.parse(response_val)
    ...

Thanks.

kbinstance
  • 346
  • 5
  • 17
  • 2
    The 1st isn't really an error. [`"[object Object]"` is just the default result from converting an object to a string.](https://stackoverflow.com/questions/4750225/what-does-object-object-mean) To see more information from the object, you'll have to specify how you want it formatted (such as the JSON it was just parsed from) or [retrieve values from the object's individual properties](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json). – Jonathan Lonowski May 04 '17 at 02:07

3 Answers3

0

The problem is you're trying to set the innerHTML to an object. innerHTML can only be a string, therefore it tries to coerce your object into a string. If you really want to display the entire responseText, you could simply document.getElementById("lola1").innerHTML = this.responseText;

I made an example fiddle to further show what setting the innerHTML of an object vs the stringified representation of the object looks like: https://jsfiddle.net/tuqd9x8k/

jas7457
  • 1,712
  • 13
  • 21
  • Thanks for the response. I need to store that information as i want to interate through the object and use some of the values in another function. If i use json.stringify then it escapes all quotes with a \ . Is there a way to retain the JSon object so i can do this ? – kbinstance May 04 '17 at 02:16
  • JSON.parse will turn the stringified object back into a normal object. My point was that you can't set innerHTML to an object. – jas7457 May 04 '17 at 02:18
  • The responsetext should return an object, but if I check the type using typeof, it says it is a string. Hence I tried to use JSON.parse which gave me an error. I don't want to display the object at all. What I want to do, is parse it into JSON format so I can iterate over the object. Is there a way to do that without hitting the errors I am getting ? – kbinstance May 04 '17 at 06:59
  • I don't think responsetext ever returns an object, but sometimes it is a stringified object. You say it should return an object, but that really depends on what url you're hitting for your ajax request, as it can return anything it wants to. What do you see when you simply log the response, without trying to parse anything? – jas7457 May 04 '17 at 11:04
  • The 2 lines I output are JSON.parse(this.responseText).results and this.responseText. The first one gives [object Object] and the second one gives {.... "signature": { "$1": "json" }, "results": [{ "$1": { "categories": [{ "alias": "sushi", "title": "Sushi Bars" }], ...... } So the response string looks like JSON, but JSON.parse().results to look at the results array gives me [ object Object] – kbinstance May 04 '17 at 18:04
0

You can try and log the information using

console.log(this.responseText);
console.log(json.parse(this.responseText));

You will see the difference and between the two and better visualize your response data.

Harshil
  • 436
  • 1
  • 7
  • 16
  • Thanks for the suggestion. I can see the output now. I also output the type - string followed by the string which looks like JSON object. The JSON.parse gives an object with results field as results: [Object] . But i need to look at the nested object. Is there a simple way to do that ? – kbinstance May 04 '17 at 07:05
  • assuming your responseText to look like '{ "car":"Ford", "mileage":30, "year":"2017"}' and you parse your data using var obj = JSON.parse(this.responseText). Then obj.car should display "Ford" – Harshil May 04 '17 at 09:06
  • I tried that. I tried to display obj.results bit that shows null. When i try expand in on the console logs then i can see the contents. Im not sure why its null. When i hover over it shows results [0]["$1"] . So i tried using that as well. But it gives an error then. – kbinstance May 04 '17 at 16:37
  • Can you create a fiddle and mention the link you are trying to access ?! That way I can recreate the issue at my end and assist you better. – Harshil May 05 '17 at 06:36
0

I managed to fix the issue in my code. @jas7457 was right, setting innerHTML to an object caused issues. I wasn't sure how it looked. But i printed it to console.log.

The code now looks like

var response = JSON.parse(this.responseText);

    // error checking
        if (!response.results || !response.results.length) {
          console.log("No results");
          return;
        }

        // there should only be one object in the result array
        var result = response.results[0];
        console.log(result);

   if (result.businesses) for (var i=0; i < result.businesses.length; i++) {
        parse the nested son businesses object in the results.. 
  }

And this works for me. Thank you too much for all the help! I really appreciate it!

kbinstance
  • 346
  • 5
  • 17