Reputation: 34006
I have an HTML form. When visitor submits form, a javascript method is invoked. This method sends an AJAX request to my server's php file. My problem is i need to get the visitor's ip address. But because of AJAX request calls php file, $_SERVER['REMOTE_ADDR'] gives me my server's address. How can i get visitor's ip, in this case? Thank you
<form onsubmit="sendData(); return false;">
// some data here
</form>
function sendData(){
// do some work, get variables
$.ajax({
url:"/mypage.php",
type:"GET",
data: { name: e },
success : function(data) {
// do some work
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
}
// in mypage.php
public function useData() {
$name=$_GET["name"];
$ip = $_SERVER['REMOTE_ADDR'];
}
Upvotes: 10
Views: 16673
Reputation: 1
try the code below though modify it as it is meant to run onloading the page, it uses jquery and some free ip api's
$(document).ready(function(){
$.getJSON("https://api.ipify.org?format=json", function(data){
var userIP = data.ip;
$.getJSON("https://api.ipgeolocationapi.com/geolocate/" + userIP, function(data){
var userLat = data.geo.latitude;
var userLng = data.geo.longitude;
// You can now use the user's latitude and longitude to determine if they're within your geo fence
});
});
});
Upvotes: 0
Reputation: 1038850
$_SERVER['REMOTE_ADDR']
will give you the IP address of the client. But since presumably you are using the same machine as server and client you get the same IP which is normal. Once you host your website into a web server and access it remotely from a different machine you will get the address of that remote machine.
So there's nothing more you need to do. Your code already works as expected.
Upvotes: 29
Reputation: 747
The ajax request is still originating from the client, it should be giving the clients IP not the servers.
Upvotes: 1