1

I need to get the IP of the client. I am able to get it through PHP variable "$_SERVER['REMOTE_ADDR']". I get this ip from server side php to html page through AJAX request but when I want to use this IP value in JavaScript it is showing that the value is undefined. any solution?

PHP code:

<?php echo $_SERVER['REMOTE_ADDR'];?>

HTML CODE:

<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>

JavaScript code:

function ip() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ip").innerHTML =
        this.responseText;
    }
  };
  xhttp.open("POST", "ip.php");
  xhttp.send();
}

function ip2() {
  setTimeout(function () {
    var ip = document.getElementById("ip").value;
    alert(ip);
  }, 1000);
}
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
Shaikh Amaan FM
  • 312
  • 4
  • 12

3 Answers3

1

First of all you should validate that you are getting the right response from your AJAX request by check that the result is certainly written to the element with id attribute "ip", and than instead of using:

var ip = document.getElementById('ip').value;

You should use Node.textContent to get the text content:

var ip = document.getElementById('ip').textContent;

Code example (without AJAX request):

function ip() {
  document.getElementById('ip').innerHTML = '127.0.0.1';
}

function ip2() {
  setTimeout(function () {
    var ip = document.getElementById('ip').textContent;
    console.log(ip);
  }, 1000);
}
<body onload="ip(); ip2();">
<kbd id="ip" ></kbd>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

You want your Ip Address in java script , so have to put ip address in that tag i think.

<?php $ip_address =  $_SERVER['REMOTE_ADDR'];?>

<body onload='ip(); ip2();'>
<kbd id='ip' ><?php echo $ip_address; ?></kbd>
Amitesh Kumar
  • 3,051
  • 1
  • 26
  • 42
0
<?php echo $_SERVER['REMOTE_ADDR'];?>
<html>
<head>
</head>
<body onload='ip();'>
<div id='ip' ></div>
</body>
</html>
<script>
function ip() {

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
    document.getElementById("ip").innerHTML =
    this.responseText;
    ip2(this.responseText);
}
};
xhttp.open("POST", "try.php");
xhttp.send();


}

function ip2(stringvalue) {
setTimeout(
       function() {
        var ip = document.getElementById("ip").value;
alert(stringvalue);
       },2000);
}
</script>

run this code you might found what is the problem.

Rizwan
  • 163
  • 2
  • 8