Kali Ma Kali Ma - 8 months ago 61
Ajax Question

Appending images from News API

I have successfully implemented an API using newsapi.org, which is working great. However, the information I have is only text, and want to add the image in for each headline. Not sure how to do this as the headlines are obviously changing.

There is a urlToImage tag within the JSON file, which presumably is what I need to implement this. You will see from my code that I have made a start at implementing this, but to no avail.

Any help on getting this implemented would be much appreciated.

jQuery

$(document).ready(function() {
$.ajax({
url: "https://newsapi.org/v2/top-headlines?sources=mtv-news&apiKey=XXXXXX",
method: "GET",
success: function(data) {
processData(data);
}
});

function processData(data) {
var articleItems = [];
for (var i = 0; i < data.articles.length; i++) {

var author = data.articles[i].author;
var title = data.articles[i].title;
var description = data.articles[i].description;
var urlToImage = data.articles[i].urlToImage;
var artUrl = data.articles[i].url;


var $author = $('<div class="author">Author: ' + author + "</div >");
var $title = $("<a href=" + artUrl + '><div class="title">' + title + "</div ></a>");
var $description = $("<a href=" + artUrl + '><div class="description">' + description + "</div ></a>");
var $urlToImage = $("<a href=" + artUrl + '><img class="urlToImage" src">')
$("#entertainment_news").append($author, $title, $description, $urlToImage);
$("#entertainment_news").append("<br />");

console.log(artUrl);
}
}
});


HTML

<div class="tab-pane fade" id="entertainment">
<h3>ENTERTAINMENT</h3>
<p id="entertainment_news"></p>
</div>

Answer Source

append() only accepts one argument and you have 4 jQuery objects. Forgo wrapping the HTML in a jQuery objects and just have them as regular strings.

var $author = '<div class="author">Author: ' + author + '</div >';
var $title  = '<a href=' + artUrl + '><div class="title">' + title + '</div ></a>';
var $description = '<a href=' + artUrl + '><div class="description">' + description + '</div ></a>';

You're also missing the source path for your image's src attribute. Assuming it's urlToImage, you'd do this:

var $urlToImage = '<a href=' + artUrl + '><img class="urlToImage" src=' + urlToImage + '>;

Then in your first append() call do this:

$("#entertainment_news").append($author + $title + $description + $urlToImage);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download