skip to Main Content

Below is my code. I have two ajax request pulling data from two seperate lists that contain the same information. When they populate my table in my Success function, it posts two seperate tables instead of one but it contains all the information I want to populate into the table.

How can I concatenate the returns into one array to post to the table?

$(function(){
    window.addEventListener('load', function(){
        var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
        var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
            $.ajax({
              url: fullUrl,
              type: "GET",
              headers: {
                  "accept":"application/json; odata=verbose"
              }, 
              success: onSuccess,
              error: onError
            });
            $.ajax({
              url: fullUrl1,
              type: "GET",
              headers: {
              "accept": "application/json; odata=verbose"
              },
              success: onSuccess,
              error: onError
            });



  function onSuccess(data) {
     var objItems = data.d.results;
     var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' +'</tr></thead><tbody>';

     for (var i = 0; i < objItems.length; i++) {
         tableContent += '<tr>';
         tableContent += '<td>' + objItems[i].Title  + '</td>';
         tableContent += '<td>' + objItems[i].Age + '</td>';
         tableContent += '<td>' + objItems[i].Position + '</td>';
         tableContent += '<td>' + objItems[i].Office + '</td>';
         tableContent += '<td>' + objItems[i].Education + '</td>';
         tableContent += '<td>' + objItems[i].Degree + '</td>';
         tableContent += '</tr>';
 }
   $('#employees').append(tableContent);
   }
    function onError(error) {
        alert('Error');
   }
  });
});

3

Answers


  1. I can think of two ways without using promise right now .
    1 You can use closure to capture the response.
    2 global variable

    I like the first approach more, because it seems more maintainable and reusable.

    function requestCounter() {
      
        return (function l2(){
          
          var data = [];
          
          var totalRequest = 0;
          
          return (function l3 (){
            
            return {
             
                get : function (){
                
                  return {data:data,totalRequest}
                  
                },add : function(responseData){
                
                   totalRequest += 1
                   
                   data = data.concat(responseData)
                }
             }
         })()
        
        })()
       
    }
    
    var requestCounter = requestCounter()
    
    var tempData1 = [
    
      {Title :"T1",Age :"12" },
      {Title :"T2",Age :"13" }
    ]
    
    var tempData2 = [
    
      {Title :"T3",Age :"125" },
      {Title :"T4",Age :"133" }
    ]
    function onSuccess(data) {
        //replace this with your data.d.results
         var objItems = data;
         
         requestCounter.add(objItems);
         
         var totalData = requestCounter.get();
     
         if(totalData.totalRequest > 1) {
                 var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' +'</tr></thead><tbody>';
    
           for (var i = 0; i < totalData.data.length; i++) {
               tableContent += '<tr>';
               tableContent += '<td>' + totalData.data[i].Title  + '</td>';
               tableContent += '<td>' + totalData.data[i].Age + '</td>';
              
               tableContent += '</tr>';
    
           }
         
         }
          
          console.log(tableContent);
     }
     //first ajax call
     onSuccess(tempData1);
     ///second ajax call
     onSuccess(tempData2);
     
     
     

    with promise you can refer to this link .
    When all AJAX requests complete

    Login or Signup to reply.
  2. Here’s a formulation using fetch() and promises. (Dry-coded, so there may be silly bugs.)

    EDIT: Added the source parameter that’s added into all results.

    function loadData(source, url) {
      return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request
        .then((r) => {
          if (!r.ok) throw new Error("Failed: " + url);  // Check for errors
          return r.json();  // parse JSON
        })
        .then((data) => data.d.results) // unwrap to get results array
        .then((results) => {
          results.forEach((r) => (r.source = source)); // add source to each item
          return results;
        });
    }
    
    window.addEventListener("load", function () {
      Promise.all([
        loadData("EmployeeInfo", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree"),
        loadData("Employee2", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree"),
      ])
        .then(([r1, r2]) => {
          const objItems = r1.concat(r2);
          var tableContent =
            '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' +
            "<td><strong>Age</strong></td>" +
            "<td><strong>Position</strong></td>" +
            "<td><strong>Office</strong></td>" +
            "<td><strong>Education</strong></td>" +
            "<td><strong>Degree</strong></td>" +
            "<td><strong>Source</strong></td>" +
            "</tr></thead><tbody>";
    
          for (var i = 0; i < objItems.length; i++) {
            tableContent += "<tr>";
            tableContent += "<td>" + objItems[i].Title + "</td>";
            tableContent += "<td>" + objItems[i].Age + "</td>";
            tableContent += "<td>" + objItems[i].Position + "</td>";
            tableContent += "<td>" + objItems[i].Office + "</td>";
            tableContent += "<td>" + objItems[i].Education + "</td>";
            tableContent += "<td>" + objItems[i].Degree + "</td>";
            tableContent += "<td>" + objItems[i].source + "</td>";
            tableContent += "</tr>";
          }
          $("#employees").append(tableContent);
        })
        .catch((err) => {
          alert("Error: " + err);
          console.error(err);
        });
    });
    

    EDIT:

    For an arbitrary number of data sources, you can do

      Promise.all([
        loadData("A", ...),
        loadData("B", ...),
        loadData("C", ...),
        loadData("D", ...),
        loadData("E", ...),
      ])
        .then((arrays) => {
          const objItems = arrays.reduce((a, b) => a.concat(b), []);
          // ...
    
    Login or Signup to reply.
  3. Consider the following code.

    $(function() {
      var myData = [];
      window.addEventListener('load', function() {
        var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
        var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
        $.ajax({
          url: fullUrl,
          type: "GET",
          headers: {
            "accept": "application/json; odata=verbose"
          },
          success: onSuccess,
          error: onError
        });
        $.ajax({
          url: fullUrl1,
          type: "GET",
          headers: {
            "accept": "application/json; odata=verbose"
          },
          success: onSuccess,
          error: onError
        });
    
        function onSuccess(data) {
          $.each(data.d.results, function(l, v) {
            myData.push(v);
          });
          refreshTable();
        }
    
        function initTable(hdrs) {
          var t = $("<table>", {
            id: "employeeTab"
          }).css({
            width: "100%",
            border: "1"
          });
          $("<thead>").appendTo(t);
          var r = $("<tr>").appendTo($("thead", t));
          $.each(hdrs, function(i, h) {
            $("<th>").html(h).appendTo(r);
          });
          return t;
        }
    
        function refreshTable() {
          var tableContent;
          if ($("#employeeTab").length == 0) {
            tableContent = initTable(["Name", "Age", "Position", "Office", "Education", "Degree"]);
            tableContent.appendTo("#employees");
          } else {
            tableContent = $("#employeeTab");
          }
          var tBod = $("tbody", tableContent);
          tBod.html("");
          $.each(myData, function(k, v) {
            var row = $("<tr>").appendTo(tBod);
            $.each(v, function(j, item) {
              $("<td>").html(item).appendTo(row);
            });
          });
        }
    
        function onError(error) {
          alert('Error');
        }
      });
    });
    

    We can use a variable, myData, outside of the functions to contain all the data. Similar to a Global Variable.

    I broke the steps down into their own functions for ease of use.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search