Xtremcool Xtremcool - 1 month ago 9
HTML Question

Through ajax not able to fill HTML dropdown

<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/Umbraco/api/RegisterUser/GetCountry',
type: 'GET', // You can use GET
data: '{}',
dataType: "json",
context: this,
success: function (data) {
alert(data);

$.each(data, function (key, item) {
$('#ddcountry').append(
$("<option></option>")
.attr("value", item.Country_name)
.text(item.Country_name)
);
});

alert("success");
},
error: function (request) {
alert("error");
}
});
});




My code return on URL path is

[HttpGet]
public string GetCountry()
{
String daresult = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataTable dt1=new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT countryid,country_name FROM country_master", UmbracoConnectionString))
{
da.Fill(dt1);
}

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(10);
Dictionary<string, object> row;

foreach (DataRow dr in dt1.Rows)
{
DataRow[] dr1 = dt1.Select("countryid=" + dr["countryid"]);
if (dr1.Count() > 0)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt1.Columns)
{
if (col.ColumnName == "country_name")
{
row.Add(col.ColumnName, dr[col]);
}

}
rows.Add(row);
}
}
return serializer.Serialize(rows);
}


My HTML code is below where i had inserted some of the data manually

Country:<select id="ddcountry">
</select>


But by doing all this things **how should I fill my dropdown with retriving data as data shown in below image

On alert of data i am getting data as below

enter image description here

Answer

I guess, It will solve your issue:

First, You need to convert your JSON String to JSON Array and Then Iterate it to dynamically create options for your select dropdown.

var res = jQuery.parseJSON(data);

$.each(res , function (key, item) {
    $('#ddcountry').append(
        $("<option></option>")
          .attr("value", item.country_name)
          .text(item.country_name)
    );
});