why PHP results in HTML are not defined when using JavaScript

advertisements

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);
}


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>