I am trying to fetch data from the API and display them in format Name + clickable website link.
I was able to display data but the link is represented as text rather than hyperlink.
There is my Ajax script:
$(function() {
$.ajax({
url: "url",
type: "get",
dataType: "json",
success: function(data) {
console.log(data.name);
for (i = 0; data.length; i++) {
name = data[i].name;
web_pages = data[i].web_pages;
var link = document.createElement('a');
link.setAttribute('href', web_pages);
link.innerHTML = web_pages;
var paragraph = $("<p />", {
text: name + " " + link
});
$("#display-resources").append(paragraph);
}
}
});
});
It's because you're inserting the link as text (string). Try this instead
var paragraph = $("<p />", { text: name + " " }).append(link)
Related
I am doing the Wikipedia Viewer challenge of freecodecamp and when I am itterating through the pages that are found the first item of the list does not contain a link to the Wikiepdia page. Why is that?
JS Code:
function getData(){
var search = $("#searchBar").val();
var url = baseUrl + '/w/api.php?action=query&format=json&origin=*&list=prefixsearch&psoffset=max&pssearch='+search;
$.ajax( {
url: url,
dataType: 'json',
type: 'GET',
success: function(data) {
var html="";
var entries = data.query.prefixsearch;
console.log(url);
html+="<ul class='items'>";
for(var i=0;i<entries.length;i++){
html+="<li><h3>"+entries[i].title+"</h3><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'</a></li>";
}
html+="</ul>";
$(".entries").html(html);
}
});
}
Html Code:
<div class="entries">
</div>
As James pointed out in comments, your code outputs <a> without a closing > and with no text.
Change:
html+="<li><h3>"+entries[i].title+"</h3><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'</a></li>";
into this:
html+="<li><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'><h3>"+entries[i].title+"</h3></a></li>";
Full Code
function getData() {
var search = $("#searchBar").val();
var url = baseUrl + '/w/api.php?action=query&format=json&origin=*&list=prefixsearch&psoffset=max&pssearch=' + search;
$.ajax({
url: url,
dataType: 'json',
type: 'GET',
success: function(data) {
var html = "";
var entries = data.query.prefixsearch;
console.log(url);
html += "<ul class='items'>";
for (var i = 0; i < entries.length; i++) {
html+="<li><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'><h3>"+entries[i].title+"</h3></a></li>";
}
html += "</ul>";
$(".entries").html(html);
}
});
}
I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});
I am doing on a instagram api, and I get information from server including user profiles and two more kinds. I want to put the information in a table on html. Each row is related to a username(since I searched for username), and there are profiles and two more things on each row. I am a little confused about how to do that.
here is my code:
var searchUsers = function(query,count){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
data: {
q: query,
count: count,
access_token: access_token,
},
url: "https://api.instagram.com/v1/users/search",
success: function(data) {
// placing the images on the page
console.log(data);
if (data.data.length>0){
var resultShow = $("#users_result");
for (var i in data.data){
resultShow.append("<img src='" + data.data[i].profile_picture + "'></img>");
// var username = "https://www.instagram.com/"+ data.data[i].username;
// console.log(username);
resultShow.append("<a target='_blank' href = 'https://www.instagram.com/"+data.data[i].username+"'>user profile</a>");
// var id = data.data[i].id;
// console.log(id);
$.ajax({
url: 'https://api.instagram.com/v1/users/' + data.data[i].id + '/media/recent/',
type: "GET",
dataType: "jsonp",
data: {access_token: access_token},
success: function(data2){
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
},
error: function(data2){
console.log(data2);
}
});
}
} else {
resultShow.html("Noting found!");
}
},
error: function(data){
console.log(data);
}
});
};
You can change almost any value in a page using the innerHTML property.
Ex:document.getElementById("demo").innerHTML = "Paragraph changed!";
http://jsfiddle.net/blazeeboy/fNPvf/
To change the values inside a table, just assign an ID to it and change with your Javascript function.
In your case, I would suggest inserting any Javascript parameter between line 31 and 32.
success: function(data2){
var title = document.getElementById('title');
var username = "https://www.instagram.com/"+ data.data[i].username;
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
It will write the username into the table with id "title", if you need more than one table value, you'll need to make a array and use the for loop to insert an specific value into a specific table, tr, etc... id
success: function(data2){
//tableids are the ids of each table row or column in the order you wanna write them
var tableids = ['0', '1', '2'];//starting at 0
var username = "https://www.instagram.com/"+ data.data[i].username;
var title = document.getElementById(tableids[i]);
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
Hope it was clear enough
i'm doing a simple php chat application that sends the message input to the server via ajax and saves it in a text file. Now after it retrieves all data in the text file and sends it to the client in an array form via ajax. Now what i want to do is populate a div called "chat-box" with the contents of the array as html but nothing happens and ii don't get any errors in firebug apart from ": undefined".
This is the code:
<script type="text/javascript">
// setInterval(function(){alert("Hello");}, 5000);
$(document).ready(function() {
function getchat(messages)
{
var chat = $(".chat-box").html();
for (var i=0; i < messages.length; i++)
{
var msg = messages[i].split(':');
var name = msg[0];
var post = msg[1];
$(".chat-box").html(chat + "<div class='bubble'>" + name + " : " + post + "</div>");
}
}
$("#btnPost").click(function() {
var msg = $("#chat-input").val();
if (msg.length == 0)
{
alert ("Enter a message first!");
return;
}
var name = $("#name-input").val();
var chat = $(".chat-box").html();
//$(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");
var data = {
Name : name,
Message : msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(chat) {
getchat(chat)
}
});
});
});
</script>
Try this instead for updating the chat box:
var index = messages[i].indexOf(':');
var name = messages[i].substring(0, index);
var content = messages[i].substring(index + 1);
var $newMessage = $('<div>')
.addClass('bubble')
.text(name + " : " + content);
$(".chat-box").append($newMessage);
If this doesn't work, check if the messages returned by the server are correct by using console.log(messages).
You said the div is called chat-box. Perhaps it's this:
$(".chat-box")
maybe you intended to write it as $("#chat-box")
Let's say I have an XML like this: http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=b25b959554ed76058ac220b7b2e0a026&track=Just%20for%20Me&artist=Hinoi%20Team
I'm trying to get the name of the track and it's not working: I do this:
$.ajax({
type: "GET",
url: "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=b25b959554ed76058ac220b7b2e0a026&track="+yourTrack+"&artist="+yourArtist,
dataType: "xml",
success: function(xml) {
$(".loading").css("display", "none");
$(xml).find('track').each(function(){
var id = $(this).find('id').text();
console.log("Success!");
var song = $(this).find('track > name').text();
var name = $(this).find('artist name').text();
var album = $(this).find('album title').text();
$("#more").append("\nSong: " + song);
$("#more").append("\nArtist: " + name);
$("#more").append("\nAlbum: " + album);
$("#more").append("\n\nlast.fm ID: " + id);
});
}
});
and the result is this:
Song:
Artist: Hinoi Team
Album: Super Euro Party
last.fm ID: 43135480
Help?
The selector in this line isn't right:
var song = $(this).find('track > name').text();
$(this) is a <track> element. You are looking for another <track> element inside of it, which isn't what you need. You are looking for the <name>, so use this instead:
var song = $('> name', this).text();