freegeoip doesn't work anymore - javascript

A few months ago I created a code that detect a visitor country and display the legal drinking age.
For country in EU is 18 and for other countries is 21.
I'm using the freegeoip.
The code was working great, but now I noticed that doesn't work anymore.
$.get("http://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
$("#country_code").html(response.country_code);
if(response.country_code=='AL','AD','AT','BY','BE','BA','BG','HR','CY','CZ','DK','EE','FO','FI','FR','DE','GI','GR','HU','IS','IE','IT','LV','LI','LT','LU','MK','MT','MD','MC','NL','NO','PL','PT','RO','RU','SM','RS','SK','SI','ES','SE','CH','UA','VA','RS','IM','RS','ME') {
$(".age").html("18");
} else {
$(".age").html("21");
}
}, "jsonp");
Here I dispay the age:
<span>ARE YOU</span> OVER <span class="age"></span>?
I assume that the problem is in freegeoip but I can't fix it.

You can also use ip-api.com like freegeoip :
function getDataOfIp($ip) {
try {
$pageContent = file_get_contents('http://ip-api.com/json/' . $ip);
$parsedJson = json_decode($pageContent);
return [
"country_name" => $parsedJson->country,
"country_code" => $parsedJson->countryCode,
"time_zone" => $parsedJson->timezone
];
}
catch (Exception $e) {
return null;
}
}

I just found an answer for the problem.
I noticed that the freegeoip.net website doesn't work so I changed the service.
I replaced the http://freegeoip.net/json/ with http://getcitydetails.geobytes.com/GetCityDetails?callback=?
and added <script language="Javascript" src="http://gd.geobytes.com/gd?after=-1&variables=GeobytesLocationCode,GeobytesCode,GeobytesInternet,GeobytesFqcn"></script>
Now the code works again.

Related

JSON select data at specific ID

In PHP, I've created a function to create a JSON file:
function writeJSONData(PDO $conn): void
{
$contentJSON = "SELECT * FROM tb_content";
$contentResultsJSON = $conn->query($contentJSON);
$contentJSONExt = array();
while ($JSON = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC)) {
$contentJSONExt = $JSON;
}
$infoJSON[] = json_encode(array('movies' => $contentJSONExt));
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/CineFlex/private/api/api.json";
file_put_contents($target_dir, $infoJSON);
}
In my HTML file I've created a button which sends the ID of the selected movie:
<!-- Edit Button -->
<button onclick="toggleDialog(editMovie, this.id)" id="<?php echo($info['content_id']) ?>Edit Movie</button>
My JavaScript file contains the function:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
console.log(data)
})
}
When I click on the edit button, it prints the entire JSON file in the console. Which is understandable.
Current output:
{
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
Now my issue is, I want the "dialogID" to be selected from the JSON file where it matches with "content_id". For example: When I click on a movie with 16 as "dialogID", I want the console to just print everything from that array.
Expected output:
{
"movies": [
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
}
]
}
To get it, you need to create dynamic API instead of static file content. In alternative case, you can get it only from JS loop (check all and check suitable ID). If you want to do it with API, you must change html and php script like this:
function getDataById(PDO $conn):string
{
$id = (int) $_GET['id'];
$contentJSON = "SELECT * FROM tb_content where id = :id";
$contentResultsJSON = $conn->prepare($contentJSON);
$contentResultsJSON->execute([':name' => 'David', ':id' => $_SESSION['id']]);
$rows = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC);
$contentJSONExt = array();
while ($JSON =$rows) {
$contentJSONExt = $JSON;
}
return json_encode(array('movies' => $contentJSONExt));
}
And, JS codes to change like this:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("https://my-site.com/getDataById/?id="+dialogID, function (data) {
console.log(data)
})
}
I don't know if you want to select in your php the right ID, and send back only the right one or if you want the whole json back and select in javascript.
First answer here gives the answer to dynamic php: only the right ID back from server.
I will try to answer the second possibility: all json movies back, selection in javascript.
html (3 buttons for example):
<button onclick="toggleDialog(this.id)" id="15">Edit Movie 15</button>
<button onclick="toggleDialog(this.id)" id="16">Edit Movie 16</button>
<button onclick="toggleDialog(this.id)" id="17">Edit Movie 17</button>
javascript, let say we have back the whole json movies, I put a variable here (it's supposed to be the whole json back from php):
let json = {
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
javascript function:
function toggleDialog(dialogID) {
dialogID = parseInt(dialogID);
json.movies.every(e => {
if (e.content_id === parseInt(dialogID)) {
console.log(e.content_id);
console.log(e.title);
console.log(e.description);
return false;
}
return true;
})
}
You iterate through the json.movies (it's an object) with "every" instead of forEach. With every, you can break the loop when condition is met dialogID === content_id with return false. You have to put return true at the end of the loop otherwise it breaks immediately.
Your content_id are numbers, so parseInt on the dialogID. If coming from php json, it'll normally be string so no need for that.
A friend of mine helped me out:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
for (let i = 0; i < data['movies'].length; i++) {
if (data['movies'][i]['content_id'] == dialogID) {
$('#editMovieTitle').val(data['movies'][i]['title'])
}
}
})
}

