Search code examples
jsonjqueryhandsontable

Assign array of strings from JSON to Handsontables object in javascript?


I am trying to assign array of string to handsontables column as auto-complete. I am getting this JSON data from AJAX calls.

I am not getting to assign to source:. Please follow the code.

    var loadBU = function(data) {          
                $.ajax({
                 url: "/EditInitiatives.svc/GetBUData",
                 data: "clientId=" + $value.val(),
                 type: "GET",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function (res) {                      
                     data(res);
                 },
                 error: function (error) {
                     alert("Error: " + error.responseText);
                 }
                });    
              };    

    $("#example2").handsontable({
        data: getCarData(),
        startRows: 7,
        startCols: 4,
        columns: [
                  {  data:'BusinessUnit',
                     type:'autocomplete',
                     source:loadBU(function(output){                            
                               var results = output.d                         
                               var arr = [], item;
                               for (var i = 0, len = results.length; i < len; i++) {
                                    item = results[i];
                                    arr.push([[item]]);
                                }
                                return arr;
                            }),      
                        strict: true
                     },
               ]
       });

It suppose to be like that EX: source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"],

enter image description here

I don't understand how to assign array to source.

Reference


Solution

  • Your "return arr;" does not return to the "source:", it returns to the "loadBU" function.

    For example, you could do:

                 success: function (res) {                      
                     var arr = data(res);
                 },
    

    This is why it is not being assigned.

    Try making your Ajax call before $("#example2").handsontable({ and save it to someVariable, then set the source: someVariable

    Depending on what your Ajax call returns, you may also need to make some manipulations. For example, I needed to loop through and load into an array:

    function AppendToArray(ajaxValues, theArray) {
        for (var i = 0; i < ajaxValues.length; i++) {
            theArray.push('' + ajaxValues[i].Text + '');
        }
    }
    

    I hope this helps