Ali
Ali

Reputation: 1678

Parsing JSON using foreach in JQuery

This is code I'm using right now to do AJAX via JQuery:

       $.ajax({
            type: "POST",
            url: linktopage,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $.each(data, function (index, item) {
                    alert(item.productId);
                });
            },
            error: function (xhr, status, error) {

            }
        });

where index = d and item = "[{"productId":5284598},{"productId":5790923}]" but alert(item.productId) is undefined, how can i access each productId?

Upvotes: 0

Views: 69

Answers (2)

Travis J
Travis J

Reputation: 82297

In your example, there is an array of items. You must iterate that to get to the productId.

for( var i = 0; i < item.length; i++ ){
 console.log(item[i].productId);
}

edit

It is possible that your data is still a string, in which case, you may want to use

data = JSON.parse(data);

before iterating. (more on parse: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse )

like this (you could also test to see if it were a string first):

$.ajax({
        type: "POST",
        url: linktopage,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            if( typeof data == "string" )data = JSON.parse(data);
            $.each(data, function (index, item) {
                alert(item.productId);
            });
        },
        error: function (xhr, status, error) {

        }
});

Upvotes: 1

Wolf
Wolf

Reputation: 2150

The data is a string entry in your case. So you have to parse it to a JSON first. Update you code to this

$.ajax({
            type: "POST",
            url: linktopage,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var dta = $.parseJSON(data);
                $.each(dta , function (index, item) {
                    alert(item.productId);
                });
            },
            error: function (xhr, status, error) {

            }
        });

Upvotes: 1

Related Questions