Accessing a variable from js file - javascript

Wrote the code for the main site, the geolocation code and the geocoder code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Electromart</title>
<!-- <link href="//db.onlinewebfonts.com/c/8274996f8cf973b15814827fa281e485?family=TechnojunkW00-Regular" rel="stylesheet" type="text/css"/>-->
<link rel="stylesheet" href="css/eshop.css">
</head>
<body>
<header class="header">
<div class="header__container">
<div class="topheader">
<div class="topheader1">
<?php
?>
</div>
</div>
<div class="header__item">
<div class="logoimage">
<img src="images/logo3.jpg" width="100" height="75" id="idsettingsforlogo" ></img>
</div>
</div>
</div>
<script type="text/javascript" src="js/geoloc.js"></script>
<script type="text/javascript" src="js/geocode.js"></script>
</header>
<footer class="footer">
</footer>
</body>
</html>
geocode.js
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: lat + ',' + lng}, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK || !results[0]) {
return;
}
var result = results[0];
var city, region, country;
for (var i = 0; i < result.address_components.length; i++) {
if (result.address_components[i].types[0] === "locality") {
city = result.address_components[i];
}
if (result.address_components[i].types[0] === "administrative_area_level_1") {
region = result.address_components[i];
}
if (result.address_components[i].types[0] === "country") {
country = result.address_components[i];
}
}
// alert(city.long_name + ", " + region.long_name + ", " + country.short_name)
console.log(results);
});
Tell me how you can access the city and country variables of the geocode.js file in the main file in the php block. Not sure how to use the Tags (), if you can do without them, write about it.
P.S. In the geocode function, the alert function was used to display the variables, with direct access to the city, country, region variables, and how to display these variables in main.html or main.php - how to access them?

An example you can use Cookie like(example you must edit):
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
Else you can use

