2

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);
});
});

2
  • Use another variable instead of overwriting req perhaps? Commented Dec 2, 2018 at 23:42
  • yep, I though about that, but then how to alter one table instead of creating a new table for each api data? Commented Dec 2, 2018 at 23:46

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

5 Comments

These are great answers!
Whoah, great piece of work! I can see data in the console, but table does not display them at all. No errors in the console though
@HalfMartianHalfHuman that's because $.ajax returns three arguments (data, status and response object) and $.when passes all this in an array form to .done() callback. I fixed the code by plucking only the data (first array item) and provided working demo with custom backed on webtask.io (last example).
@marzelin Thanks for you help. I was trying to get further and create search field but I was unsuccessful. I've edited my question so if you can take a look I would appreciate it.
@HalfMartianHalfHuman you are creating a new table for each request. Target the existing table and append to it instead.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.