1

I'm trying to retrieve data from JSON object which I passed from the servlet. But my keys are numbered. I need to add these numbers to the name which i given to the keys.

My response looks like this..

{"shareInfo1":[{"uname":"xyz","image":"iVBO..","imname":"ryty","senderPicture":"iVBOR"}],"shareInfo2":[{"uname":"sds","image":"iVBO","imname":"ryty","senderPicture":"iVBOR}],....}

I tried with following code:

$.ajax({
    type: "GET",
    url: "RetrieveShares",
    data:'action='+encodeURIComponent(action),
    dataType: "json",
    success: function( data, textStatus, jqXHR)
    {
    if(data.success)
    {

for(var z=1;z<=data.loops;z++)
{
len=data["shareInfo"+z].length;
for(var k = len-1;k>=0;k -= 1){
    var newcommhtml = '<div id="S0'+thecid+'" class="snew">';
    newcommhtml = newcommhtml + '<div class="author-image"><img src="data:image/jpeg;base64,'+data["shareInfo"+z][k].senderPicture+'" alt="'+data["shareInfo"+z][k].uname+'" width="100%" height="100%" class="ava"></div><span>'+data["shareInfo"+z][k].uname+' shared the image '+data["shareInfo"+z][k].imname+'</span>';
    newcommhtml = newcommhtml + '<div class="s-content"><div class="s-message"><span>'+nl2br(data["shareInfo"+z][k].message+'</span></div><div class="shpicture">');
    newcommhtml = newcommhtml + '<img src="data:image/jpeg;base64,'+data["shareInfo"+z][k].image+'" alt="'+data["shareInfo"+z][k].imname+'" width="100%" height="100%" class="SharedImage" class="SharedImage" data-id="'+data["shareInfo"+z][k].id+'" data-alid="'+data["shareInfo"+z][k].alid+'" data-shareid="'+data["shareInfo"+z][k].shareId+'">';
    newcommhtml = newcommhtml + '</div></div>';
    var thelm = "#S0"+thecid;
    $('#spscrl').append(newcommhtml);
    $(thelm).hide().fadeIn('slow');
    newcommhtml ='<div class="SPcommentbox">';
    var i=0;
    if(Object.keys(data["shareInfo"+z][k]).length>8)
    {
        var x;
        for(x=data["shareInfo"+z][k].loopreq-1;x>=0;x-=1)
            {
       newcommhtml = newcommhtml + '<div class="comment"><div class="commenter-image"><img src="data:image/jpeg;base64,'+data["shareInfo"+z][k]["commenterPicture"+i]+'" alt="'+data["shareInfo"+z][k]["whocommented"+i]+'" width="100%" height="100%" class="ava"></div><div class="commentername">'+data["shareInfo"+z][k]["whocommented"+i]+'</div><span>'+data["shareInfo"+z][k]["commented"+i]+'</span></div>';
       i+=1;
            }
    }
    newcommhtml = newcommhtml + '<div class="comment"><div class="commenter-image">';
    newcommhtml = newcommhtml +'</div><div class="addcomment"><input type ="text" placeholder="Write a comment..." class="commentbox"></input></div></div>';
    $('#spscrl').append(newcommhtml);
    thecid++;
    }
    $(".primg > img").first().clone().appendTo(".commenter-image");
    }
    }
 },
    error: function(jqXHR, textStatus, errorThrown)
    {
    alert("error"+errorThrown);
    console.log("Something really bad happened " + textStatus);
    },
    });

But it produces the error TypeError: data[("shareInfo" + z)] is undefined

Please anyone help me to solve this problem ... Thanks...

  • Try this ..["shareInfo1":[{...}],"shareInfo2":[{...}],....] – Prasath K Mar 20 '13 at 09:09
  • 3
    Try posting a bit more of your code please. – SteveP Mar 20 '13 at 09:10
  • The full key with the z var does not exists. post more from your code using jsfiddler or something – Adidi Mar 20 '13 at 09:12
  • How do you convert the JSON response to a JavaScript data structure? What is `data.loops`? – Quentin Mar 20 '13 at 09:17
  • Is data your response object from an ajax call ? Please post the code were you get or setup data. – SteveP Mar 20 '13 at 09:21
  • The error message says "VshareInfo" and not "shareInfo" as in your example. Typo or not? – Stefan Mar 20 '13 at 09:22
  • Please post the result of `console.log(data)`. – Stefan Mar 20 '13 at 09:26
  • @Stefan I can't able to post complete response here. I'm retrieving images. In the response which is in `base64` String format. Response is similar to I given in Question. –  Mar 20 '13 at 09:29
  • `{"shareInfo1":[{...}],"shareInfo2":[{...}],....}` isn´t much. Try to mock your response (excl. the base64 properties). – Stefan Mar 20 '13 at 09:35
  • Try creating a reduced test case. What we have now is partial data that the script won't run because lots is still missing (including the aforementioned `data.loops`). Skip the JSON parsing and put the data directly in `var data`. Strip out anything that isn't contributing to the problem (e.g. the image data and anything that tries to read it). Show us a live demo on http://jsbin.com/ or similar. – Quentin Mar 20 '13 at 09:53
  • @Quentin I don't know how I represent the response in jsbin –  Mar 20 '13 at 10:12
  • @JamesRobinson — `var data = {"shareI…` – Quentin Mar 20 '13 at 10:27
  • you need to use json2.js file and then JSON.parse(yourjsonstring); this will convert jsonstring into javascript object – Vishal Sharma Mar 20 '13 at 11:41
  • @vishalsharma — No. The OP is using jQuery's `ajax` method with specifying the `dataType` (so no matter what the server says the data is, it will be treated as JSON). – Quentin Mar 20 '13 at 13:12

3 Answers3

0

I know this doesn't direcly answer your question, but it may provide a way to sort it out.

If you are able to modify the back end, I would suggest changing the format of your returned data to use arrays:

{
  "shareInfo":[
     {...},
     {...},
     {...}
  ]
}

Then you can just use normal shareInfo[index], and shareInfo.length etc.

SteveP
  • 18,840
  • 9
  • 47
  • 60
  • I know this will works.. But In my response I need to post more arrays with a common name in those.. I edited the response in my question. I can't able to post all `response`... –  Mar 20 '13 at 09:37
-1

Your Servlet is sending your json object as String not as Object. So you first have to convert it to JSON Object like

data = eval( '(' + response + ')' );
data["shareInfo"+z].length;
user160820
  • 14,866
  • 22
  • 67
  • 94
  • Never use `eval` to parse JSON. – Quentin Mar 20 '13 at 09:16
  • I don't think this is the problem, as he is referring to data.loops. Converting a string to JSON should be done using JSON.parse. – SteveP Mar 20 '13 at 09:20
  • Try to use [JSON.parse](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse) or [jQuery.parseJSON](http://api.jquery.com/jQuery.parseJSON/) rather then [eval](http://stackoverflow.com/questions/1843343/json-parse-vs-eval). – Stefan Mar 20 '13 at 09:20
  • That's right. But `data.shareInfo["whocommented"+i]` works fine. –  Mar 20 '13 at 09:21
  • @Quentin: Why should one never use eval? funny comment. – user160820 Mar 20 '13 at 09:40
  • @user160820 — At best it is slow, at worst it is a security risk. – Quentin Mar 20 '13 at 09:43
  • @SteveP: Are you sure about Browsers native JSON support? – user160820 Mar 20 '13 at 09:43
  • @Quentin: Security risk, when you are getting data from your own Server :) It should not be used when you are getting data from third party services. – user160820 Mar 20 '13 at 09:45
  • http://stackoverflow.com/questions/891299/browser-native-json-support-window-json – SteveP Mar 20 '13 at 10:09
-1

Make a smaller and easier structure before you start modifying the DOM elements.

Here is an example using jQuerys $.each() function;

var data = {
    loops: {
        "shareInfo1": [
            {
                "uname": "xyz",
                "image": "iVBO..",
                "imname": "ryty",
                "senderPicture": "iVBOR"
            },
            {
                "uname": "abc",
                "image": "iVBO..",
                "imname": "smile",
                "senderPicture": "iVBOR"
            }
        ],
        "shareInfo2": [
            {
                "uname": "sds",
                "image": "iVBO",
                "imname": "happy",
                "senderPicture": "iVBOR"
            }
        ]
    }
};

console.log('data', data); // DEBUG

// Iterating the data
$.each(data.loops, function(key, shareInfo) {
    console.log('shareInfo', key, shareInfo); // DEBUG

    $.each(shareInfo, function(key, user) {
        console.log('user', key, user); // DEBUG

        // Username: user.uname
    });

});
Stefan
  • 5,644
  • 4
  • 24
  • 31
  • Thanks, for giving idea. You provided method for `response data` worked for me.... –  Mar 20 '13 at 13:31