I need help accessing data from a REST API and displaying it in a table

How can I call all the data in "md" and display it in a table? I've tried multiple values but none seem to work. Can someone guide me on how to use the "md" value to display in a table?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $.get("https://cricapi.com/api/matches?apikey==apikey", function(matchdata) {
    console.log(matchdata.matches);
    matchdata.matches.forEach(function(md) {
      console.log(md.description + " - to grab more details, simply use the unique_id " + md.unique_id + " with the cricketScore api!");

      return true;

    });
  });
</script>

Answer №1

var $tableBody = $('#tableBody');

function createRow(dm) {
  var team_1 = dm['team-1'],
    team_2 = dm['team-2'],
    winner = (
      dm['toss_winner_team'] ?
      dm['toss_winner_team'] :
      'N/A'
    )
  return (
    '<tr>' +
    '<td>' + team_1 + '</td>' +
    '<td>' + team_2 + '</td>' +
    '<td>' + winner + '</td>' +
    '</tr>'
  )
}
$.get("https://cricapi.com/api/matches?apikey=your key", function(matchdata) {
  console.log(matchdata.matches);
  var rows = matchdata.matches.map(createRow).join('');

  $tableBody.html(rows);
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <table>
    <thead>
      <tr>
        <td>Team A</td>
        <td>Team B</td>
        <td>Winner</td>
      </tr>
    </thead>
    <tbody id="tableBody">
      <tbody>
  </table>
</body>

</html>

Click here for a live DEMO

Answer №2

There is a small mistake with an additional = in the apikey parameter.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $.get("https://cricapi.com/api/matches?apikey=DSyFXyxkkyMk1t1L0FNiInn3Pu92", function(matchdata) {
    console.log(matchdata.matches);
    matchdata.matches.forEach(function(md) {
      console.log(md.description + " - for more details, use the unique_id " + md.unique_id + " with the cricketScore api!");

      return true;
    });
  });
</script>

View Raw Output Here

Answer №3

Creating an HTML Table

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css" >


    </style>
</head>
<body>
    <table id="mytable">

    </table>
</body>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<!-- <script type="text/javascript" src="js/slick.min.js"></script> -->

<script type="text/javascript" src="js/custom.js"></script>

</html>

Implementing JavaScript (AJAX)

$(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: 'https://cricapi.com/api/matches?apikey="api key"',
        dataType: 'json',
        success: function (data) { 
            $.each(data, function(index, element) {
                $.each(element, function(index1, e1) {
                        $('#mytable').append('<tr><td>'+e1.date+'</td> <td>'+e1.type+'</td></tr>');
                });
            });
        }
    });
});

View the Result

https://i.stack.imgur.com/yyXgg.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the solution for halting code execution in a foreach loop with nested callbacks?

Currently, I am in the process of setting up a nodejs database where I need to retrieve user information if the user exists. The issue I'm facing is that when I return callback(null) or callback(userdata), it does not stop the code execution and resul ...

Click and release file upload

I am working on creating a drag and drop upload feature where the user can drop files onto a div, and then click an upload button to send them to the server. I'm facing an issue with JavaScript not recognizing the variable fd. How can I pass that vari ...

Encountered an Uncaught ChunkLoadError with Vercel Next.js: Chunk 0 failed to load

Upon removing the node modules and package-lock.json files, I encountered the error mentioned above when attempting to reload any page. The project works fine after being restarted for the first time. However, upon reloading the page again, it displays a b ...

JSF with PrimeFaces triggers two Ajax calls when deleting and filtering data

Our application utilizes Wildfly and a JSF Primefaces version 6.2 UI. During testing, I noticed that Primefaces makes two AJAX calls when executing the following scenario: Perform filtering by name Filter by Name <h:form id="accountForm"> ...

Utilize a randomized dynamic base URL without a set pattern to display a variety of pages

I am intrigued by the idea of creating a dynamic route that can respond to user-generated requests with specific files, similar to how Github handles URLs such as www.github.com/username or www.github.com/project. These URLs do not follow a set pattern, ma ...

TransitionGroup with CssTransition fails to execute exit transition

After making the switch from the outdated CSSTransitionGroup to the newer react-transition-group library for CSSTransition and TransitionGroup, I encountered an interesting challenge. I've been tinkering with creating an overlay loader, aiming to add ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

Top method for filling an array with strings

Imagine having an array called 'newArray'. var newArray = []; You can add strings to it like this: var thisString = 'watch'; newArray.push(thisString); Now, if you want to have 50 instances of the 'thisString' in the newAr ...

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

Using Cordova plugman to add the initial platform-specific plugin into the project

Here are the system dependencies: cordova: @7.1.0 plugman: @2.0.0 I am trying to use plugman specifically for installing plugins on a particular platform (such as android). Having reviewed the documentation, I find that the workflow and usage is not en ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

Dynamic, AJAX-driven content is experiencing a 200 status code

Is it necessary for a single-page website, which dynamically loads content via ajax and utilizes browser session history stacking, to return a "200 Status" for each successful state change? The core code of my website is as follows: $(document).on('c ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

Resetting React state can occur during routing in Ionic applications

I've been working on implementing React states in a way that allows all components and pages to easily access important variables with updates reflected across the app. However, I've encountered an issue where my state/context is reset to its ini ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...

How can I use `app.js` in Zendesk to connect to an external API using the complete URL

As someone new to developing Zendesk apps, I've been following the step-by-step guide available here. To Summarize I'm facing an issue with passing external API URLs to the AJAX call syntax within Zendesk's app.js file. You can find my sim ...

The process of styling with styled components in Mui - a guide to styling

Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...

Issue encountered with Ionic and Angular 2: Denied application of style from 'http://localhost:8100/build/main.css' due to unsupported MIME type ('text/html')

Initially, everything was going smoothly with my Ionic build, but things took a turn when I tried to test it on my iPhone. After stopping the server and running ionic serve --address localhost, I noticed that my stylesheet wasn't loading. Even after r ...