user2332505
user2332505

Reputation: 649

How to print JSON response in javascript

I am able to make a Ajax request and getting response as well in form of JSON string, still alert box of JavaScript is not showing actual response text. I am new to ajax concept and dont know much.

Ajax-Call:-

Action triggered on dropdown
<select name="state" onchange="getOptions(this.value)">

Javascript Function called :-
function getOptions(state){
  AJAX.onreadystatechange = handler;
  AJAX.open("GET", "getData?id="+state);
  AJAX.send();
};

Response Firebug is showing

Response Content

This is my code to fetch response and print.

function handler() {
  if(AJAX.readyState == 4 && AJAX.status == 200) {
    var json = eval('(' + AJAX.responseText +')');
    alert('Success. Result:' + json);
  }
  else if (AJAX.readyState == 4 && AJAX.status != 200) {
      alert('Something went wrong...');
  }
}

Every time its a success but i get output as enter image description here

Upvotes: 1

Views: 14123

Answers (2)

If you need to see the value as part of debugging the code, you should use console.log(AJAX) to inspect the value.

If you really need to display some message to the user, then reconsider showing the json result unformatted/filtered - that said you could iterate through all the objects properties and concenate theese in a string (like @Hiral shows).

Upvotes: 0

codingrose
codingrose

Reputation: 15709

You need to treat your response as JSON not as text.

Try this:

function handler() {
    if (AJAX.readyState == 4 && AJAX.status == 200) {
        var json = JSON.parse(AJAX.responseText), len = json.length, i = 0, txt = "";
        for (; i < len; i++) {
            if (txt) {
                txt += ", ";
            }
            txt += json[i].name;
        }
        alert('Success. Result:' + txt);
    } else if (AJAX.readyState == 4 && AJAX.status != 200) {
        alert('Something went wrong...');
    }
}

Upvotes: 1

Related Questions