1

Hi I have a web service which returns data in json format. I am not able to bind the country names and the country code returned from web service. My code is


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Using jQuery and XML to populate a drop-down box demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "get",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({"objectData": formData}),
            url: "127.0.0.1:15021/Service1.svc/getallcustomers",
            dataType: "json",
            success: ajaxSucceess,
            error: function(xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(xhr.responseText);
                alert(thrownError);
            }
            //error: ajaxError
        });

        function ajaxSucceess(response) {
            $.each(response.d, function(key, value) {
                $("#ddlCountry").append($("<option>       </option>").val(value.country_code).html(value.country_name));
            });
        }
        function ajaxError(response) {
            alert(response.status + ' ' + response.statusText);
        }
    });
</script>

my html code is

<body> 
    <div>
        <select id="ddlCountry"> 
            <option value="-1">loading</option> 
        </select>
    </div>
</body>
</html>

sample json data returned from web services

// correct json format

{
    "GetAllCustomersResult": [
        {
            "country_code": "OT",
            "country_desc": "Other",
            "country_name": "Other",
            "country_sk": "-1",
            "country_telecom_code": "+1",
            "currency_sk": 225,
            "date_format": "mdy",
            "distance_measurement_unit": null,
            "fnb_type_sk": "",
            "is_sms_notification": null
        },
        {
            "country_code": "ZW",
            "country_desc": null,
            "country_name": "Zimbabwe",
            "country_sk": 239,
            "country_telecom_code": "263",
            "currency_sk": 11,
            "date_format": null,
            "distance_measurement_unit": null,
            "fnb_type_sk": "",
            "is_sms_notification": null
        }
    ]
}
Anjith K P
  • 2,158
  • 27
  • 35
user1778878
  • 17
  • 1
  • 2
  • 6

4 Answers4

1

You need to push the values while appending to the select box in a proper format.

    <title>Using jQuery and XML to populate a drop-down box demo</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
    $.ajax({
    type: "get",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ "objectData": formData}),
    url: "127.0.0.1:15021/Service1.svc/getallcustomers",
    dataType: "json",
    success: ajaxSucceess,
    error: function (xhr, ajaxOptions, thrownError) {
               alert(xhr.status);
               alert(xhr.responseText);
               alert(thrownError);
           }
    //error: ajaxError
    });

    function ajaxSucceess(response) {
    $.each(response.d, function (key, value) {
//Assuming key is the country code and value is country name in the this function.
appendString= "<option value='"+key+"'>"+value+"</option>";
    $("#ddlCountry").append(appendString);
    });
    }
    function ajaxError(response) {
    alert(response.status + ' ' + response.statusText);
    }
    });
    </script>

EDITED CODE: THIS IS A WORKING CODE AS TESTED

    $(document).ready(function () {
        response = '{"GetAllCustomersResult":[{"country_code":"OT","country_desc":"Other","country_name":"Other","country_sk":-1,"country_telecom_code":"+1","currency_sk":225,"date_format":"mdy","distance_measurement_unit":null,"fnb_type_sk":"","is_sms_notification":null},{"country_code":"ZW","country_desc":null,"country_name":"Zimbabwe","country_sk":239,"country_telecom_code":"263   ","currency_sk":11,"date_format":null,"distance_measurement_unit":null,"fnb_type_sk":"","is_sms_notification":null}]}';
    ajaxSucceess(response);
    });

function ajaxSucceess(response) {

  responseJSON = $.parseJSON(response);
        console.log(responseJSON);
    $.each(responseJSON, function (key, value) {
        currentObj = $(this);
        $.each(currentObj,function(key,value)
               {
                   console.log(value);
                   country_code = value.country_code;
                   country_name = value.country_name;
                   appendString = "<option value='"+country_code+"'>"+country_name+"</option>";
                   $("#ddlCountry").append(appendString);
               });
//Assuming key is the country code and value is country name in the this function.

    });
    }
    function ajaxError(response) {
    alert(response.status + ' ' + response.statusText);
    }
Akhilesh Sharma
  • 1,580
  • 1
  • 17
  • 29
0

This might help you out.

function ajaxSucceess(response) {
    var options = "";
    $.each(response.d, function (key, value) {
        options+= '<option vlaue="'+value.country_code+'">'+value.country_name+'</option>';
    });
    $("#ddlCountry").html(options);
}
Anubhav Ranjan
  • 1,558
  • 3
  • 18
  • 32
0

try creating the option without the closing tag. JQuery will evaluate it to a DOM element

$('<option />').val('Your value').html('html inside');

a quick test in chrome developer tools

