3

I using some GeoIP service to place country flag on pages depends on country IP. And I need to cache JSON response for all pages on my site.

This code placed into header.php:

$.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
  $('#flag').html("<a class='fancybox-inline int' href='#international'><img src='/images/flags/"+data.countryCode+".png'></a>");
  }

Is it possible to cache it with $.ajaxSetup({ cache: true })? - seems to not work.

Or probably better to use HTML5 localStorage, but I'm not sure how to do that.

I also tried JSONCache plugin, but it did not work for me.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Dmitry
  • 544
  • 1
  • 5
  • 12
  • try to use $.ajax it has functionality you are looking for. – Manish Parmar Jun 29 '13 at 10:42
  • @Mac `$.getJSON` is an ajax request to a service that returns JSON specifically. It's a shortcut method so you don't have to specify `type: 'JSON'` ergo - he is using ajax ;) – ddavison Jun 29 '13 at 10:53

2 Answers2

10

You could use localStorage like that:

var smartIp = JSON.parse(localStorage.getItem('smartIp'));

if (!smartIp) $.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
    smartIp = localStorage.setItem('smartIp', JSON.stringify(data));
});

DEMO

So, in your specific case, you should use this code in your header.php page:

var smartIp = JSON.parse(localStorage.getItem('smartIp'));

if (!smartIp) $.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
    smartIp = localStorage.setItem('smartIp', JSON.stringify(data));
    $('#flag').html("<a class='fancybox-inline int' href='#international'><img src='/images/flags/" + data.countryCode + ".png'></a>");
});
else $('#flag').html("<a class='fancybox-inline int' href='#international'><img src='/images/flags/" + smartIp.countryCode + ".png'></a>");
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • @kasperTaeymans do you mean 'unecessary' instead? But localstorage can only store string, not javascript object so how would you do that without 'sringified' js object? – A. Wolff Jan 05 '14 at 12:27
  • The max that you can save this way is 5mb per domain. http://diveintohtml5.info/storage.html – vumaasha Dec 05 '14 at 11:21
8

$.getJSON() is equivalent to

$.ajax({
  dataType: "json",
  url: 'http://smart-ip.net/geoip-json/ip_address',
  data: data,
  success: function(data){ // do something here }
});

In this form you can add additional parameters, such as cache:true, or any other $.ajax parameters you might need.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103