Hey, I've been experimenting with some code using ajax and have ended up with a lot of repetitive lines. Is there a way to streamline the code without losing functionality? I keep using the .done method multiple times when I could probably just use it once. Could you help me rewrite this code in a more concise manner? I'm not even sure if this is the best approach to using ajax?
var tbody = $('.tbody');
$('.item').on('click', function() {
$(this).addClass('active').siblings().removeClass('active');
});
$('li a').on('click', function(e) {
e.preventDefault();
var link = $(this).attr('href');
if (link == "books") {
$.ajax({
url : "https://mysafeinfo.com/api/data?list=bestnovels1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
dataType : "json"
})
.done(function (res) {
$('.page-header').html(link);
var text1 = '';
for(prop in res[0]) {
text1 += '<th>'+prop+'</th>'
}
thead.html(text1);
var text = '';
for (var i = 0; i < res.length; i++) {
text += '<tr>';
for(prop in res[i]) {
text += '<td>'+res[i][prop]+'</td>'
}
text += '</tr>';
}
tbody.html(text);
});
}else if(link == "novels" || link == "actors") {
var apiLink = "";
switch(link) {
case "novels":
apiLink = "bestnovels7";
break;
case "actors":
apiLink = "bestactors1";
break;
}
$.ajax({
url : `https://mysafeinfo.com/api/data?list=${apiLink}&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L`,
dataType: "json"
})
.done(function (res) {
$('.page-header').html(link);
var text1 = '';
for (const prop in res[0]) {
text1 += '<th>'+prop+'</th>'
}
thead.html(text1);
var text = '';
for (let i = 0; i < res.length; i++) {
text += '<tr>';
for(const prop in res[i]) {
text += '<td>'+res[i][prop]+'</td>'
}
text += '</tr>';
}
tbody.html(text);
});
}
})