javascriptjqueryajaxjquery-ui-selectable

Fill jQuery UI selectable by AJAX call


I am working on filling a jQuery selectable via AJAX call. I have prepared server side API, which has been tested will return serialized jason object.

I have declared the selectable at client side

<ol id="selectable"></ol>

Then I have a button will trigger the AJAX call to get data.

$.ajax({
    url: '/api/XXX/XXX,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    //error: OnAjaxError,
    success: function (data) {

    }
});

button.onclick = function () {
    $("#selectable").selectable({
      //here to fill the selectable list
    });                
}

I searched via Google but most of the case I found were predefined the list at client side.

Then how I render the list after I got my data?


Solution

  • Do a loop of your returned data from the server and build li tags dynamically into your ol tag and then apply the plugin.

    $.ajax({
        url: '/api/XXX/XXX,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        //error: OnAjaxError,
        success: function (data) {
           $.each(data,function(){
             $("#selectable").append('<li>'+this.Name+'</li>');
             //here I am using data.item change it to whatever your server is returning and what you have to show in the li tags
           });
           $("#selectable").selectable(); //apply the plugin
        }
    });