3

I have the following JSON data that is returned from a WCF RESTful Service.

{"Cities":["LUSAKA","HARARE"],"Countries":["ZAMBIA","ZIMBABWE"]}

I am attempting to populate the following HTML Table with this data.

<table id="location" border='1'>
    <tr>
        <th>Countries</th>
         <th>Cities</th>
    </tr>
</table>

The below code works, however, it relies on the index of either the Countries or the Cities and I cannot access the data from the item variable in the anonymous function.

var trHTML = '';

$.each(data.Countries, function (i, item) {

trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';

});

$('#location').append(trHTML);

However if I attempt to access the data like this it does not work:

$.each(data.d.results,function(d, item){ 

    $("#location tbody").append(
                "<tr>"
                  +"<td>"+item.Countries+"</td>"
                  +"<td>"+item.Cities+"</td>"
                +"</tr>" )
            })

How do I access the data using the item variable in the loop function above?

Here is the complete working code:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>WCF Client</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

</head>

<body>

<table id="location" border='1'>
    <tr>
        <th>Countries</th>
         <th>Cities</th>
    </tr>
</table>

<script>

var service = 'http://localhost/DistributedDataSystem/Service.svc/';

$(document).ready(function(){

    jQuery.support.cors = true;

    $.ajax(
    {
        type: "GET",
        url: service + '/GetAllCountries/',
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {

        var trHTML = '';

        $.each(data.Countries, function (i, item) {

            trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';
        });

        $('#location').append(trHTML);

        },

        error: function (msg) {

            alert(msg.responseText);
        }
    });
})

</script>

</body>
</html>
2

1 Answer 1

6

Since you have 2 separate arrays Countries and Cities, there's no unified collection of items that each has a Countries and a Cities property.

Also in your modified code you are trying to use each on data.d.results which I would expect to be undefined based on the sample data you provided. Overall, you could probably improve your code by appending individual rows, but there's no useful item that has both values you need.

If you have control of the JSON data you could restructure it as follows:

[{City:"LUSAKA",Country:"ZAMBIA"},{City:"HARARE", Country: "ZIMBABWE"}]

Then access it like this:

$.each(data,function(i,item){
    $("#location tbody").append(
        "<tr>"
            +"<td>"+item.Country+"</td>"
            +"<td>"+item.City+"</td>"
        +"</tr>" )
    })
Sign up to request clarification or add additional context in comments.

5 Comments

Very helpful explanation. I am unsure how I could return a list of both Countries and Cities. I could simply append both pieces of data to a List but will that work? In a nutshell I want to return a JSON data containing Countries and Cities so that each is in a separate column?
Check out my edited answer for the desired structure of the JSON.
Got it! Yes I have access to the Web Service code. I'll attempt to modify the return JSON formatted data to the above. Thanks a million!
Great. I'm not super familiar with WCF but I'd guess you'll want to serialize a List<TItem> where TItem is a class with Country and City properties
Perfect!! I was able to Serialized the Class and return the formatted JSON data just as you illustrated above, tested the code and it works as required. Thank you so much, you just made my evening. :) On another note: I will be posting a new question on how I can generate the table and columns using the data fields as headers, instead of manually writing the initial table.

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.