0

Using the following code to extract items for a SharePoint list and display in HTML. Works great thank to all you folks here.

Now I want to inject the output into the jQuery DataTables plugin but not able to get it work correctly. Would appreciate assistance. Perhaps this can only be done using a REST query?

<script>
    $(document).ready(function() { 
       BuildResources();
    });

    // START BUILD RESOURCES
    // ******************************//
   // ******************************//
//GET TOP FIVE RECORDS BASED ON CREATION DATA
      //This variable will holds a reference to the collection of items for the specified list   
      var returnedBuildResources = null;   

      //This function that loads the specified list and runs the query asynchronously   
      function  BuildResources() {   
         //Get the current context   
         var context = new SP.ClientContext();   
         //Get the specified list value can be passed through the function as an agrument   
         var list = context.get_web().get_lists().getById('{757c78b2-dbba-4da2-bf34-23dcc97dc24e}')
         //Create CAML query   
         var caml = new SP.CamlQuery();   
         //Actual CAML query that will return records or fields   
         caml.set_viewXml("<View><Query><Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where></Query><ViewFields><FieldRef Name='ID' /><FieldRef Name='Group' /><FieldRef Name='Competency' /><FieldRef Name='Title' /><FieldRef Name='FileRef' /><FieldRef Name='_UIVersionString' /><FieldRef Name='Modified' /></ViewFields><QueryOptions /></View>");

         //Specify the query and load the list oject   
         returnedBuildResources = list.getItems(caml);   
         context.load(returnedBuildResources);   
         //Run the query asynchronously, passing the functions to call when a response arrives   
         context.executeQueryAsync(onSucceededBuildResourcesCallback, onFailedBuildResourcesCallback);   
      }   

        //This function fires when the query completes successfully   
      function onSucceededBuildResourcesCallback(sender, args) {   
         var enumerator = returnedBuildResources.getEnumerator();   
         //Formulate HTML from the list items
           var markup='';   
         //Loop through all the items   
         while (enumerator.moveNext()) {

            var listItem = enumerator.get_current();
            // Trim to shorten values
            //var ToTrim = listItem.get_item('Description') ;
            //var TrimedDescription = jQuery.trim(ToTrim).substring(0, 100)
            // .split(" ").slice(0, -1).join(" ");
            // The mark up
            markup += '<tr>';
            //markup += '<td>' + listItem.get_id() + '</td>';
            markup += '<td>' + listItem.get_item('Group') + '</td>';
            markup += '<td>' + listItem.get_item('Title') + '</td>';
            markup += '<td>' + listItem.get_item('Competency') + '</td>';
            markup += '<td>' + listItem.get_item('_UIVersionString') + '</td>';
            markup += '<td>' + listItem.get_item('Modified') + '</td>';
            markup += '<td><a href="' + listItem.get_item('FileRef') + '">Click to Open</a></td>';
            markup += '</tr>' ;
        }   
      //Display the formulated HTML in the Reporting-Window element   
       ResourcesDisplay.innerHTML = markup += '';
   }   
      //This function fires when the query fails   
     function onFailedBuildResourcesCallback(sender, args) {   
      //Formulate HTML to display details of the error   
      var markup = '<p>The request failed: <br>';   
      markup += 'Message: ' + args.get_message() + '<br>';   
      //Display the details   
      ResourcesDisplay.innerHTML = markup ;   
   }  
// ******************************//
// ******************************//
// END BUILD RESOURCES      
</script>

2 Answers 2

1

Datatable expects the array for the aaData property. There are few more ways. Check the datatable plugin examples.

Create an array to hold the items. (Outside the callback)

var resultsArray = new Array();

On your success callback, use something like below:

    //ItemsQuery item success
    function (listItems) {
        var listItemEnumerator = listItems.getEnumerator();
        //iterate though all of the items

        while (listItemEnumerator.moveNext()) {

            var currItem = listItemEnumerator.get_current();

            var obj = {
                'Title' : currItem.get_item('Title') ? currItem.get_item('Title') : '',
                'Competency' : currItem.get_item('Competency') ? currItem.get_item('Competency') : '',
                'Group' : currItem.get_item('Group') ? currItem.get_item('Group') : '',
                'Modified' : currItem.get_item('Modified') ? currItem.get_item('Modified') : ''
            };

            resultsArray.push(new Array (obj.Title, obj.Competency, obj.Group, obj.Modified));
        }

        $('#tblResults').dataTable( {
            "aaData": resultsArray
        });
    },

    //Item failure
    function (sender, args) {
        alert(args.get_message());
    }
2
  • Thanks. Interesting way to handle. But I need to easily inject into HTML to create links, and other functionality
    – PianoMan
    Commented Jun 2, 2016 at 19:15
  • 1
    For that you can use DataTables columns.render property. Each column can have its own separate render function to return formatted HTML as you like. For that you would still need to fetch all the data first, before rendering the table. Source: datatables.net/reference/option/columns.render Commented Dec 10, 2019 at 2:02
0

I was able to get this to work by inserting the datatables call right after the construction of the query results and before the failed function call.

  //Display the formulated HTML in the Reporting-Window element   
   ResourcesDisplay.innerHTML = markup += '';

         $('#example222').DataTable( {
        //"dom": 'Rlfrtip'
         } );

}

1
  • 1
    I see that you solved your problem, but just for future reference, if you use REST to get the data you can get it back as JSON which (as Aveenav pointed out) you can just drop directly into DataTables Data property, so there would be no need to do all that item.get_item() stuff to get the values. And if you need to do some special formatting (like inject links), you can do that with DataTables column renderers. Commented Jun 2, 2016 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.