js can set cookies and reload the page. And php from cookies will take data.
(or can php define geo data, example: https://www.php.net/manual/en/book.geoip.php)

Related

I want to show text in div with javascript

i am trying to make a javascript stopwatch here and i want to add time to div.circle and i don't know whats wrong in this code please help me!! thanks
<-- this is html code --->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>stopwatch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box">
<h1>Stopwatch</h1>
<div class="circle"></div>
<div class="buttons">
<button>Start</button>
<button>Stop</button>
<button>Reset</button>
</div>
</div>
</body>
<script>
<-- this is js code -->
let min = 0;
let sec = 0;
let mil = 0;
let time = document.getElementsByClassName("circle");
time = min + " : " + sec + " : " + mil ;
time.innerHTML = time;
console.log (time);
</script>
</html>
let time = document.getElementsByClassName("circle");
time = min + " : " + sec + " : " + mil;
time.innerHTML = time;
Those lines actually set the time variable as an element, but then break it and put it inside a string.
Should be like that:
const time = document.getElementsByClassName("circle");
time.innerHTML = min + " : " + sec + " : " + mil;
Your code has some very fundamental pieces missing. I have changed it a bit to show something on button click but it will require way more efforts than that. I will highly recommend you to go through some tutorial in HTML, CSS, JS for a day or two.
const button = document.getElementsByTagName("button")[0];
button.onclick=() => {
let min = 0;
let sec = 0;
let mil = 0;
let time = document.getElementsByClassName("circle")[0];
let timeString = min + " : " + sec + " : " + mil ;
time.innerHTML = timeString;
console.log(timeString);
}
<div class="box">
<h1>Stopwatch</h1>
<div class="circle"></div>
<div class="buttons">
<button>Start</button>
<button>Stop</button>
<button>Reset</button>
</div>
</div>

Changing Date should change data

Hello what I am not understanding why when the user inputs the date it it doesn't update the URL. I am taking the NASA API for the APOD and trying to make it interactive, the issue here is that when I manually change the URL the api data loads that data, but I lost on why my user input data is not working for it.
// Go to https://api.nasa.gov/index.html#apply-for-an-api-key to get an API Key
var apodContain = document.getElementById('apod');
var API_KEY = 'XEXvzGBBdF14FSu6UZyzoPYqazSsUkSwAsI8730G';
var datePick = document.getElementById('date');
datePick.max = todaysDate();
datePick.value = todaysDate();
var date = datePick.value;
var url = 'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY + '&date=' + date;
function makeApiRequest(url) {
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function () {
if (myRequest.readyState === XMLHttpRequest.DONE) {
if (myRequest.status === 200) {
var responseText = myRequest.responseText;
myRequest.onload = function () {
var responseJson = JSON.parse(responseText);
console.log(responseJson);
renderHTML(responseJson);
}
} else {
var errorMessage = document.getElementById('error');
errorMessage.innerHTML = "This date this not work";
}
}
}
// intializes AJAX
myRequest.open('GET', url, true);
myRequest.send();
};
makeApiRequest(url);
datePick.addEventListener('change', function(e){
date = datePick.value;
url = 'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY + '&date=' + date;
})
function todaysDate() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
return year + '-' + month + '-' + day;
datePicker.setAttribute("max", datePicker.value);
}
function renderHTML(data) {
var htmlString = "";
htmlString = "<img src = " + data.url + "></img>" + "<h1>" + data.title + "</h1>" + "<p>" + data.explanation + "</p>";
apodContain.insertAdjacentHTML('beforeend', htmlString);
}
h1{
text-align: center;
font: bold;
}
h5 {
text-align: center;
font: bold;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 500px;
height: 500px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>INFO 343 APOD</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>INFO 343 APOD</h1>
<div id="apod"></div>
<h5>Choose your date: <input id="date" type="date"></input></h5>
<div id="error"></div>
<script src="js/app.js" type="text/javascript"></script>
</body>
</html>
.
You forgot to add
datePick.addEventListener('change', function(e){
date = datePick.value;
url = 'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY + '&date=' + date;
makeApiRequest(url); // <- this
})

Don't find why my function don't change the temperature degree from Celsius to Fahrenheit

I do a weather app for Free code camp, but i don't know why my button don't change the temperature from celsius to fahrenheit.
I think it's a problem for the recuperation of the variable but i don't know where.
I try some change in my code but i just go around in circles.
This is my javascript :
$(document).ready(function(){
var long;
var lat;
var celsius;
var fahrenheit;
navigator.geolocation.getCurrentPosition(function(position){
long = position.coords.longitude;
lat = position.coords.latitude;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&lang=fr'+'&units=metric&appid=d475e2ed504ab40f4de6c1b3cba9ebcc';
$.getJSON(url, function(data){
var weatherType = data.weather[0].description;
var windSpeed = data.wind.speed;
var icon = data.weather[0].icon;
var city = data.name;
var country = data.sys.country;
var description = data.weather[0].description;
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
$('.card').html( city + '<br> Temp: '+Temp+' °C'+ '<br> Wind Speed:'+windSpeed+'M/s');
$('.icon').html('<img src="http://openweathermap.org/img/w/' + icon + '.png" /> ' + '<br>'+weatherType);
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
$('.btn').on('click', function() { change (); })
console.log(city);
console.log(weatherType);
console.log(windSpeed);
console.log(icon);
};
})
})
});
and the HTML :
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<title>Weather App</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class='col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 weather' >
<div class="col-sm-6 text-center card">
</div>
<div class="col-sm-6 text-center text-uppercase icon">
</div>
<button type="button" class="btn degree">°C/°F</button>
</div>
</div>
</div>
<div class="text-center footer">by Mathieu Dupré-Fontana
</div>
<script src="js/app.js"></script>
Can somebody help me please?
Ps: Sorry for my bad English, i'm French .
celsius appears to be a number, not a string, when Temp is set to the value of celisus, Temp is set to a number, not a string
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
Temp would not be equal to "fahrenheit" or "celcius" within change function
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
}
.html() should also be called within change() function, if the expected result is to toggle Celcius and Fahrenheit rendering at HTML on click at element.

sessionStorage displays undefined in IE11?

