user1964234 user1964234 - 3 months ago 7
jQuery Question

Use jQuery to get value from this JSON string

Seems like this should be easy!

I am submitting a form via jQuery/ajax and the success output is a JSON sting like this:

{"activities-tracker-steps":[{"dateTime":"2016-09-06","value":"0"}]}


All I want to do is get the value (in this case 0). So, I try this:

submitHandler: function() {
var postData = $("#form").serializeArray();
var formURL = $("#form").attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success : function(data) {
var json;
json = $.parseJSON(data);
alert(json['value']);
$('#form').trigger("reset");
$("#success").show().fadeOut(3000);
},
error : function() {
$("#fail").show().fadeOut(3000);
}
});
}


Undefined, apparently. What am I doing wrong!?

Many thanks for your thoughts,

Answer

As per provided structure you can fetch value by json['activities-tracker-steps'][0].value as mentioned below.

submitHandler: function() {
        var postData = $("#form").serializeArray();
        var formURL = $("#form").attr("action");
        $.ajax({
            url : formURL,
            type: "POST",
            data : postData,
            success : function(data) {
                var json;
                json = $.parseJSON(data);
                alert(json['activities-tracker-steps'][0].value);
                $('#form').trigger("reset");            
                $("#success").show().fadeOut(3000);
            },
            error : function() {
                $("#fail").show().fadeOut(3000);
            }
        });
    }