Search code examples
jquerycssjsonmediawiki-api

Creating and appending blocks of data using jQuery


I'm creating a web app that queries 10 wikipedia entries using the mediapedia API and displays each of them in blocks.

Here's the json:

https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=Shakira&limit=10&profile=fuzzy

What I want to do is display these entries all in blocks one below each other. So I was thinking of using a for loop to iterate through each entry and then using jQuery to append each block layered from top to bottom. How would I accomplish this?

Here's my codepen for simplicity: http://codepen.io/tadm123/pen/oBqwYZ

My attempt to iterate and append entries to blocks:

for(var i=0;i<10;i++)
{
    title = a[1][i];
    descr = a[2][i];
    link =a[3][i];

    var b = $('<a href = "' + link '"><div class="panel panel-info"><p class="panel-heading">' + title + '</p><p class="panel-body">' + descr + '</p></div></a>');

    $('#block').append(b);
}

I'd appreciate any help. Thanks.


Solution

  • What you have seems to work, except you're missing the + after link in var b. And b can just be a normal variable - no need to wrap it in jQuery.

    $.getJSON("https://cors-anywhere.herokuapp.com/http://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=Shakira&limit=10&profile=fuzzy", function(a) {
    
      for (var i = 0; i < 10; i++) {
        var title = a[1][i],
          descr = a[2][i],
          link = a[3][i],
          b = '<a href = "' + link + '"><div class="panel panel-info"><p class="panel-heading">' + title + '</p><p class="panel-body">' + descr + '</p></div></a>';
    
        $('#block').append(b);
      }
    
    });
    .form {
      text-align: center;
      margin: 50px;
      font-size: 20px;
    }
    
    .glyphicon {
      font-size: 20px;
    }
    
    .panel {
      margin: auto;
      width: 1000px;
      border-radius:
    }
    
    .panel-heading {
      font-size: 20px;
      text-align: center;
    }
    
    .panel-body {
      font-size: 15px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    
    
    <div class="form">
      <input type="text" placeholder="Search for...">
      <button class="glyphicon glyphicon-search" aria-hidden="true"></button>
    </div>
    
    
    <div id="block"></div>