I am working on web related applications.When i try to display sessionStorage item it returns "undefined".
IE settings also changed but still i am getting same.
Login.html page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var currentDate = new Date,
dformat = [(currentDate.getMonth() + 1),
currentDate.getDate(),
currentDate.getFullYear()].join('/') +
' ' +
[currentDate.getHours(),
currentDate.getMinutes(),
currentDate.getSeconds()].join(':');
function unicsession(length) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
var sess = "";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
sess += chars.charAt(i);
}
return sess;
}
function generate() {
var intime = dformat;
sessionStorage.setItem("logintime", intime);
var username = document.getElementById("Username").value;
sessionStorage.setItem("username", username);
var unisession = unicsession(5);
sessionStorage.setItem("unisession", unisession);
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input id="Username" type="text" />
</td>
</tr>
<tr>
<td>
Click here
</td>
</tr>
</table>
</body>
</html>
home.htm page code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var getid = sessionStorage.getItem("username");
var logintimes = sessionStorage.getItem("logintime");
var unicsessionid = sessionStorage.getItem("unisession");
var currentDate = new Date,
outformat = [(currentDate.getMonth() + 1),
currentDate.getDate(),
currentDate.getFullYear()].join('/') +
' ' +
[currentDate.getHours(),
currentDate.getMinutes(),
currentDate.getSeconds()].join(':');
function Getout() {
alert("Login Id: " + getid + " ; login Time: " + logintimes+" ; Unic Session-Id : "+unicsessionid+" ; Logout Time : "+outformat);
}
</script>
</head>
<body>
<input id="logout" type="button" value="Logout" onclick="Getout()"/>
</body>
</html>
When i click on login page it redirect to home page and after click on logout button in home page it displays undefined.
How can i resolve this issue.
Thanks in advance for help.
sessionStorage is not avialable from IE if you access your files via your local filesystem. Use any local server to serve your scripts as http

getJSON not working in Safari

Can someone help explain why the following code works in Chrome and IE, but not Safari. I believe the issue is somewhere with the getJSON. It is returning the JSON and works in other browsers, again just not safari. Thanks
Link to actual page: Link to actual page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Lenward Cunningham" />
<meta name="keywords" content="Louisiana Post Game Scores" />
<meta name="description" content="Post Game" />
<meta name="robots" content="all" />
<meta name="copyright" content="Lenward Cunningham" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
<title>Louisiana Post Game</title>
<link rel="apple-touch-icon" href="img/acadianaPGicon.png">
<link rel="stylesheet" type="text/css" href="assets/_styles.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id='header'><img src="img/acadianaPG200.jpg"></div>
<div id='content'></div>
<script type="text/javascript">
$(function() {
var url = "https://script.google.com/macros/s/AKfycbwFp0U_pYseCIXVUVfK_wOMoTgno76sk-JXDMGmPResdseOX3Xj/exec";
/*Populate list from JSON */
$.getJSON(url)
.done(function(data) {
for (var d in data) {
/*Process JSON Parameters*/
var game = data[d];
console.log(game)
if (game.matchup) {
var matchUp = game.matchup.split('\n');
var matchUp1 = matchUp[0];
var matchUp2 = matchUp[1];
}
var score1 = '';
var score2 = '';
if (game.score) {
var score = game.score.split('\n');
score1 = score[0];
score2 = score[1];
}
var gameStatus = game.gameStatus;
/*if (game.matchup === null || game.matchup === '')
continue;*/
$('#content').append(
"<div class='game'>"+
"<div class='team'><span class='rank'></span>"+matchUp1+"<span class='score'>"+score1+"</span></div>"+
"<div class='team'><span class='rank'></span>"+matchUp2+"<span class='score'>"+score2+"</span></div>"+
"<div class='status'>"+gameStatus+"</div>"+
"</div>"
);
}
})
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-51502655-1', 'googledrive.com');
ga('send', 'pageview');
</script>
</body>
</html>
Use this json format
$.getJSON(
"https://script.google.com/macros/s/AKfycbwFp0U_pYseCIXVUVfK_wOMoTgno76sk-JXDMGmPResdseOX3Xj/exec",
function (data) {
for (var d in data) {
/*Process JSON Parameters*/
var game = data[d];
console.log(game)
if (game.matchup) {
var matchUp = game.matchup.split('\n');
var matchUp1 = matchUp[0];
var matchUp2 = matchUp[1];
}
var score1 = '';
var score2 = '';
if (game.score) {
var score = game.score.split('\n');
score1 = score[0];
score2 = score[1];
}
var gameStatus = game.gameStatus;
/*if (game.matchup === null || game.matchup === '')
continue;*/
alert();
$('#content').append(
"<div class='game'>" +
"<div class='team'><span class='rank'></span>" + matchUp1 + "<span class='score'>" + score1 + "</span></div>" +
"<div class='team'><span class='rank'></span>" + matchUp2 + "<span class='score'>" + score2 + "</span></div>" +
"<div class='status'>" + gameStatus + "</div>" +
"</div>"
);
}
}
);

Categories

Resources