Pratik Mehta
Pratik Mehta

Reputation: 1352

Parse JSON output issue

I am calling service to get languages based on country. when it returns multiple languages my following code is working fine.. but when it returns only one record the output is not coming correctly(coming as "indefined".. please advice.

here is my code:

$.ajax({
            type: 'POST',
            url: "http://mymethod",
            complete: function () { $.mobile.hidePageLoadingMsg(); },
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                "country": countryCode
            }),
            success: function (output, textStatus, jqXHR) {
                $.each(output.geographyInfo, function (i, theItem) {
                    try {
                        languages.push("<option value='" + theItem.languageCode + "'>" + theItem.languageName + "</option>");
                    }
                    catch (error) {
                        alert(error);
                    }
                });
                $(languages.join('')).appendTo("#dpdLanguages").trigger("create");
            }
        });

here is the json output.

here is the output when only one language:

{"geographyInfo":{"active":"true","countryCode":"US","countryName":"UNITED STATES","instanceID":"1","languageCode":"EN","languageName":"English","regionName":"North America"},"reasonDetails":null,"size":"1","status":"true"}

and in multiple cases

{"geographyInfo":[{"active":"true","countryCode":"CA","countryName":"CANADA","instanceID":"1","languageCode":"EN","languageName":"English","regionName":"North America"},{"active":"true","countryCode":"CA","countryName":"CANADA","instanceID":"1","languageCode":"FR","languageName":"French","regionName":"North America"},{"active":"true","countryCode":"CA","countryName":"CANADA","instanceID":"2","languageCode":"EN","languageName":"English","regionName":"Americas"}, {"active":"true","countryCode":"CA","countryName":"CANADA","instanceID":"2","languageCode":"FR","languageName":"French","regionName":"Americas"}],"reasonDetails":null,"size":"4","status":"true"}

yes udidu, i think thats the case.. but how to solve this?

Upvotes: 0

Views: 498

Answers (1)

Gajotres
Gajotres

Reputation: 57309

Easiest solution here would be, in case you have only one geographyInfo element to wrap it in [], like this:

{"geographyInfo":[{"active":"true","countryCode":"US","countryName":"UNITED STATES","instanceID":"1","languageCode":"EN","languageName":"English","regionName":"North America"}],"reasonDetails":null,"size":"1","status":"true"}

Because of this it will act as an one element array, and you are not going to need to change your code. Currently when there's only one geographyInfo element each loop will show inner geographyInfo items as separate array elements and it will loop 7 times.

Here's a working example:

index.html :

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>    
    <script>
        $(document).on('pagebeforeshow', '#index', function(){     
            $('#populate-button').on('click',function(e,data){     
                $('#dpdLanguages').empty()
                $.ajax({
                    type: 'POST',
                    url: "json.php",
                    complete: function () { $.mobile.hidePageLoadingMsg(); },
                    dataType: "json",
                    contentType: 'application/json',
                    data: "",
                    success: function (output, textStatus, jqXHR) {
                        $.each(output.geographyInfo, function (i, theItem) {
                            try {
                                $('<option>').attr('value',theItem.languageCode).html(theItem.languageName).appendTo("#dpdLanguages");
                            }
                            catch (error) {
                                alert(error);
                            }
                        });
                        $('#dpdLanguages').selectmenu();  
                    }
                });
            });        
        });
    </script>
</head>
<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
        </div>

        <div data-role="content">
            <a href="#" data-role="button" id="populate-button">Load JSON data</a>
            <select id="dpdLanguages"></select>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>    
</body>
</html>   

jsop.php :

<?php
    echo '{"geographyInfo":[{"active":"true","countryCode":"US","countryName":"UNITED STATES","instanceID":"1","languageCode":"EN","languageName":"English","regionName":"North America"}],"reasonDetails":null,"size":"1","status":"true"}';    
?>

EDIT :

In case you can't change your JSON code this will work as well:

$(document).on('pagebeforeshow', '#index', function(){     
    $('#populate-button').on('click',function(e,data){     
        $('#dpdLanguages').empty()
        $.ajax({
            type: 'POST',
            url: "json.php",
            complete: function () { $.mobile.hidePageLoadingMsg(); },
            dataType: "json",
            contentType: 'application/json',
            data: "",
            success: function (output, textStatus, jqXHR) {
                if(typeof output.geographyInfo.length !== 'undefined') {                                      
                    $.each(output.geographyInfo, function (i, theItem) {
                        try {
                            $('<option>').attr('value',theItem.languageCode).html(theItem.languageName).appendTo("#dpdLanguages");
                        }
                        catch (error) {
                            alert(error);
                        }
                    });
                } else {
                    $('<option>').attr('value',output.geographyInfo['languageCode']).html(output.geographyInfo['languageName']).appendTo("#dpdLanguages");
                }
                $('#dpdLanguages').selectmenu();                            
            }
        });
    });        
});

Upvotes: 1

Related Questions