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

How the React Component Class Executes OnChange Event in a Closure

When working on my React code, I found myself creating a closure by calling "onChange." class CityInput extends React.Component { constructor( props ){ super( props ); this.state = { city : "", country : "" ...

The Vue warning states that the property "$store" was attempted to be accessed during rendering, but it is not defined on the current instance

Hello, I am new to the world of web development and currently working on an online shop project. I have encountered two errors that I'm struggling to fix: 1) [Vue warn]: Property "$store" was accessed during render but is not defined on instance. 2) ...

Sending data from JavaScript to Jade templatesIs this alright?

Utilizing node.js, express, jade, and socket.io, I have successfully executed JavaScript code on the jade side. However, I am encountering difficulty in generating HTML output from the script block. Based on your feedback, I have updated my question to in ...

Expanding a JavaScript list using HTML inputs

I have a script where a grid dynamically displays a list of words. Is there a way to populate the word list in the grid using HTML? Currently, I am doing this... var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"]; Can additional words be adde ...

Adjusting the timing of a scheduled meeting

Is there a way for me to update the time of a Subject within my service? I'm considering abstracting this function into a service: date: Date; setTime(hours: number, mins: number, secs: number): void { this.date.setHours(hours); this.date.s ...

Press a button to activate a function on a dynamically created table using Ajax

On my website, I have an ajax function that dynamically generates a table and displays it inside a designated div. Below is the PHP code called by the Ajax function. echo "<table border='1' cellspacing='12' cellpadding='4' ...

Maximizing Efficiency: Utilizing a Single jQuery Function to Retrieve Specific Values

I have a webpage with select menus for choosing user type, minimum age, and maximum age. I want to select options and send values as an object array to ajax. Initially, the getAjax function is working when the page loads. However, it stops working when I c ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

Using Vue3 to set attributes on web components

I recently developed a self-contained web component using Vite and Vue3 to replace outdated jQuery libraries. When this component is rendered in HTML, it appears like this: <custom-datepicker id="deliveryTime"> #shadow-root <div> ...

Generate the URL based on the JSON feed

Can someone help me figure out what I'm doing wrong here? I'm attempting to create the image URL using the flickr.photos.search method now (I need to show images close to the visitor's geolocation), it was working with groups_pool.gne befor ...

The absence of the iframe in ie8 is causing problems that cannot be fixed with relative positioning

On a website, I am integrating an external 2-factor authentication solution called Duo Web using their PHP and Javascript. It works smoothly on all browsers except for IE8. When the user passes the initial login screen, the 2FA login page loads, but the if ...

Next.js triggers the onClick event before routing to the href link

Scenario In my current setup with Next.js 13, I am utilizing Apollo Client to manage some client side variables. Objective I aim to trigger the onClick function before navigating to the href location. The Code I'm Using <Link href={`/sess ...

Using es6 map to deconstruct an array inside an object and returning it

I am looking to optimize my code by returning a deconstructed array that only contains individual elements instead of nested arrays. const data = [ { title: 'amsterdam', components: [ { id: 1, name: 'yanick&a ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

Substitute the functions within a Node.js module with simulated functions

I am currently working on a Node.js project that serves as an API wrapper. To ensure the reliability of my code, I am writing unit tests using nodeunit and need to incorporate mock functions into the module. For instance, I require a function that mimics s ...

Completely different method for transmitting an array to NodeJS through AJAX

Recently, I've encountered difficulties when sending arrays to NodeJS using AJAX. It seems that whenever I try to send it with JSON, the error function is always triggered. Despite seeking explanations, I haven't found a satisfactory answer. The ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

AngularJS - Introducing blurred delay

Here is the code snippet I am working with: <div class="staff"> <input ng-model="user" ng-focus="isFocused = true;" ng-blur="isFocused = false;/> <div class="matches" ng-if="isFocused"> <div ...

Tips for submitting multiple radio button values in a tabular format

HTML Code: <div class="tab"><h4>Zip Code</h4> <p><input type="text" class="text1" placeholder="Enter zip code..." oninput="this.className = ''" name="zipcode"></p> </div> <div class="tab">& ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...