I need to fetch data from multiple API and display them in the table.
What I came up with is:
var req = $.ajax({
url: "....linkhere",
dataType: 'jsonp'
});
var req = $.ajax({
url: "....linkhere1",
dataType: 'jsonp'
});
req.done(function(data) {
console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Although, this way I can only get data from one api. How can I take it from multiple?
EDIT:
I am trying to add text input, so I can send request about specific word. I am trying to append existing table with new results. I was trying to alter code which was provided as an answer below. However, I did something work, and it does not work.
$("#inputChoice").on("blur", function() {
let choice = $(this).val();
let req = $.ajax({
url: "...APIlink"+choice,
dataType: "jsonp"
});
req.done(function (data) {
console.log(data);
var infoTable = $("<table />");
let arrayL = data.length;
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
titleCell.addClass("title-row");
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
detailCell.addClass("details-row")
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Request data from endpoints and when they're all done create a table
function multiReq(...links) {
let responseCount = links.length;
const responses = [];
let handler;
function responseHandler(i) {
return data => {
responseCount -= 1;
responseCount === 0
? handler([].concat(...responses))
: (responses[i] = data)
}
}
links.forEach((link, i) => $.ajax({
url: link,
dataType: 'jsonp'
}).done(responseHandler(i)));
return {
done(callback) {
handler = callback;
}
};
}
multiReq(link1, link2).done((data) => {})
or
function multiReq(...links) {
return Promise.all(links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses))
}
multiReq(link1, link2).then(data => {
// create table
})
or
function multiReq(...links) {
return $.when(...links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses.map(([data]) => data)))
}
multiReq(link1, link2).done(data => {
// create table
})
or as close to your code as possible:
var req1 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
var req2 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
$.when(req1, req2).done(function([data1], [data2]) {
var data = data1.concat(data2); // merge data from both request into one
//console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display-resources"></div>
Related
I'm having issues with saving multiple rows to the back-end. I don't know how to send all the rows in batch, so I was trying to send each row at a time but it hits after it has put the last row into the oEntry.
submitButtonPress: function() {
var oModel = this.getModel();
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
//get only rows with changes
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
var oEntry = {};
//for each row get data
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
oEntry.MRU_ID = obj.EST_MRU_ID.toString();
oEntry.ESTIMATE_PRCT = obj.ESTIMATE_PRCT;
oEntry.INSTALL_READ = obj.INSTALL_READ;
oEntry.PLAN_ESTIMATE = obj.EST_INSTALL;
oEntry.MRU_DATE = estDate;
oEntry.OFFICE_CODE = officeCode.toString();*/
oModel.create("/MRU_ESTSet", oEntry, {
success: function(oData, response) {
sap.m.MessageBox.alert("MRU: " + oEntry.MRU_ID + " EST DATE:" + oEntry.MRU_DATE + " SAVED!");},
error: function(oError) {
sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
}
If you are using oDataModel V2 then what you could just simply do is:
oModel.submitChanges()
This would send all changes made to the model in a batch.
submitChanges method documentation
This is what ended up working for me.
Adding:
oModel.setUseBatch(true);
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
So the function ends up like this and only sends one confirmation instead of many:
submitButtonPress: function() {
var oModel = this.getModel();
oModel.setUseBatch(true);
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
var oEntry = {
MRU_ID: obj.EST_MRU_ID,
ESTIMATE_PRCT: obj.ESTIMATE_PRCT,
INSTALL_READ: obj.INSTALL_READ,
PLAN_ESTIMATE: obj.EST_INSTALL,
MRU_DATE: estDate,
OFFICE_CODE: officeCode
};
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
},
here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});
Here is my code.
Currently here every time inner ajax method will call when outer method mark as done.
var folderpath = encodeURIComponent('Recording' + new Date().getTime());
var ajaxWorking = true;
function uploadAudio(mp3Data) {
var reader = new FileReader();
reader.onload = function (event) {
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
console.log("mp3name = " + mp3Name);
fd.append('fname', mp3Name);
fd.append('data', event.target.result);
//Costin testing
fd.append('studentId', '1');
fd.append('folderpath', folderpath);
fd.append('recording', stopRecording)
$.ajax({
type: 'POST',
url: '/api/ClientApi/PostRecordedStream',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log(data + " : AjaxDone");
ajaxWorking = false;
}
}).done(function (data) {
console.log(data);
//setTimeout(this, 5000);
console.log(stopRecording + " : " + ajaxWorking);
if (stopRecording == true && ajaxWorking == false) {
console.log(stopRecording + " : " + ajaxWorking + "LoadMP3");
$.ajax({
type: 'GET',
url: '/api/ClientApi/GetAudio',
data: { folderpath: folderpath },
success: function (data) {
console.log(data);
}
}).done(function (data) {
var url = 'data:audio/mp3;base64,' + data;
var li = document.createElement('li');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
hf.download = 'audio_recording_' + new Date().getTime() + '.mp3';
hf.innerHTML = hf.download;
li.appendChild(au);
li.appendChild(hf);
recordingslist.appendChild(li);
});
}
});
};
reader.readAsDataURL(mp3Data);
}
Outer ajax will call multiple time from UI. But I want to call only when all outer ajax call are done.
I have a 'ng-grid' table that have 2 types of data source. One is from my database using a function called getContributors(), and another one is from a list of api(s).
The getContributors function is like the default function in the ng-grid tutorial.
function getContributors() {
var deferred = $q.defer();
$http.get(contributorsFile)
.then(function(result) {
contributors = result.data;
deferred.resolve(contributors);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
My method for loading the multiple api data is to load the database data first, and then after all the database data is all loaded it will make a request to the api using a parameter from the database data
var ajax_wait_count = 0;
gridService.getContributors().then(function(data) {
// Looping each data with angular.forEach()
angular.forEach(data, function(value, key){
var this_uid = value['uid'];
// if(ajax_wait_count==0)
// {
$timeout(function(){
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getrank.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['ranked_tier'] = json;
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlevel.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['level'] = json['level'];
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getsummonercreate.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != 0) {
var date_c = json[0]['create_date'];
date_c = date_c.replace(' ', 'T');
new_date = new Date(date_c);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['summoner_create_date'] = datestring;
}
else if (json == 0) {
data[key]['summoner_create_date'] = "";
}
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlastplayed.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != "null" && json != null) {
var datedatas = json;
var datearray = [];
var thedatestr = "";
var loopidx = 1;
now_date = new Date();
now_date.setHours(0);
now_date.setMinutes(0);
now_date.setSeconds(0);
now_date.setDate(now_date.getDate() - 2);
next_date = new Date();
next_date.setHours(23);
next_date.setMinutes(59);
next_date.setSeconds(59);
// next_date.setDate(next_date.getDate());
angular.forEach(datedatas, function (value3, key3) {
datearray[key3] = parseInt(value3['createDate']);
});
datearray.sort();
datearray.reverse();
var count_played_today = 0;
angular.forEach(datearray, function (value2, key2) {
if (loopidx == 1) {
thedatestr = value2;
}
date_compare = new Date(parseInt(value2));
if (date_compare.getTime() >= now_date.getTime() && date_compare.getTime() < next_date.getTime()) {
count_played_today++;
}
loopidx++;
});
// var date_c = json[0]['create_date'];
// date_c = date_c.replace(' ','T');
var dateinsert = parseInt(thedatestr);
new_date = new Date(dateinsert);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['last_played_date'] = datestring;
this_date = new Date();
date_diff = dateDiff(new_date.toString(), this_date.toString());
data[key]['last_played_date_qty'] = date_diff.d + " days " + date_diff.h + " hours " + date_diff.m + " minutes";
data[key]['count_played'] = count_played_today;
}
else if (json == "null" || json == null) {
data[key]['last_played_date'] = "";
data[key]['last_played_date_qty'] = "";
data[key]['count_played'] = 0;
}
},
error: function () {
// alert("Error");
}
});
},1500);
ajax_wait_count=0;
// }
ajax_wait_count++;
});
$scope.myData = data;
});
Now, the problem that emerges is :
The loading time for the api data is very long, and because of ajax asynchronous request, I can't make a loading function to delay the data
It appends the api data after the database data, which sometimes confuses the user whether the data is loaded or not
Sometimes in Chrome, the request is too much and it returns "err_insufficient_resources"
My question is,
Can my method of loading the api data be changed so it will make the loading time much faster and more efficient?
To make users less confused about the high amount of data, how can I make the progressbar (angular progress bar) wait for the database data + the api (AJAX) data?
Thank you in advance
that is my ajax call:
function getEle(id) {
var element = new Array();
$.ajax({
async: false,
url: "map.php",
type: "POST",
dataType: 'json',
data: {
"id": id
},
success: function (data) {
var resultArr = new Array();
var resultArr = data;
var state = new Array();
for (var s = 0; s < resultArr.length; s++) {
state[s] = resultArr[s];
element[s] = id;
element[s] = state[s];
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
return element;
}
Have some solution kindly post it..... thanks in advance....
you can use window.location in javascript.
success: function (data) {
var resultArr = new Array();
var resultArr = data;
var state = new Array();
for (var s = 0; s < resultArr.length; s++) {
state[s] = resultArr[s];
element[s] = id;
element[s] = state[s];
}
window.location = "yourpage address";// add this line
}