l-emi l-emi - 3 months ago 10
jQuery Question

Wikipedia API - displaying only 4 results

I'm using the Wikipedia API to display some articles. The only issue is that it only displays the first 4 results. I've looked at similar questions but still can't find a way to display more. Here's the jsfiddle.

JS:

$(document).keypress(function(e) {

if(e.which == 13) {

var searchTerm = $('#searchy').val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&format=json&callback=?";

$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function(data){
//console.log(data[1][0]);
//console.log(data[2][0]);
//console.log(data[3][0]);
$('#output').html('');
for (var i = 0; i < data.length; i++) {
$('#output').prepend("<li><a href=" + data[3][0] + ">" + data[1][0] + "</a><p>" + data[2][0] + "</p></li>");

$('#centbox').css("top", "14%");
$('#resultati').css("top", "16%");
}
},
error: function(errorMessage){
alert("Error!");
}

})

};
});

Answer

You have:

for (var i = 0; i < data.length; i++) {

But data.length is always going to be 4: [0] is the search, [1] is an array of article names, [2] is an array of summaries, and [3] is an array of links.

So perhaps:

for (var i = 0; i < data[1].length; i++) {
    $('#output').prepend("<li><a href=" + data[3][i] + ">" +  data[1][i] + "</a><p>" + data[2][i] + "</p></li>");
Comments