var a = $('<option />').val('a').html('the a');
$('<select />').append(a);

appends the value into the select tag.

UPD: have you tried looking at the keys and the values in the developer console? you might have an error parsing the result. put a breakpoint, analyze the result.

Igarioshka
  • 677
  • 3
  • 14
0

Try jsonp as dataType in ajax:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {$.ajax({
        type: "get",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({"objectData": 'formDataText'}),
        url: "http://doctor2book.com/service1.svc/getallcountries?callback=?",
        jsonpCallback: 'callbackParseJSON',
        crossDomain: true,
        dataType: "jsonp",
        success: successResponse,
        error: errorResponse
});// end ajax

// callback function form web services json data
function callbackParseJSON(response){
    alert('Callback Function called.');
}
// success function
function successResponse(response){
// get response data from web services
alert('Success!!');
// parse json data from web services
$.each(response.GetAllCustomersResult, function (key, value) {
    var appendData = "<option value='" + value.country_code + "'>" + value.country_name + "</option>";
    $("#ddlCountry").html($("#ddlCountry").html() + appendData);
});
}

// ajax error function
function errorResponse(xhr, ajaxOptions, thrownError) {
    alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);                
}

});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSONP Demo</title>
</head>

<body>    
        <select id="ddlCountry"> 
            <option value="-1">loading</option> 
        </select>          
</body>
</html>
Nono
  • 6,986
  • 4
  • 39
  • 39
  • thank for quick replies I have checked my web service data. on jasonlint.com it gives output as valid jason. @neeraj singh – user1778878 Jun 06 '13 at 10:18
  • thank for code it works for me for hard coded json data but when I try to access the json data through web services i get nothing, I dont know what is going wrong. this is my web service url pls see what can be done http://doctor2book.com/service1.svc/getallcountries @neeraj singh – user1778878 Jun 06 '13 at 10:29
  • above script is running for me, i check it with an ajax event and I haven't any issue with your sample json data. – Nono Jun 06 '13 at 10:30
  • @user1778878: Bro!! use dataType:'jsonp' instead of dataType:'json' in ajax. I think your domain and ajax request not in same domain. – Nono Jun 06 '13 at 10:44
  • yaa that's correct, but I cannot pass hard-coded json data, I have to get the data through web service url can you pls check it once with the web service url I have provided and find where is the problem. @neeraj singh – user1778878 Jun 06 '13 at 10:48
  • on my local 1. my web service returnign json data url is http://127.0.0.1:15021/service1.svc/getallcountries or http://localhost:15021/service1.svc/getallcountries I am developing mobile app where country state city are bound together to drop down. I am using Aptana studio for code development and for output I am using ripple emulator (which is chrome plugin) for output the url on chrome is http://127.0.0.1:8020/Project_Hello/New%20folder/chapter19/Ex19-1/test.html, pls see what can be done. I want to know where is cross domain issue @neeraj singh – user1778878 Jun 06 '13 at 11:14
  • @user1778878: check this link http://stackoverflow.com/questions/7391707/jquery-ajax-with-jsonp-not-invoking-success-callback-function and http://stackoverflow.com/questions/13424884/unable-to-read-data-from-ajax-datatypejsonp-call-to-web-service . u needs some modification in your web services. – Nono Jun 06 '13 at 12:08
  • @user1778878: Check my edited answer, hope it will help you after alter your web services. – Nono Jun 06 '13 at 12:28
  • I just copied your code as it is hey neeraj I am getting error like "error on ajax call status:200 response text: undefined error:error:callbackParseJSON was not called" @neeraj singh – user1778878 Jun 06 '13 at 13:05
  • @user1778878: you must have add callback function name with your web services data. Read this carefully http://stackoverflow.com/questions/5943630/basic-example-of-using-ajax-with-jsonp – Nono Jun 06 '13 at 13:17
  • @user1778878: read this also http://stackoverflow.com/questions/2887209/what-are-the-differences-between-json-and-jsonp – Nono Jun 06 '13 at 13:39
  • thanks neeraj, after editing my web.config to allow cross domain, finally got success.@neeraj singh – user1778878 Jun 07 '13 at 10:49
  • hey neeraj I have finally binded my web service url for countries. Now I am binding state and city names according to country. but state and city are on another web service url, where can I include this in my code. @neeraj singh – user1778878 Jun 07 '13 at 11:00
  • @user1778878: Hi! :) Congrats!! You can bind multiple web service url as u want, u just needs to send url and ajax success as input param in ajax controll. you can write an ajax code and set all the input param inside ajax code. the u can send dynamically parameter to ajax. I hope u got me.. – Nono Jun 10 '13 at 07:33