Using Cookie and user IP in JS
116   1  

Using Cookie and user IP in JS

  07 Jan 2018
  Coding Category
Using Cookie and user IP in JS

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookies were invented to solve the problem: how to remember user information. We want to check IP and save it with Cookie.

I use Cookie JS to save cookies. Check Github to read more about this plugin in this address: js-cookie

And also I use ipinfo to get user IP and save it in Cookie. You can check other features in IPinfo

And these are codes after use <script src="/path/to/js.cookie.js"></script>:


var user_ip, user_city, user_country, user_page;

$.get("https://ipinfo.io", function(response) { //get some info of users from ipinfo.io and save them to variables

    user_ip = response.ip;

    user_city = response.city;

    user_country = response.country;

    user_page = window.location.href; //save user page landing

}, "jsonp");

setTimeout(function() {

    $.ajax({

        url: apiaddress, //my api.php address to relation to MySQL DB

        data: {action: 'user_ip', user_ip: user_ip, user_city: user_city, user_country: user_country, user_page: user_page},

        type: 'POST',

        dataType: 'JSON',

        success: function (result) {

            if (result['status'] == 'OK' && typeof Cookies.get( 'user_ip' ) == 'undefined') { //check if cookie is set or not. I do not want to show messages to user every time and make him angry

                alert("We use cookies to ensure that we give you the best experience on Giliapps. If you continue to use this site, we will assume that you are happy with it :-) Have a nice time 🌹"); //You should use your framework to show notification and beautify it

                Cookies.set( 'user_ip', user_ip, { expires: 360 } ); //save cookie with name, value and expiration date by days

            }

        }

    });

}, 20000); //run those after 20 seconds

Author: Ismael Azaran

Do you like it? Share it with your friends.

Categories

Tags