How to translate text generated with javascript

So adminlte has the trans() function which works perfectly when its used in blade.php.
Lets say i have a form that if completed incorrectly throws a warning. I do the checking in js. And I want to have a pop up message that is displayed. The message need to be translatable.
What I tried is - in the php file make an array with the translatable text:
$returnArr = [
'titleSuccess' => trans('title.success'),
'titleWarning' => trans('title.warning')
];
Then retrieve it in the js and display the message.
$.post('/' + currentLanguage.locale + '/admin/page/error', {id:sId, note:note})
.done(function (result) {
if (result.status === 1) {
msg
.html(createAlert(result.titleSuccess, result.msg, 'success'))
.slideDown('fast');
} else {
msg
.html(createAlert(result.titleError, result.msg, 'danger'))
.slideDown('fast');
}
})
The problem is these keywords- title.warning, title.success are translated but in the default language that is set in the system. Not the one that the user has set.
Why is that happening? And is there a way to use trans() in js?

jQuery search in an object using a string

UPDATE
23 November 2016:
I was very close to the solution. Rory McCrossan has solved it for me, so I accepted his answer. BUT I changed the code for faster developing. I want to share this so you can use it to.
JSON langfile-v1.0.json
{
"nl": {
"text1":"Hallo Wereld!",
"text2":"voorbeeld.com",
"text3":"Ik hou van Stack Overflow"
},
"en":{
"text1":"Hello World!",
"text2":"example.com",
"text3":"I love Stack Overflow"
}
}
Javascript / jQuery script.js
//Creating an GLOBAL object
var languageObject;
//Get the language json file
$.get("langfile-v1.0.json", function(response){
languageObject = response; //Assign the response to the GLOBAL object
setLanguage(); //Calling the setLanguage() function
});
//Call this function to set the language
function setLanguage() {
$("lang").html(function() {
var userLang = navigator.language || navigator.userLanguage;
var langSupported = false; //Check if the user language is supported
$.each(languageObject, function(key) {
if (userLang == key) {
langSupported = true;
}
});
if (langSupported) {
//Users language is supported, use that language
return languageObject[userLang][$(this).html()];
} else {
//User language is NOT supported, use default language
return languageObject.en[$(this).html()];
}
});
}
HTML page.html
<lang>text1</lang> <br>
<lang>text2</lang> <br>
<lang>text3</lang>
Demo
You can check how this works on JSFiddle (with a slightly different code because I dont know how to inculde the langfile-v1.0.json file)
Click here for demo
OLD QUESTION POST:
I want to search in a object using a string.
Example:
JSON
{
"nl": {
"lang":"Nederlands",
"header-WelcomeText":"Welkom op de website",
"header-Sub1":"Hoofdpaneel"
},
"en": {
"lang":"English",
"header-WelcomeText":"Welcome on the website",
"header-Sub1":"Dashboard"
}
}
Javascript/jQuery
var output;
$.get("file.json", function(response){
output = response; //This is now a object in javascript
});
This all works, here what i want:
//The jQuery code
$('span .lang').text(output.nl.$(this).attr("data-lang"));
//The HTML code
<span class="lang" data-lang="header-Sub1"></span>
I know this will not work, but I know there will be a way to achief this.
To make this work there's a few changes you need to make.
when accessing the key of an object through a variable you need to use bracket notation.
to reference the element through the this keyword you need to run your code within it's scope. To do that you can pass a function to the text() method which returns the value you need from the object.
the .lang class is directly on the span, so you shouldn't have the space in your selector.
With all that in mind, this should work for you:
var output = {
"nl": {
"lang": "Nederlands",
"header-WelcomeText": "Welkom op de website",
"header-Sub1": "Hoofdpaneel"
},
"en": {
"lang": "English",
"header-WelcomeText": "Welcome on the website",
"header-Sub1": "Dashboard"
}
}
$('span.lang').text(function() {
return output.nl[$(this).data("lang")];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="lang" data-lang="header-Sub1"></span>

$watch function gives undefined - AngularJS

I am a very basic beginner in AngulerJS.
What i'm trying to do is that when a user clicks on a product, the types of that product come up, then they pick a type and the colors of that type come up. I've tried using the same system that gets the types to show but my colors keep coming up undefined.
<section class="colorDisplay">
<div class="mcolor" ng-repeat="color in shoColor">
<img ng-src="{{color.image}}"/></div>
</section>
script.js
$scope.prod = {"name":"Pens"};
$scope.typ = {"id":1};
$scope.$watch('prod.name',function(){
$http.get("products/"+$scope.prod.name+".json").success(function(data){
$scope.type = data;
});
$scope.$watch('typ.id',function(type){
$scope.shoColor = type[$scope.typ.id].colors;
});
})
JSON File
{
"types":[
{
"name":"laser",
"id":0,
"image":"d-u-b/pens/laser.png",
"colors":[
{
"color":"Black and Silver",
"image":"colors/blacksilver.png",
"prodimage":"d-u-b/pens/laser/blacksilver.png"
},
{
"color":"Red",
"image":"colors/red.png",
"prodimage":"d-u-b/pens/laser/red.png"
}
]
},
{
"name":"plain",
"id":1,
"image":"d-u-b/pens/plain.png",
"colors":[
{
"color":"Yellow",
"image":"colors/yellow.png",
"prodimage":"d-u-b/pens/plain/yellow.png"
},
{
"color":"Blue",
"image":"colors/blue.png",
"prodimage":"d-u-b/pens/plain/yellow.png"
},
{
"color":"Cyan",
"image":"colors/cyan.png",
"prodimage":"d-u-b/pens/plain/cyan.png"
},
{
"color":"Silver",
"image":"colors/silver.png",
"prodimage":"d-u-b/pens/plain/silver.png"
}
]
}
]
}
I'm trying to call the id number of a certain types colors, putting it into something like this: types[0].colors, where the 0 is the inserted id number.
No matter where I put the watch function or what I name it, it's either the "0" is undefined or "colors" is undefined.
What am I doing wrong this time?
change this
$scope.shoColor = type[$scope.typ.id].colors;
to
$scope.shoColor = $scope.type[type].colors;
and
$http.get("products/"+$scope.prod.name+".json").success(function(data){
$scope.type = data;
to
$http.get("products/"+$scope.prod.name+".json").success(function(response){
$scope.type = response.data;
Here is a working fiddle of what i think you are trying to achieve.
note: - i have hard coded the $scope.type data in order for it to work on jsfiddle.
i have used nested ng-repeats as it follows the same code structure as the json response.
Hope it helps,
D

search to json pull from API to html all nice and pretty?

I'm working on a project for a client where the site visitors can search Campusbooks.com and get the results displayed.
Contacted Campusbooks and was told that I can use their API and have fun... and that's it.
I've found how to create a search form that pulls the results as posts the raw JSON. There's no formatting in the JSON so what I am getting is
"response":{
"#attributes":{
"status":"ok",
"version":"10"
},
"label":{
"#attributes":{
"plid":"3948",
"name":"Textbooks 4 You"
}
},
"page":{
"#attributes":{
"name":"search"
},
"count":"1000",
"pages":"100",
"current_page":"1",
"results":{
"book":[{
"isbn10":"1463590776",
"isbn13":"9781463590772",
"title":"Life on the Mississippi",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"13.99",
"pages":"316",
"publisher":"CreateSpace",
"published_date":"2011-06-19",
"edition":"Paperback",
"rank":"99999999",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/51sXKpUcB0L.SL75.jpg"
},
{
"isbn10":"1406571253",
"isbn13":"9781406571257",
"title":"How to Tell a Story and Other Essays (Dodo Press)",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"12.99",
"pages":"48",
"publisher":"Dodo Press",
"published_date":"2008-02-29",
"edition":"Paperback",
"rank":"214431",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/41S5poITLpL.SL75.jpg"
},
{
"isbn10":"0520267192",
"isbn13":"9780520267190",
"title":"Autobiography of Mark Twain, Vol. 1",
"author":"Mark Twain",
"binding":"Hardcover",
"msrp":"34.95",
"pages":"743",
"publisher":"University of California Press",
"published_date":"2010-11-15",
"edition":"1",
"rank":"344",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/41LndGG6ArL.SL75.jpg"
},
{
"isbn10":"1936594595",
"isbn13":"9781936594597",
"title":"The Adventures of Huckleberry Finn",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"8.88",
"pages":"270",
"publisher":"Tribeca Books",
"published_date":"2011-04-07",
"edition":"Paperback",
"rank":"1285",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/51J4kzmKcpL.SL75.jpg"
}
]
}
}
}
}
I need to take that output and make it all nice and pretty in HTML.
The script I am using to do this with at this point is:
// Vanilla JS Example: CampusBooksJS
(function () {
var CampusBooks = require('campusbooks'),
// This key is a special dummy key from CampusBooks for public testing purposes
// Note that it only works with Half.com, not the other 20 textbook sites, so it's not very useful,
// but good enough for this demo
cb = CampusBooks.create("T4y4JKewp48J2C72mbJQ"),
cbform = document.getElementById("vanilla-campusbooksjs-form");
// Note: This is for demonstration purposes only (with modern browsers)
// Use MooTools or jQuery for a real-world solution that works cross-browser
// (and please don't write you own, it's not worth it)
function cbSearch(e) {
var cbform = this,
search = cbform.querySelector("select").value,
data = cbform.querySelector("input").value;
e.preventDefault();
if (!data) {
alert("Try Typing in a Keyword or Two First");
return;
}
alert("Your Search: " + search + ": " + JSON.stringify(data, null, ' '));
var params = {};
params[search] = data;
cb.search(params).when(function (err, nativeHttpClient, data) {
if (err || !data) {
alert("Error: " + JSON.stringify(err) || "No Data Returned");
return;
}
document.querySelectorAll("#vanilla-campusbooksjs-display")[0].innerHTML = JSON.stringify(data, null, ' ');
});
}
// This will work on modern browsers only
cbform.addEventListener("submit", cbSearch, false);
}());
The search form is:
<form id="vanilla-campusbooksjs-form">
<select name="cb_search">
<option>keywords</option>
<option>author</option>
<option>isbn</option>
</select>
: <input name="cb_value" type="text"/>
<input type="submit" value="Search"/>
</form>
<div>
<pre>
<code id="vanilla-campusbooksjs-display">
</code>
</pre>
</div>
I hope this isn't too long of a post. If additional information is needed, please let me know.
I would suggest using Mustache Templates. Its easy to apply mustache templates to JSON and get some markup. It can be done on the server or client side.

Categories