2

I want to run a this code only if a visitor is from a specific country

window.onload=function(){ document.getElementById("buy").click(); };

I tried this but didn't work :

 var requestUrl = "http://ip-api.com/json";
var xhr = new XMLHttpRequest();
xhr.open('POST', requestUrl, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
    var json = JSON.parse(xhr.responseText)
    if(json.country == 'France'){
        document.getElementById("buy").click(); 
    };
};
xhr.send(null);
Aymn
  • 21
  • 4
  • How would you determine the visitor's country? – Kosh Nov 24 '18 at 21:34
  • 1
    This is what im asking for , like use a json link like this one : http://ip-api.com/json and then put rule like if visitor from "germany" run the script and if not just ignore it – Aymn Nov 24 '18 at 21:36
  • You're asking something different, IMHO. – Kosh Nov 24 '18 at 21:37
  • @charlietfl i didn't get an answer bro , its like this but this one didn't work : function Get(http://ip-api.com/json){ xhr.open('POST', GET, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onload = function () { var json = JSON.parse(xhr.responseText); if (json.country == 'Germany') { document.getElementById("buy").click(); } }; xhr.send(null); – Aymn Nov 24 '18 at 21:40
  • Hi Aymn, and welcome to StackOverflow. This question looks like it may have been asked before. See if this answers your question: https://stackoverflow.com/questions/48278024/how-to-detect-browser-country-in-client-site?noredirect=1&lq=1 – ethan.roday Nov 24 '18 at 21:41
  • @err1100 thanks for your answer but its not im asking for , i've modified the question and may you could understand more thanks – Aymn Nov 24 '18 at 21:46
  • Are you asking specifically about how to use the `ip-api.com` API? – ethan.roday Nov 24 '18 at 21:48
  • Possible duplicate of [How to detect browser country in client site?](https://stackoverflow.com/questions/48278024/how-to-detect-browser-country-in-client-site) – Jack Bashford Nov 24 '18 at 21:48
  • No , i want that the script i puted work only for visitors from france – Aymn Nov 24 '18 at 21:51
  • @JackBashford no jack i couldn't find the answer im looking for there , like i said before that little code up there want to run only for visitors from france if from other country just ignore it – Aymn Nov 24 '18 at 21:52

1 Answers1

0

Here's an easy way to do it with that same API:

fetch('http://ip-api.com/json').then(response => {
    return response.json();
}).then(data => {
    if (data.country == "France") {
        document.getElementById("buy").click();
    }
});

Or if you prefer jQuery:

$.getJSON("http://ip-api.com/json", function(data) {
    if (data.country == "France") {
        $("#buy").click();
    })
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79