Skip to content
Advertisement

Parsing JSON returned via an AJAX POST formating issue

I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:

//json return
$return["answers"] = json_encode($result);
echo json_encode($return);

This returns the following string:

answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]" 

And this is where I am trying to catch it to use the data:

$.ajax({
            type: "POST",
            url: "http://ldsmatch.com/pieces/functions/question.functions.php",
            dataType : 'JSON',
            data: dataString,
            success: function(data) {
                alert(data.answers[0]["aa"]);
            }       
        });

I’ve been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.

If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.

I have tried other variations, such as:

data.answers[0]["aa"]   (this returns 'undefined' in the alert)
data.answers["aa"]      (this returns 'undefined' in the alert)
data.answers[0]         (this returns the first character of the string)

I feel like I’m close, but missing something. Any guidance appreciated.

edit:

thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa

Advertisement

Answer

success: function(data) { var json = $.parseJSON(data); alert(json.answers[0][“aa”]); }

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement