0

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?

3
  • Show us also your JSON output, for every case. Commented Feb 24, 2013 at 9:37
  • 1
    Sounds like when you receiving multiple languages you're getting an array of objects and when it's only one language it's single JSON object Commented Feb 24, 2013 at 9:53
  • I edited the question with json output Commented Feb 24, 2013 at 10:41

1 Answer 1

1

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();                            
            }
        });
    });        
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Gajotres for your response. but I dont have control on json output... is there any solution from html/jquery side?
Take a look at my answer, I have added an EDIT part. There's an if inside a success, it will determine if output.geographyInfo is an array or a single element.
hey thank you again, just one question what is typeof variable_here? I am using jquery mobile...
typeof output.geographyInfo.length will check if output.geographyInfo is an array. So in case !== 'undefined' it is an array then use your original method, in case === 'undefined' it is not an array then use it as an single JSON element. And that is a pure javascript.

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.