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
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.
with promise you can refer to this link .
When all AJAX requests complete
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.EDIT:
For an arbitrary number of data sources, you can do
Consider the following code.
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.