ajax json weather auto refresh data - javascript

I am trying to make an weather auto refresh which is reloading for changes every 5 seconds. It loads perfectly first time on load but my setinterval is not working correctly. It goes of every 5 seconds but it doesnt update my menu even though changes has been made?
Here is what i got so far:
var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude + "," + position.coords.longitude;
jQuery(document).ready(function(weather) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/lang:AR/forecast/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather_html = ("<h3>Results of " + parsed_json.current_observation.display_location.city +
"</h3>" + "<p>Temperature: " + parsed_json.current_observation.temp_f + "</p>" +
"<p>Current Weather: " + parsed_json.current_observation.weather + "</p>" + "<p>Wind Gusts: " +
parsed_json.current_observation.wind_mph + "mph</p>" + '<img src="http://icons.wxug.com/logos/PNG/wundergroundLogo_black_horz.png" width="200"</img>');
$('#returned_data').html(weather_html).hide().fadeIn("slow");
$(document).ready(function() {
weather(); //Get the initial weather.
setInterval(weather, 600000); //Update the weather every 10 minutes.
});
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون الطقس ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
});
});
}
It doesn't seem to be working.

$(document).ready(function() {
var weather = function() {
... your ajax function here ....
};
weather();
-- add your timer functionality here and wire it to call weather --
});
You have to declare weather as a function and then call the function. Then create your timer to repeatedly call the weather function in order to fulfill your update call.

Related

freecodecamp API takes forever to load, or doesn't load at all

JS/Jquery: I thought the problem was because I did not wrap my code in a document.ready(), however I tried doing that and the same problem occurred. Sometimes the weather, temp and image, especially the image, take more than 5 minutes to load. This was created in codepen.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude, function(json) {
$("#current-weather").html(json.weather[0].main);
var temp = json.main.temp;
var fahtemp = temp * (9 / 5) + 32;
var celtemp = (temp - 32) * (5 / 9);
$("#temp").text(Math.round(json.main.temp) + " °C");
$("#image").attr("src", json.weather[0].icon);
$("#fah").on("click", function() {
$("#temp").text(Math.round(fahtemp) + " °F");
});
$("#cel").on("click", function() {
$("#temp").text(Math.round(celtemp) + " °C");
});
});
});
}
$(document).ready(function() {
$.get("https://api.ipdata.co", function(response) {
$("#location").html(response.city + ", " + response.region);
}, "jsonp");
});
<script src="https://fcc-weather-api.glitch.me/"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://api.ipdata.co"></script>
API's can have variable speeds depending on the host of the API. There is a chance it has nothing to do with your code, but that it is their server struggling to keep up.
I believe your geolocation request is taking a long time. Look into the PositionOptions and add a timeout to the geolocation request.
You might also want to add a max age option to the geolocation request.

Show a new GIF on each page visit or page reload

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 + ')');

Javascript Geolocation API

Iam trying get the location of the user and than pass it to an Weather API.i need to the location and also to get the API data and insert the location to API url as a coordinates. this is my code and it isn't working :
$(document).ready(function() {
var weatherLocal;
var url = {
"apiKey": "&appid=API_KEY",
"api": "http://api.openweathermap.org/data/2.5/weather?lat=",
"units": "&units=metric",
};
function geoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback);
}else {
console.log("not avialable");
}
}
function successCallback(position) {
url.lat = position.coords.latitude;
url.lon = position.coords.longitude;
}
function preLoader() {
var u = successCallback();
var apiUrl = url.api + u + url.apiKey + url.units;
$.getJSON(apiUrl, getData);
console.log(apiUrl);
}
function getData(data) {
weatherLocal = data;
console.log("the longitude is " + weatherLocal.coord.lon + " and the latitude is " + weatherLocal.coord.lat + " and the description is " + weatherLocal.weather[0].main + " and the city is " + weatherLocal.name + " temperature is " + weatherLocal.main.temp);
}
preLoader();
});

Jquery Global Variable Scope/Wrong Values [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a problem with the final values assigned to global variables (success, count_error, error) in my code below. Before the outputting section if I don't include "alert( success );" all values are zero. However if I include that line then the correct values are outputted.
Why is this, is there something wrong with the variable scope ?
<html>
<head>
<script src="../jquery-1.11.0.js"></script>
<script>
var rows_all = [1,2,3,4,5,6,7,8,9,10],
success = 0,
count_error = 0,
error = [];
/////////////////////////////////////////////////////////////////////////
// In test_addresses create lat/lon [number] from coordinates [string] //
/////////////////////////////////////////////////////////////////////////
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function(data) {
//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});
//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function(key1, val1) {
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function(data1) {
$.each(data1.rows, function(key2, val2) {
address = val2['address'];
lat_lon = val2['coordinates'];
if (lat_lon.indexOf('?') === -1) {
lat = parseFloat( lat_lon.split(',')[0] );
lon = parseFloat( lat_lon.split(',')[1] );
$.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
success++; //number of successfully completed operations
}
else {
count_error++; //#error operations
list = {};
list["id"] = val1; //#which cartodb_id in table
list["address"] = address; //#which matching address in table
error.push(list);
}
});
});
});
alert( success );
//Ouput text
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
$.each(error, function(key4, val4) {
$("#result").append("<br> " + val4["id"] + " : " + val4["address"]);
});
$.each(rows_all, function(key5, val5) {
$("#result").append("<br>" + key5);
});
});
</script>
</head>
<body>
<p id="result"></p>
</body>
</html>
It is an asynchronous request, so the alert() will fire before getting the data. So you should change the code like,
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function (data) {
//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});
//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function (key1, val1) {
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function (data1) {
$.each(data1.rows, function (key2, val2) {
address = val2['address'];
lat_lon = val2['coordinates'];
if (lat_lon.indexOf('?') === -1) {
lat = parseFloat(lat_lon.split(',')[0]);
lon = parseFloat(lat_lon.split(',')[1]);
$.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
success++; //number of successfully completed operations
alert(success);
} else {
count_error++; //#error operations
list = {};
list["id"] = val1; //#which cartodb_id in table
list["address"] = address; //#which matching address in table
error.push(list);
}
});
//Ouput text
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
$.each(error, function (key4, val4) {
$("#result").append("<br> " + val4["id"] + " : " + val4["address"]);
});
$.each(rows_all, function (key5, val5) {
$("#result").append("<br>" + key5);
});
});
});
});
You should put the code inside the scope of $.getJSON itself. So it will run only after getting the data.
Actually its not alert() doing the magic. If you put an alert, the success event will happen with in less timespan, before the user clicks ok button. Within that time all the values will be populated.

retrieving the twitter search feeds dynamically using ajax

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

Categories