-2

I am making an Ajax call in my JSP which is recieving a JSON response.

Running alert('Ajax Response ' + respArr); gives the following screen:

Screenshot of Alert message

The Java server-side code:

public void doGet(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
    try {
        String fromDate = request.getParameter("drFrom");
        String toDate = request.getParameter("drTo");
        JSONArray jsonArray = chartData.getCCSBJson(fromDate, toDate);
        res.setContentType("application/json");
        res.getWriter().write(jsonArray.toString());
    }

The JavaScript:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if(xmlhttp.responseText != null) {
        var respArr = xmlhttp.responseText;
        var jsonData = eval("(" + respArr + ")");
        alert('JSON Chart ' + jsonData); // The line from above
        var obj = JSON.parse(xmlhttp.responseText);
        alert('JSON Parse' + obj);

The JSON that is being returned:

[
  {
    "chart":{
      "caption":"",
      "exportDataFormattedVal":"1",
      "numberPrefix":"",
      "showexportdatamenuitem":"1",
      "xAxisName":"Bureau usage",
      "yAxisName":"count"
    },
    "data":[
      {
        "label":"SB AutoDecison",
        "value":"0"
      },
      {
        "label":"CC AutoDecison",
        "value":"0"
      },
      {
        "label":"CC Judgemental",
        "value":"0"
      },
      {
        "label":"SB Judgemental",
        "value":"0"
      }
    ]
  }
]

The alerts result:

alert('JSON Chart ' + jsonData) // JSON Chart[object Object]
alert('JSON Parse ' + obj);     // JSON parse[object Object]

What I want is to parse the object and generate an Excel sheet out of the content.

When I try to loop:

var jqueryData = jQuery.parseJSON(respArr);
var obj = JSON.parse(xmlhttp.responseText);
for (var i in obj) {
    alert('For loop string' + obj[i]);
}

It throws some 7 or 8 alerts with JavaScript code

for (i = 0; i < 5; i++) {
    alert(i + ' of respArr ' + respArr[i]);
}

Gives letter after letter of the JSON: [, {, ", c, h, and so on for each iteration of the loop.

Can I not just traverse the JSON like respArr[0].data or respArr[0].chart?

6
  • I don't understand what is the problem? Commented Jun 3, 2014 at 18:30
  • I removed the jQuery tag.. but I now see the jqueryData variable.. even though there isn't actually any jQuery in what you've shown us, and jqueryData isn't defined anywhere.. so if I was wrong to remove the jQuery tag, please add it back. Commented Jun 3, 2014 at 18:30
  • try to use console.log in place of alert, it will help to debug fast Commented Jun 3, 2014 at 18:30
  • Don't use alert, use console.log, it'll show the object. Commented Jun 3, 2014 at 18:31
  • Help me parsing the Json object... respArr[0].chart says undefined..I just tried multiple ways of parsing JSon.. Not issue with the jQuery.. Commented Jun 3, 2014 at 18:33

3 Answers 3

1

A couple of things:

First, your Java servlet is not really returning a "string". When you write jsonArray.toString(), yes, you are turning the array into a string, but that is solely for the purpose of writing it across the network. HTTP is a text protocol. So, what the doGet method is actually returning, in a sense, is a HTTP response (it just happens to be as text, it could very well be binary).

With that, when a client (in this case, your JavaScript via XMLHttpRequest) makes a GET request to your server (your servlet), it is getting back the JSON response (yes, as text). Your xmlhttp.responseText variable in this case should contain the JSON you've shown in the question.

Calling one of:

  • JSON.parse(xmlhttp.responseText)
  • jQuery.parseJSON(xmlhttp.responseText)
  • $.parseJSON(xmlhttp.responseText)

Should all return you the same object. With this object you can access its properties the way you want to. The following should work:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if (xmlhttp.responseText != null) {
        var json = xmlhttp.responseText;
        var arr = JSON.parse(json);
        var data = arr[0].data;       // This is what you want to do?
        var chart = arr[0].chart;     // This is what you want to do?
        // try running alert(chart.xAxisName);
        // and so on

Side note: When you run alert(obj); where obj is a object, you are seeing [object Object] because that is how JavaScript represents objects as strings. If you want to see the internals of a JavaScript object, as others have pointed out, you are better off using console.log(obj). (Also, upgrade or switch to a better browser. You will have access to better debugging tools.)

Sign up to request clarification or add additional context in comments.

Comments

1

Your json response has this structure:

[
   {
      "chart":{
         "caption":"",
         "exportDataFormattedVal":"1",
         "numberPrefix":"",
         "showexportdatamenuitem":"1",
         "xAxisName":"Bureau usage",
         "yAxisName":"count"
      },
      "data":[
         {
            "label":"SB AutoDecison",
            "value":"0"
         },
         {
            "label":"CC AutoDecison",
            "value":"0"
         },
         {
            "label":"CC Judgemental",
            "value":"0"
         },
         {
            "label":"SB Judgemental",
            "value":"0"
         }
      ]
   }
]

Access the the 1st element of the outermost object like response[0]. And then the chart object within it like response[0].chart and so on. http://jsonformatter.curiousconcept.com/ will help format the JSON and make it readable.

1 Comment

You mean var respArr = xmlhttp.responseText; alert(respArr[0]); ------------> gives [ alert(response[0].chart); -----------> gives undefined...
1

Check out this FIDDLE

You can access the properties of your object directly.

$(function () {

    var q = [{
        "chart": {
            "caption": "",
                "exportDataFormattedVal": "1",
                "numberPrefix": "",
                "showexportdatamenuitem": "1",
                "xAxisName": "Bureau usage",
                "yAxisName": "count"
        },
            "data": [{
            "label": "SB AutoDecison",
                "value": "0"
        }, {
            "label": "CC AutoDecison",
                "value": "0"
        }, {
            "label": "CC Judgemental",
                "value": "0"
        }, {
            "label": "SB Judgemental",
                "value": "0"
        }]
    }];

    console.log(q);
    console.log(q[0].data);
    q[0].data.forEach(function (item) {
        console.log(item.label);
        console.log(item.value);
    });

});

6 Comments

Iam testing in IE 9 ... is Fire Bug available for in IE9
Press F12. There's a console there (a really poor one, though)
Afterreplacing console.log(q[0].data); with alert('zero of resp Arr '+respArr[0].data); says undefined....
@Technomation have you changed the variable's name?
No I didnt..Pls chck the screen i have attached of alert('Ajax Response '+respArr); alert('zero of resp Arr '+respArr[0].data); says undefined
|

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.