I am using the following code to show my latest tweets from the new twitter API. I've got it working perfectly, however, no matter what I do I can only get it to show one tweet, how can I make it show 5 tweets?
here is my code:
<script type="text/javascript">
var twitterFetcher=function(){var d=null;return{fetch:function(a,b){d=b;var c=document.createElement("script");c.type="text/javascript";c.src="http://cdn.syndication.twimg.com/widgets/timelines/"+a+"?&lang=en&callback=twitterFetcher.callback&suppress_response_codes=true&rnd="+Math.random() document.getElementsByTagName("head")[0].appendChild(c)},callback:function(a){var b=document.createElement("div");b.innerHTML=a.body;a=b.getElementsByClassName("e-entry- title");d(a)}}}();
twitterFetcher.fetch('345901443028488192', function(tweets){
// Do what you want with your tweets here! For example:
var x = tweets.length;
var n = 0;
var numtweets = 5;
var element = document.getElementById('tweets');
var html = '<ul id="tweetul">';
if (tweets[n].innerHTML) {
html += '<li><img src="images/myicon.png" class="twittericon"/>' + tweets[n].innerHTML + '</li>';
} else {
html += '<li><img src="images/myicon.png" class="twittericon"/>' + tweets[n].textContent + '</li>';
}
n++;
html += '</ul>';
element.innerHTML = html;
});
</script>
You are not looping. You increment n, but you're never going back to the code above it.
you can get a new version of the api here :
http://jasonmayes.com/projects/twitterApi/#sthash.CAN6FObk.dpbs
then you can write this :
twitterFetcher.fetch('345170787868762112', 'example1', 1, true);
change with "1" in the code above count of tweets you wanted.
I hope you could help.
Related
In my code, I add an event listener to the pagination button. I can pass the page number to the function and set a new page number based on user input. Before changing the table data I want to clear the table. In this case, I am using datatable.empty() method but it gives me that the datatable.empty is not a function. Any idea how can I solve it?
function pageButtons(pages) {
var t = document.getElementById('test');
for (var page = 1; page <= pages; page++) {
//console.log(pages)
t.innerHTML += '<button id=' + page + '>' + page + '</button>';
}
document.getElementById('test').addEventListener("click", function (event) {
var newPageNumber = event.target.id;
var datatable = document.getElementById('data1');
state.page = newPageNumber;
datatable.empty();
console.log(state.page);
buildTable();
})
}
I am having trouble. So I need to get data from an api. I have a search bar and the user needs to input the search bar to look up a super hero api.
How would I get data from a search bar and put in my url all in a .click function.
var userInput;
var url;
var test;
//https://superheroapi.com/api/10215865526738981
$(document).ready(function () {
// when the user types in the data and clicks the button
$(btn1).click(function () {
// this is where the search bar is
userInput = document.getElementById('mySearch').innerHTML;
});
url = 'https://www.superheroapi.com/api.php/10215865526738981/search/batman' + userInput;
// here is where the api link in say type in batman
// and is should pop up with info about batman and
$.getJSON(url, function (data) {
var html = '';
$.each(data.results, function (i, demo) {
html += '<h2>' + demo.name + '</h2>';
//html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2> Power Stats ' + demo.powerstats.combat + '</h2>';
html += '<p> Connections ' + demo.connections.relatives + '</p>';
html += '<p> appearance ' + demo.appearance.gender + '</p>';
html += '<h2> Work ' + demo.work.base + '</h2>';
html += ' Profile <img src ' + demo.image.url + '>';
});
$('#demo').html(html);
});
}
<p>
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<p id="demo"></p>
</p>
Here is something that works that you can use to compare with your code and make something out of it. I've used plain javascript and left comments what is going on so that you can learn from it.
There were few wrong assumptions in original question.
code was executing on page load and didn't wait for user input
url was hardcoded to start with batman + what ever user wrote
Code below is not perfect, but it is close enough to original code and it should be easy to understand. I also opted not to use jQuery, but you should be able to use it if wanted. Just replace getElementById with jQuery selectors and replace XMLHttpRequest with getJson.
I hope this helps you move ahead with your problem and that you will be able to learn something new which could help you better understand javascript. Happy coding!
var button = document.getElementById('btn1');
// when user clicks on button, we want to call function start search
button.addEventListener('click', startSearch);
function startSearch(event) {
// when we are starting the search, we want to pick up the value
// input field from user
var userInputValue = document.getElementById('mySearch').value;
// this is base API url on which we can add what user wanted
var urlBase = 'https://www.superheroapi.com/api.php/10215865526738981/search/'
// if user did not provide name in input, we want to stop executing
if (userInputValue === null || userInputValue === '') return;
// if we are still in this function, append what user typed onto urlBase
var searchUrl = urlBase + userInputValue;
// call function which actually executes the remote call
performSearch(searchUrl);
}
function performSearch(searchUrl) {
// this could be jQuery getJSON if you so prefer
// here it is vanila JS solution of how to get data via AJAX call
var requestData = new XMLHttpRequest();
// because AJAX is always async, we need to wait until file is loaded
// once it is loaded we want to call function handleResults
requestData.addEventListener('load', handleResults);
requestData.open('GET', searchUrl);
requestData.send();
}
function handleResults() {
// once we get response, because we used vanilla JS, we got response
// available in this context as "this.response", however it is type string
// we need to take that string and parse it into JSON
var responseJSON = JSON.parse(this.response);
// if there is error, we didn't find any character
if (responseJSON.error) console.log('Character not found');
else {
var html = '';
responseJSON.results.forEach(function (result) {
html += '<h2>' + result.name + '</h2>';
// html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2>Power Stats ' + result.powerstats.combat + '</h2>';
html += '<p>Connections ' + result.connections.relatives + '</p>';
html += '<p>Appearance ' + result.appearance.gender + '</p>';
html += '<p>Work ' + result.work.base + '</p>';
// html += ' Profile <img src ' + result.image.url + '>';
})
// this is bad thing to do, injecting html like that into DOM
// but let's leave this lesson for later stage
// so, let's take this html and drop it onto the page
document.getElementById('demo').innerHTML = html;
}
}
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<div id="demo"></div>
const value = document.getElementById('mySearch').value;
And then use this value in your api url.
Hi guys i been trying to figure out for a long time but i suck at this, i found this code on google and i added it adn changed what i need but still doesnt work i really need this for my site: http://www.balkan-party.cf/
I found code here: http://www.samkitson.co.uk/using-json-to-access-last-fm-recently-played-tracks/
My last.fm username i need in js: alicajdin AND
Api key: 24f6b03517ad9984de417be5d10e150b
This is what i did:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=alicajdin&api_key=24f6b03517ad9984de417be5d10e150b&limit=2&format=json&callback=?", function(data) {
var html = ''; // we declare the variable that we'll be using to store our information
var counter = 1; // we declare a counter variable to use with the if statement in order to limit the result to 1
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
} // close the if statement
counter++ // add 1 to the counter variable each time the each loop runs
}); // close each loop
$('.listening-to h5').append(html); // print the information to the document - here I look for the h5 tag inside the div with a class of 'listening-to' and use the jQuery append method to insert the information we've stored in the html variable inside the h5 tag.
}); // close JSON call
});
I created that file and i tried to add on head section, footer section but it wont show recent tracks.
And yea i have scroblr installed on google crome
below </script> add the following code:
<div class="listening-to"></div>
then remove "h5" on
"$('.listening-to h5').append(html);"
so your code like this:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOUR_USERNAME&api_key=YOUR_API_KEY&limit=2&format=json&callback=?", function(data) {
var html = '';
var counter = 1;
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
}
counter++
});
$('.listening-to').append(html);
});
});
</script>
<div class="listening-to"></div>
Hope you can help. Sorry, my English is very Bad (Google Translate)
I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;
I'm trying to customise the output from a WordPress plugin called Showtime. Showtime contains the following Javascript to output what is entered in the schedule. For styling reasons I'm entering into the plugin admin area for a show -
<h3>Drivetime</h3><p>with Davie Boy</p>
The issue I have is this is literally printed out / echoed on the page and the html is not rendered / processed, as though wrapped in pre tags.
I understand the following javascript outputs the show, how could I get it to actually not echo the html but process it. Sorry if I'm not using the correct terminology.
Any help much appreciated
rob
UPDATE
Thanks for the comments - to get me thinking. This javascript is getting the Showname from a PHP script called crud.php. Looking over this I think this may be the offending line in crud.php
$showname = htmlentities(stripslashes(($_POST['showname'])));
rather than the javascript itself?
jQuery(function($){
function get_current_show() {
//Get the current show data
$.post(crudScriptURL, {"crud-action" : "read", "read-type" : "current"}, function (currentShowJSON) {
var schedule = $.parseJSON(currentShowJSON);
var outputHTML = '';
var currentShow = schedule['current-show'];
if (currentShow.showName){
var currentShowName = currentShow.showName;
var imageURL = currentShow.imageURL;
var linkURL = currentShow.linkURL;
var startClock = currentShow.startClock;
var endClock = currentShow.endClock;
outputHTML += '<div id="showtime">'+currentShowName+'</div>';
if (imageURL){
if (linkURL){
outputHTML += '<img class="showtime-image-thumbnail" src="'+imageURL+'" alt="'+currentShow.showName+'" />';
} else {
outputHTML += '<img class="showtime-image-thumbnail" src="'+imageURL+'" alt="'+currentShow.showName+'" />';
}
}
} else {
outputHTML += '<h3 class="current-show">'+currentShow+'<h3>';
}
var upcomingShow = schedule['upcoming-show'];
if (upcomingShow){
var upcomingShowName = upcomingShow.showName;
var upcomingShowLink = upcomingShow.linkURL;
var upcomingStartClock = upcomingShow.startClock;
var upcomingEndClock = upcomingShow.endClock;
if (upcomingShowLink){
outputHTML += '<h3 class="upcoming-show"><strong>Up next:</strong> '+upcomingShowName+'</h3>';
} else {
outputHTML += '<h3 class="upcoming-show"><strong>Up next:</strong> '+upcomingShowName+'</h3>';
}
outputHTML += '<span>'+upcomingStartClock + ' - ' + upcomingEndClock + '</span>';
}
$('.showtime-now-playing').html(outputHTML);
//Set a timer to update the widget every 30 seconds
setTimeout (get_current_show, (30 * 1000));
});
}
get_current_show();
});
If you have a consistent format for these, and don't really need to use symbols as part of the display, you can implement a sort of parser in the jquery function. For example, you could enter <h3>Drivetime</h3><p>with Davie Boy</p>, and in the code do something like:
var currentShowName = $('<div/>').html(currentShow.showName).text();