1

I have tried to set data in header. eg: header('Access-Control-Allow-Origin: *'); etc but i am getting error: "Response to preflight request doesn't pass access control check".

var ip_address = $('#ip_address').val();
$.ajax({ 
    url: 'http://www.geoplugin.net/json.gp?ip='+ip_address,
    success: function(output) {
        $('#country_name').val(JSON.parse(output).geoplugin_countryName);
    }
});
Tony Greig
  • 63
  • 7
  • Please read this : https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work And solution maybe is this : https://stackoverflow.com/a/11691776/2282880 – Meloman Aug 22 '17 at 08:35

3 Answers3

2

It seems that you are trying to get country name from IP address from geolugin.net. Instead of an ajax call you can try this code. It works form me.

$.getJSON("https://cors-anywhere.herokuapp.com/http://www.geoplugin.net/json.gp?ip="+$('#ip_address').val(),function(response){
        $('#country_name').val(response.geoplugin_countryName);

    });
PRADEEP PANDEY
  • 344
  • 2
  • 15
  • Yes i was trying to get country name of visitors ip address on my website and your solution works. Thanks for your help. – Tony Greig Aug 22 '17 at 09:13
2

For jQuery:

// In this example, if you make an ajax request to the following website
var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';
//  But if you make it from a browser, then it will work without problem ...

// However to make it work, we are going to use the cors-anywhere free service to bypass this
var proxy = 'https://cors-anywhere.herokuapp.com/';

$.ajax({
    // The proxy url expects as first URL parameter the URL to be bypassed
    // https://cors-anywhere.herokuapp.com/{my-url-to-bypass}
    url: proxy + myUrl,
    complete:function(data){
        console.log(data);
    }
});

Or using the shortcuts of $.get, $.getJSON or $.post :

var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';

var proxy = 'https://cors-anywhere.herokuapp.com/';

var finalURL = proxy + myUrl;

// With the get JSON (frequently used) method
$.getJSON(finalURL, function( data ) {
    console.log(data);
});

// With the get method
$.get(finalURL, function( data ) {
    console.log(data);
});

// With the post method
$.post(finalURL, function( data ) {
    console.log(data);
});
Tony Greig
  • 63
  • 7
1

This might be helpful

Code to get country name from ip

ash45
  • 36
  • 3