0
<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

  • 2
    Have you checked the request in the console? The URL looks odd. – Rory McCrossan Oct 17 '16 at 13:15
  • ohk on removing static I am able to get success, now how should i feel my dropdown –  Oct 17 '16 at 13:16
  • @RoryMcCrossan I think he is using MVC – Jonathan Newton Oct 17 '16 at 13:16
  • @Xtremcool http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery – Jonathan Newton Oct 17 '16 at 13:17
  • @Xtremcool Also: http://stackoverflow.com/questions/2637694/how-to-populate-a-dropdownlist-with-json-data-in-jquery – Mic Oct 17 '16 at 13:17
  • 2
    @JonathanNewton Yep, but my point was that he seems to have two actions in the URL: `RegisterUser` and `GetCountry` – Rory McCrossan Oct 17 '16 at 13:22
  • @RoryMcCrossan ah spot on! – Jonathan Newton Oct 17 '16 at 13:24
  • @RoryMcCrossan its an actual path not an issue in that, on succes i am getting data as {"Table1":[1,"abc"],[2,"abc1"],[3,"abc2",null]} but not able to fill the dropdown –  Oct 17 '16 at 13:44
  • Any one help please? –  Oct 17 '16 at 14:06
  • What's the output of `/Umbraco/api/RegisterUser/GetCountry` looks like? It may not be well formatted JSON object. – SaidbakR Oct 17 '16 at 14:25
  • @sємsєм updated the question, I am receiving data as shown in image –  Oct 17 '16 at 14:38
  • Any how now i am able to get different type of record and i want to show countryname only, now any help? –  Oct 17 '16 at 15:27
  • @sємsєм I am using Umbraco, in that i am using HTML control –  Oct 17 '16 at 16:47
  • @Xtremcool It is very nice to find a solution for your question, what I have meant by the output, is the output printed in the browser not the alert message. i.e visiting `yoursite.com/Umbraco/api/RegisterUser/GetCountry`. However, the string shown in the alert screen shot, is not correct JSON object. Any JSON object should start with curly braces. – SaidbakR Oct 17 '16 at 18:28
  • 1
    @sємsєм actually at different places ajax are being called so i m just following same syntax, I will take care now on wards –  Oct 17 '16 at 18:50

3 Answers3

1

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)
    );
});
gschambial
  • 1,383
  • 2
  • 11
  • 22
  • and instead of response i have to put data, and other all things would be saame? –  Oct 17 '16 at 13:28
  • well i have tried and its showing only old record like vovo, saab and all that , not the country name –  Oct 17 '16 at 13:31
  • @Xtremcool There is problem with your JSON data. I have created a fiddle to demonstrate the same. https://jsfiddle.net/gschambial/25ndL3pv/2/ Can you check and confirm? – gschambial Oct 17 '16 at 16:20
  • @Xtremcool i have updated my answer and fiddle as well. You can check. I guess it will work for you. – gschambial Oct 17 '16 at 16:25
  • @gschanbial i have also updated my question from your code please review my json data and succes code, its showing blank over there –  Oct 17 '16 at 16:27
  • You have used `item.id`, instead you should use `item.country_name`. Have you checked the fiddle? – gschambial Oct 17 '16 at 16:29
  • @Xtremcool on `alert`, JSON data is coming in right format. I can see from screenshot. – gschambial Oct 17 '16 at 16:31
  • Yes also see success part there also i had implement your fiddle code, but my dropdown is showing blank –  Oct 17 '16 at 16:32
  • `ddcountry` empty select dropdown is present in your HTML code before executing AJAX call or you need to create it dynamically ? @Xtremcool – gschambial Oct 17 '16 at 16:34
  • @Xtremcool Remove `alert` statements from your code and run once. – gschambial Oct 17 '16 at 16:38
  • yes ddcountry empty select dropdown is present in my HTML code before exceuting ajax call –  Oct 17 '16 at 16:38
  • @Xtremcool Have you tried after removing `alert` statmements? – gschambial Oct 17 '16 at 16:43
  • I have tried removing alert statement still not working –  Oct 17 '16 at 16:47
  • @Xtremcool can you check developer console? if you are getting any errors? – gschambial Oct 17 '16 at 16:52
  • error like XMLHttpRequest cannot load http://catcher.gourmetads.com/pub.php?pid=859. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:59462' is therefore not allowed access. but i dont think so it is related to this –  Oct 17 '16 at 16:56
  • 1 more error Uncaught TypeError: $R(...).tiles is not a function but this come before ajax runs –  Oct 17 '16 at 16:59
  • @Xtremcool Is your `document.ready` code at bottom of the page or in the `head` section? – gschambial Oct 17 '16 at 17:06
  • its is on head section –  Oct 17 '16 at 17:09
  • @Xtremcool Ohh, i see. Just move it to the bottom of your page, before `body` section ends. It will work. – gschambial Oct 17 '16 at 17:12
  • done still not working, but we can make it write any where i think so, 1 more thing I am using umbraco but in that case i am calling other function and they totally are working well. I have issue in this case only, yesterday i had tried sending data through ajax and it is also working well. U can also see my updated code on which i am trying –  Oct 17 '16 at 17:17
  • @Xtremcool actually, it will not work if you place it at the head section because, your page at that stage is not rendered completely. Therefore, `ddcountry` dropdown will not be visible inside your AJAX success callback. Though, i will check yiur update. – gschambial Oct 17 '16 at 17:21
  • @Xtremcool I think data is a json string not json object in your example. So, can you just add `data = jQuery.parseJSON(data);` before creating `select`. It will convert your JSON string into JSON Object. I have updated the answer also. Check and Confirm. – gschambial Oct 17 '16 at 17:29
  • u mean var res = jQuery.parseJSON(data); $.each(res, function (key, item) { $('#ddcountry').append( $("") .attr("value", item.Country_name) .text(item.Country_name) ); }); still not working –  Oct 17 '16 at 17:34
  • @Xtremcool You are writing `Country_name` here? Character `C` is not capital in your JSON, change it to `item.country_name` with `c` small character. – gschambial Oct 17 '16 at 17:37
  • Yes now its working fine thanks, please update your answer so that i make it done –  Oct 17 '16 at 17:40
  • @Xtremcool My pleasure. I have update the answer. You can mark it as done. – gschambial Oct 17 '16 at 17:43
