Search code examples
ajaxjsondropdownlistfordancer

Populate dropdown using ajax in Dancer framework


I am using Dancer module to get data as :

any [ 'ajax', 'get' ] => '/textbook' => sub {
    set serializer => 'JSON';
    @textbooks = [{id => '1', name => "text1"},{id => '1', name => "text1"}...];
    return { 'text_list'  => \@textbooks;
};

I have following code in my textbook.tt file :

           <select id="textbook">
           <option value="">Please Select</option>
          </select>

and in js file

$(function() {

$.ajax({
    type: "GET",
    url:"/textbook",
    dataType: "json",
    success: function (data) {
        $.each(data.aaData,function(i,data)
        {
         alert(data.value+":"+data.text);
         var div_data="<option value="+data.value+">"+data.text+"</option>";
        alert(div_data);
        $(div_data).appendTo('#textbook');
        });
        }
  });

});

But this don't load the entries automatically when page loads. Please help


Solution

  • I think there are several bugs in your JS.

    Bug #1: First of all, you're not referring to text_list, you're referring to an unknown element 'aaData'.

    Instead of this:

    $.each(data.aaData,function(i,data)
    

    Try this:

    $.each(data.text_list, function(i, data)
    

    Bug #2: Within the iteration loop, 'data' is the hashref within your array. Therefore, 'data.value' and 'data.text' will not work. You should use 'data.id' and 'data.name', as you specified within your Dancer code.

    Instead of:

    var div_data="<option value="+data.value+">"+data.text+"</option>";
    

    Try this:

    var div_data="<option value="+data.id+">"+data.name+"</option>";
    

    Lastly, for readability, suggest changing 'data' to something else outside of your each.

    Instead of this:

    success: function (data) {
    ...
    $.each(data.text_list, function(i, data)
    

    Use this:

    success: function (response) {
    ...
    $.each(response.text_list, function(i, data)
    

    Likewise, I would consider changing 'data' to something a little more readable such as 'textbook'.

    Good luck, don't forget to "accept" if my answer works for you.