[RESOLVED]$.each not working

I fetch data through WebAPI but the loop using jQuery $.each statement is not working.

<script>
jQuery(document).ready(function () {

$.getJSON('api/testAPI')

.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: item.Productname }).appendTo($('#products')); //<<----each <li> rendered null Frown
});
})
.fail(function (jqXHR, textStatus, err) {
$('#products').text('Error: ' + err);
});
});
</script>
Function GetAllProduct() As IEnumerable(Of ProductList)      
        Dim newLists As New List(Of ProductList)

            Dim products = From b In _db.ProductsNorthWind _
               .Select(Function(c) New With { _
                        .ProductName = c.ProductName,
                        .ProductID = c.ProductID})

            For Each item In products
                newLists.Add(New ProductLists With { _
                              .ProductName = item.ProductName,
                              .ProductID = item.ProductID})
            Next

            Return newLists
    End Function

-imperialx

Use debugger or alert to check data is coming up to line of the code- $.each(). If data is available and $.each is not working, use for loop at place of each as

for(index=0;index<data.length;index++)

{

     $(‘<li>’, { text: data[index].Productname }).appendTo($(‘#products’));

}

SharadTripathi

alert to check data is coming up to line of the code- $.each().

There were 10 records coming from API as there were 10 <li> tags rendered but still below doesn’t work.

$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: data[key].Productname}).appendTo($('#products'));
});
for (index = 0; index < data.length; index++) {

$('<li>', { text: data[index].Productname }).appendTo($('#products'));

}

And to check using Alert(item); it only returns [object Object] on each iteration.

What seems to be the issue?

-imperialx

SharadTripathi

Use debugger

Found it. Using Firebug response from API, I get below

[{"_ProductID":2,"_ProductName":"Chang","_SupplierID":null,"_CategoryID":null,"_QuantityPerUnit":null,"_UnitPrice":null,"_UnitsInStock":null,"_UnitsOnOrder":null,"_ReorderLevel":null,"_Discontinued":false,"_Category":null,"_Order_Details":[],"_Supplier":null},{"_ProductID":3,"_ProductName":"Aniseed Syrup","_SupplierID":null,"_CategoryID":null,"_QuantityPerUnit":null,"_UnitPrice":null,"_UnitsInStock":null,"_UnitsOnOrder":null,"_ReorderLevel":null,"_Discontinued":false,"_Category":null,"_Order_Details":[],"_Supplier":null}]

Notice the preprend "_" undrescore symbol on each object. 

This works now.

$(‘<li>’, { text: item._ProductName }).appendTo($(‘#products’)); //<<<—added "_" becomes _ProductName

Why API added "_" underscore symbol???

Leave a Reply