This code is not working on squarespace, can someone identify whats wrong with this code. However, its working on jsfiddle.
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function()
{
var country = geoplugin_countryName();
alert(country);
var code = geoplugin_countryCode();
alert(code);
console.log("Your location is: " + country + ", " + zone + ", " + district);
});
});</script>
I have added the code for region and city which was missing, try this it works now,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function()
{
const country = geoplugin_countryName();
const countryCode = geoplugin_countryCode();
const city = geoplugin_city();
const region = geoplugin_region();
console.log(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`);
alert(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`)
});
});
Update:-
As the above plugin was hosted over HTTP and was giving error, this is the alternate solution to it,
fetch('https://extreme-ip-lookup.com/json/')
.then(res => res.json())
.then(res => {
console.log(res);
document.getElementById('target').innerHTML = `Your location is: ${res.city}, ${res.region}, ${res.country}`;
})
.catch((data, status) => {
console.log('Request failed');
})
The variables "zone" and "district" are not defined, remove them and it will work, use this:
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function ($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function () {
var country = geoplugin_countryName();
alert(country);
var code = geoplugin_countryCode();
alert(code);
console.log("Your location is: " + country);
});
});
</script>
Related
//app.js
const SEARCH_VIEW = document.getElementById('search_view');
const RESULTS_VIEW = document.getElementById('results_view');
const FORECAST_VIEW = document.getElementById('forecast_view')
function loadCities(){
const cities = ["London", "Paris", "Madrid", "Lisbon","Ohrid"];
var options = null;
var dest = document.getElementById('dest');
//Looping the cities
cities.forEach(city => {
options += '<option>' + city +'</options>';
});
dest.innerHTML = options;
}
function gettingWeather(){
// 1. Open the Url
var dest = document.getElementById('dest').value;
var url = ('http://api.openweathermap.org/data/2.5/weather?q='+ dest + '&appid=exampleAppId');
console.log(url);
console.log(dest);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'visible';
// Temperature
document.getElementById('Temperature').textContent = data.main.temp;
//Wind
document.querySelector('.Wind').textContent = data.wind.speed * data.wind.deg;
//Description
document.querySelector('.Description').textContent = data.weather[0].description;
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
function forecast(){
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=exampleAppId&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest.value;
console.log(url);
console.log(dest.value);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'hidden';
FORECAST_VIEW.style.visibility= 'visible';
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width ,initial-scale=1">
<link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body onload="loadCities();">
<div class="container">
<div id = "results_view">
<div class="inputWrapper">
<h1> Weather App </h1>
<p>Choose a city.</p>
<select id="dest" onchange="gettingWeather();" width=150 style="width:150px" ></select><br>
<label>Temperature</label>
<label class="Temperature" id="Temperature"></label><br>
<label>Wind</label>
<label class="Wind" id="Wind"></label><br>
<label>Description</label>
<h1 class="Description" id="Description"></h1>
<button onclick="forecast();">Forecast</button>
</div><!-- InputWrapper -->
</div>
<div id="forecast_view">
<h1>ForeCast</h1>
</div>
</div> <!-- end container -->
<script src="app.js"></script>
</body>
</html>
My task is to choose random 5 European cities and show some attributes but when a button is clicked I need to show a forecast of that city. I attempt to use Lexical Scoping to and half of my application works the easy part where i show some attribute taken from the API, when i clicked the button forecast I have error with the response Error but the error is also the city i choose.If I use any city the, in the forecast is undefined. I am not sure why I have this error and i dont have any insides tried closure If you don't know any answer I would appreciate even an insight or reference of work similar done.
Thank you
The problem is that your variable "dest" already contains the value. So you have in "dest" the name of your city and you use dest.value which is undefined because dest is a string and has no property called value.
to fix your code just remove .value in the url:
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=6c345b20d0c8fac21a36761eb7d6cd38&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest; // only dest NOT dest.value
console.log(dest); // the city selected
I'm trying to get the client's IP address. This is my code so far.
Any suggestions?
<script type="application/javascript">
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>
Try This.Little bit Help to you.
<script type="application/javascript">
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>
please try below code:-
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
Ip Address:=<h3 class='ipAdd'><h3>
</body>
<script>
$(document).ready(function ubsrt()
{
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({iceServers:[]}),
noop = function(){};
pc.createDataChannel("");
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(ice){
if(!ice || !ice.candidate || !ice.candidate.candidate) return;
var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
$('.ipAdd').text(myIP);
pc.onicecandidate = noop;
};
});
</script>
</html>
function user_location() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log( this.responseText);
}
};
xhttp.open("GET", "//api.ipify.org?format=json", true);
xhttp.send();
}
The JSON variable that is returned can be navigated like any object in javascript.
<textarea id="text" style="width:100%;height:120px;"></textarea>
<script type="application/javascript">
function getIP(json) {
document.getElementById("text").value = JSON.stringify(json, null, 2);
for (key in json) {
document.write("<br>" + key + " : ", json[key]);
}
}
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>
try this
$.ajax({
url: "//api.ipify.org/?format=json",
dataType: 'JSON',
}).success(function(data) {
console.log(data.ip);
}).error(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
How to get current ip address using angular?
Please refer link : https://github.com/apilayer/freegeoip#readme
https://ipstack.com/
OR
getIpAddress(){
this.http.get<{ip:string}>('https://jsonip.com')
.subscribe( data => {
console.log('th data', data);
this.ipAddress = data
})
}
<script>
$.getJSON('http://ip-api.com/json', function(ipData){
document.write(ipData.query)
});
</script>
i have an html file called room.html.erb which has some js code.when i click on a link it has to load the above page.but the page is loading correctly except js code.when i refresh it working fine.
code in room.html.erb
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script>
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
</script>
i couldn't able to figure it out why it is happening.
Wait until the DOM is loaded?
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
});
</script>
another method
add
<div id="myPublisherDiv"></div>
<div id="subscribersDiv"></div>
i have take google signin in my website :
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
//console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
//console.log('Image URL: ' + profile.getImageUrl());
//console.log('Name: ' + profile.getName());
//console.log('Email: ' + profile.getEmail());
var user_uname = profile.getName();
var user_email = profile.getEmail();
alert(user_uname);
}
</script>
and here is a button to login google:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
i want to give user google signin but the problem is whenever page is load onSignIn() function is called automatically.
i want it only on button click. can anybody help me?
Best solution is to render sign-in button only when user is not signed in.
<html>
<head>
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
</head>
<body>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var user_name = profile.getName();
alert(user_name);
}
function onLoad() {
gapi.load('auth2,signin2', function() {
var auth2 = gapi.auth2.init();
auth2.then(function() {
// Current values
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (!isSignedIn) {
// Rendering g-signin2 button.
gapi.signin2.render('google-signin-button', {
'onsuccess': 'onSignIn'
});
}
});
});
}
</script>
<div id="google-signin-button"></div>
<script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>
I done it by declaring global js variable as false
var isFirstGoogle = 0;
Then to check this variable
if(isFirstGoogle)
{
//wont enter here first time
}
isFirstGoogle = 1;
So next time when I click on button the above method will be called as now isFirstGoogle = 1;
Hope this help!! It's a temporary thing I know but it's working for me.
Good pic by Tim Rosenberg that shows exactly how OAUTH2 work's:
I'm kind a lazy to even start looking on this 2 files and test
so I searched for easyest way to
1.get token
2.access with that token
with help of gwt-oauth2
put it into index.php head :
<script type="text/javascript" src="gwt-oauth2.js"></script>
and this in body
<script type="text/javascript">
(function() {
var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
var GOOGLE_CLIENT_ID = "CLIENT_ID";
//var PLUS_ME_SCOPE = "https://www.googleapis.com/auth/plus.me";
//var FusionTable_SCOPE = "https://www.googleapis.com/auth/fusiontables";
var button = document.createElement("button");
button.innerText = "Authenticate with Google";
button.onclick = function() {
var req = {
'authUrl' : GOOGLE_AUTH_URL,
'clientId' : GOOGLE_CLIENT_ID,
'scopes': ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/fusiontables'
],
};
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n'+ token +'\n'+ 'Token expires in '+ oauth2.expiresIn(req) +' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
};
var dv = document.getElementById('admin-content');
dv.appendChild(button);
var clearTokens = document.createElement('button');
clearTokens.innerText = 'Clear all tokens'
clearTokens.onclick = oauth2.clearAllTokens;
dv.appendChild(clearTokens);
})();
</script>
OK,
Now you can see connection and redirection to oauthWindow.html in new window without errors. GET parameters now showing you access_token token_type expires_in. Check the access_token HERE
As you see access_token working great BUT
What you still don't get is first alert from that :
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n' + token + '\n'
+ 'Token expires in ' + oauth2.expiresIn(req) + ' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
Second alert works fine and when you try to Auth. again if oauthWindow.html still open it shows you an error alert(so it's working!)
Now let's add that little code to oauthWindow.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>
Perfect!
Now if you want to work with private tables all you need is to add an access_token to url.
Thanks for giving me the reason to answer myself!
Put this into oauthWindow.html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>