0

Something like this in the success section:

                $.each(data, function(i, item) {
                    $('#yourDiv').find('#yourSelect')
                    .append($('<option>', { value: item['yourID'], 
                                           text: item['yourText'] }));
                });

Also try doing this in your class:

//daresult = DataSetToJSON(ds);
return Json(daresult);
Neo
  • 3,309
  • 7
  • 35
  • 44
  • I had tried doing success: function (data) { $.each(data, function (i, item) { $('#ddcountry').append($(' –  Oct 17 '16 at 13:23
  • Have you set a break point to see that you are actually getting data back from the call? Is the URL correct? – Neo Oct 17 '16 at 13:24
  • on doing alert(data); in success i am getting proper data –  Oct 17 '16 at 13:26
  • Set a break point on your call to public string GetCountry() as see that you are reaching the server. – Neo Oct 17 '16 at 13:27
  • on doing alert(data); in success i am getting proper data {"Table1":[1,"abc"],[2,"abc1"],[3,"abc2",null]} –  Oct 17 '16 at 13:36
  • 1
    JSON format what ever you are getting not correct ... correct format is.. { "Table1": {[1, "abc"], [2, "abc1"], [3, "abc2", null]} } – BEJGAM SHIVA PRASAD Oct 17 '16 at 14:20
  • Yes I think you should let .NET do the work. See my updated answer. – Neo Oct 17 '16 at 14:22
  • But the data I am receiving is correct earlier my code retrieving json format was not correct so i had updated the code and now mu updated json format is like –  Oct 17 '16 at 16:54
0

try this

$(document).ready(function () {
    $.ajax({
        url: '/Umbraco/api/RegisterUser/GetCountry',
        type: 'GET', // You can use GET
        data: '{}',
        dataType: "json",
        context: this,                
        success: function (data) {
            var options = "";
            $.each(data, function(i, item) {
                options += '<option value="'+item.id+'">'+item.label+'</option>';
            });
            $('#ddcountry').append(options);
        },
        error: function (request) {
            alert("error");
        }
    });

});
Syed Arif Iqbal
  • 1,830
  • 12
  • 16
  • Tried putting this, data is filling as undefined –  Oct 17 '16 at 13:34
  • I have tried putting this as options += ''; still undefined is coming –  Oct 17 '16 at 13:38
  • on doing alert(data); in success i am getting data as {"Table1":[1,"abc"],[2,"abc1"],[3,"abc2",null]} –  Oct 17 '16 at 13:40
  • what is your data return from ajax request – Syed Arif Iqbal Oct 17 '16 at 13:45
  • from code in am retriving country id an country_name and on converting it to JavaScriptSerializer i am getting data as {"Table1":[1,"abc"],[2,"abc1"],[3,"abc2",null]} –  Oct 17 '16 at 13:49