10

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:

[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]

in my success callback I have tried accessing as json.status and json[0][0] but it always returns "undefined". what am I doing wrong?

function getSysinfo(source) {
    var json = null;
    $.ajax({
        url: source,
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            json = eval("(" + data + ")");
            $('#data').html(json.status);
            alert(json[0][0]);
            refreshChart(json);
        },
        error: function (request, status, error) {
            alert("REQUEST:\t" + request + "\nSTATUS:\t" + status + 
                  "\nERROR:\t" + error);
        }
    });
    return json;
}

I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.

1
  • i gave some answer which can be used in your case, there are already methods availbe like getJSON which takes care of all the issues, and you can just loop through Commented Dec 12, 2010 at 22:53

8 Answers 8

15

To access that status value you would need:

data[4].status

This is because it is an object stored in the the fifth element in an array, with status being a property on the object.

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

1 Comment

ahh - well that makes a little more sense... I didn't really care so much about the status element. I needed the k/v pairs. I was really just experimenting... and I was thinking that data[1].v and data[1][1] were synonymous. thanx.
9

Your JSON-data looks like this:

[
    {
        "k": "label0",
        "v": 0.5
    },
    {
        "k": "label1",
        "v": 99.43
    },
    {
        "k": "label2",
        "v": 2.46
    },
    {
        "k": "label3",
        "v": 46.29
    },
    {
        "status": "OK"
    }
]

You would have to read your status using

json[4].status

with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:

{
    "status": "OK",
    "entries": [ ... ] // add your data here
}

Comments

8

In your success callback try:

var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
    alert( jsondata.k );
    alert( jsondata.v );
});

4 Comments

@lorezo , we have to loop through all the elements right?? what does .k and .v gives??
@gov: you're right!! I've missed the loop part. Edited the answer to reflect this
You don't need to parse the json like this, jQuery will have already parsed it.
thanx guys. this looks promising b/c I need to loop through the data & stuff it into the right places... let me read a little on parseJSON and then I'll play around for a while.
5

You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'

From the jQuery docs for dataType:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

5 Comments

NO. BAD. JSON.parse(). Don't use eval for JSON. BAD.
I'm not advocating using eval. I'm simply saying he doesn't need it. Also JSON.parse is not supported by all browsers (especially older ones). Using something like $.parseJSON that makes an informed decision based on the browser is probably better.
I agree with the eval() part I just wasn't sure what was going on under the hood. Some of the stuff I was googling was from several years ago. I've learned that jQuery 1.4 has it built in so I would only need it if my stream was type='text'.. but I'll hafta look more into parseJSON().
oops sorry- I meant dataType='text'
yeah that did it - I din't even need anything else. I just modified my callback for success to loop through the changes it needed to make. My biggest mistake was thinking that data[0].v was data[0][0] thanks again.
4

no need to use eval any more use below code which can be more for json

$.getJSON(url+query,function(json){
            $.each(json,function(i,value){

            });
        });

2 Comments

That isn't needed, the code in the question will already be parsing the json perfectly happily. Also $.getJSON can only be used for GET requests not POST, as the question is using.
yeah I need POST & ajax() also gives more flexibility with the options. Thanks for the reply, though...
2

nategood already wrote that you don't need do do anything with data, it's already an object.

In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):

  data[data.length-1].status

But maybe you should think about another structure of your JSON, it doesn't look very comfortable.

Something like that:

{
 "items":[
         {"k":"label0","v":0.5},
         {"k":"label1","v":99.43},
         {"k":"label2","v":2.46},
         {"k":"label3","v":46.29}
        ],
 "status":"OK"
}

...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).

2 Comments

I didn't care 2 much about the status, but the k/v pairs... I thought maybe it was needed for the response to trigger the parsing. I was trying to get it into something similar to your structure but inadvertently did and array_push ($jsonData, array("status" => 'OK')); -- on the php side. In any case, I needed the nomenclature to access the array properly...
I DO appreciate your help, though.
1

The data parameter is the decoded JSON as you can see in this example:

http://www.jsfiddle.net/rLprV/1/

Comments

1
$.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: formData,
        showLoader:true,
        success: function (response) {
            var parsed =  JSON.parse(JSON.stringify(response));
            $.each(parsed, function (key, val) {
                alert( val.name );                      
            });
        },
        error: function (err) {
            alert("Please enter a valid id")    
        }
     });

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.