I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!
Here is the function I'm using to query data
function weather(position) {
var apiKey = '';
var url = '';
var data;
// console.log(position);
$.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {
$('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
$('.js-current-item2').html(data.currently.summary);
gif(data.currently.icon)
city(position.coords.latitude + "," + position.coords.longitude)
});
}
And here is the function for pulling images from GIPHY
function gif(status) {
var apiKey = '';
var url = 'http://api.giphy.com/v1/gifs/search?q=';
var query = status;
$.getJSON(url + query + apiKey, function(data) {
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
});
}
In your function gif(status) while setting the image choose a random value from data array instead of fixed
change
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
to
var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');
Related
I am getting some data from an API using $.getJSON. I am appending the information to a div once I recieve it. But sometimes the data takes time to load and hence I want to display a loading functionality, until something is appended to the div. How do i do this?
function getApis(){
var source = document.getElementById('toplace').value;
var dest = document.getElementById('fromplace').value;
var options = "";
var container = document.getElementById('div-form');
var disp_info = document.getElementById('train-info');
// var train_block = document.getElementById("train-block");
container.style.display = 'none';
disp_info.style.display = 'inline-block';
var url = "http://api.railwayapi.com/between/source/" + source + "/dest/" + dest +"/date/18-09/apikey/abvsl2868/";
$.getJSON(url,function(data){
console.log(data);
// I WANT TO DISPLAY A LOADING FUNCTIONALITY UNTIL THIS DATA IS APPEARING ON THE SCREEN
$("#train-info").append("Total Number of trains running from " + source + " to " + dest + " : " + data.total + "<br><br><br>");
data.train.forEach(function(trains){
options = "<div style='border:1px solid black;font-family:'Kaushan Script''> <br>Train Name : " + trains.name + "<br><br>" +"Train Number : " + trains.number + "<br><br>Departure Time : " + trains.src_departure_time + "<br><br> Arrival Time : " + trains.dest_arrival_time + "<br><br></div>";
// $('#train-block').append(options + "<br>");
$('#train-info').append(options + "<br>");
});
});
}
You need to display your image, or whatever before the ajax call
$("#myDiv").html("<img src='spinner.gif'>");
$.ajax({
dataType: "json",
url: url,
data: data,
success: $("#myDiv").html("success");
});
Add a spinner image tag in the container element.
<div id="#train-info"><img src="loading-spinner.gif"/></div>
Before appending data to it, remove this image tag.
I've got a JQuery click event that doesn't seems to be firing at all. If I am missing something I'm almost certain it's something trivial. I've tried debugging the code via Chrome but the button click on the Filter button is not even hitting the breakpoint.
$('#filter').click(function () {
var dataurl;
var visit = $('#visitFilter').val;
var dns = $('#dnsFilter').val;
var visitdate = $('#visitDateFilter').val;
var entrypage = $('#entryPageFilter').val;
var timeOnSite = $('#timeOnSiteFilter').val;
var timeonsiteselector = $('#timeOnSiteSelector').val;
var pages = $('#pagesFilter').val;
var cost = $('#costFilter').val;
var city = $('#cityFilter').val;
var country = $('#countryFilter').val;
var keywords = $('#keywordsFilter').val;
var referrer = $('#referrerFilter').val;
dataurl = "http://localhost:56971/VisitListFilter/28/" + visit + "/" + dns + "/" + visitdate + "/" + entrypage + "/" + timeOnSite + "/" + timeonsiteselector + "/" + pages + "/" + cost + "/" + city + "/" + country + "/" + keywords + "/" + referrer + "/" + "?format=json";
$('#VisitListTable').bootstrapTable('refresh', {url: dataurl});
});
I've also created a fiddle here with the full code: https://jsfiddle.net/W3R3W0LF666/epu54yc4/1/
Remember .val() is a function.
You need to use () when invoking a function. Currently you are just passing the function reference.
var visit = $('#visitFilter').val(); //Note ()
It is getting fired.
Blockquote
Replace all .val with .val() as .val() is a jquery function for getting values.as :
var dns = $('#dnsFilter').val;
I have a weather web api,which I need to show weather report of current city in website.Whenever the code calls in the API, it results only in old data.Data never changes and when I run the web API URL on the browser it results exactly what I want.
Please help me what could be the reason for the cached data.
webAPI
http://api.openweathermap.org/data/2.5/weather?lat=26.894049&lon=80.942686&mode=json
my code
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + 'mode=json&rand=' + Math.random(), function (data) {
var wind = {};
var temp = {};
wind = data.wind;
temp = data.weather;
var clouds = '%' + data.clouds.all;
var description = data.weather[0].description;
var temp = data.main.temp - 273.15;
var humidity = data.main.humidity + '%';
var icon = data.weather[0].icon;
weatherImg = "<img height=\"45\" width=\"45\" style=\"border: medium none; width: 45px; height: 45px;position:relative;top:-10px; background: url('http://openweathermap.org/img/w/" + icon + ".png') repeat scroll 0% 0% transparent;\" alt=\"title\" src=\"http://openweathermap.org/images/transparent.png\">";
document.getElementById('weatherImg').innerHTML = weatherImg;
document.getElementById('current_temp').innerHTML = (temp) + '°C';
document.getElementById('current_wind').innerHTML = ' ; ' + wind.speed + 'Km/h';
document.getElementById('city_name').innerHTML = data.name;
});
tested your code working fine for me some time api response is slow but other than that every thing looks ok to me
htttp://jsfiddle.net/navneetccna/un2u5j0v
Shouldn't the url in your script prefix mode with &. You should throw this in a fiddle / be more specific. You say you're getting old data. Are you getting an old JSON response that doesn't change at all, or infrequently?
I have a list of my recent Tumblr audio posts coming in through the Tumblr API and with each post, an artist summary from the Last.fm API is attached. I have the data coming in correctly, but the audio posts are not showing up in chronological order. Every time I refresh the page, they appear in random order. I would like to have the most recent audio post appear at the top. Here is my code:
$(document).ready(function() {
var user = "nycxnc";
var key = "###";
var type = "audio";
var limit = "5";
var url = "https://api.tumblr.com/v2/blog/" + user +
".tumblr.com/posts/" + type + "?callback=?&filter=" + type +
"&limit=" + limit + "" + key + "";
$.getJSON(url, function(data) {
$.each(data.response.posts, function(i, item) {
var artist = item.artist;
var track = item.track_name;
var url2 =
"http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&track=" +
track + "&artist=" + artist +
"&api_key=###&autocorrect=1&format=json&callback=?";
$.getJSON(url2, function(data) {
$.each(data, function(i, item) {
artist_summary = item.bio.summary;
artist_image = item.image[4]["#text"];
$(".au-wrapper").append(
'<div class="audio-wrapper"><img src=' + artist_image +
'><div class="audio-meta"><span class="audio-title">' +
track + '</span><div class="audio-artist">' + artist +
'</div></div><div class="url">' + artist_summary +
'</div></div>');
});
});
});
});
});
How can I combine the data from two API in the correct order, if the second JSON url (Last.fm) is dependent on data from the Tumblr API? I'm new to Javascript and I'm creating this script as a learning experiment, so any help would be very appreciated. (: Thank you.
Long back I used JSON and was successful to get the hash tag feeds from twitter and facebook. But presently I am just able to get the feeds but its not being updated constantly that means it not been update dynamically. I guess I need to ajaxify it, but I am not able to do that since I am not aware of ajax. Here is the code which I have used to get the twitter search feeds.
$(document).ready(function()
{
$("#Enter").click(function(event){
var searchTerm = $("#search").val() ;
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data)
{
$("#tweets").empty();
if(data.results.length < 1)
$('#tweets').html("No results JOINEVENTUS");
$.each(data.results, function()
{
$('<div align="justify"></div>')
.hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span><a href="http://www.twitter.com/'
+ this.from_user + '">' + this.from_user
+ '</a> ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
});
});
function makeLink(text)
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
The code below should help you. What I've done is moved the code which fetches the tweets into a function. This function is then called every X seconds to update the box. When the user enters a new search term and clicks "Enter", it will reset the timer.
var fetchSeconds = 30; //Number of seconds between each update
var timeout; //The variable which holds the timeout
$(document).ready(function() {
$("#Enter").click(function(event){
//Clear old timeout
clearTimeout(timeout);
//Fetch initial tweets
fetchTweets();
});
});
function fetchTweets() {
//Setup to fetch every X seconds
timeout = setTimeout('fetchTweets()',(fetchSeconds * 1000));
var searchTerm = $("#search").val();
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data) {
$("#tweets").empty();
if (data.results.length < 1) {
$('#tweets').html("No results JOINEVENTUS");
}
$.each(data.results, function() {
$('<div align="justify"></div>').hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span>' + this.from_user + ' ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
}
function makeLink(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Hope this helps