J. Doe doe doe doe J. Doe doe doe doe - 5 months ago 12
jQuery Question

Cannot get value from PHP variable

I am using JQuery Ajax (and I am sure that things have changed since the last time I used it) but I am having trouble pulling the information from the variable. Basically I am getting the IP address and logging how long it took that IP to load the page fully. Here is my code...

getIP.php

<?php
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
echo $ip; //Just to check if it worked - it shows the IP
?>


Event listener that calls it

(function() { //Test if document fully loaded - used to test speed
window.addEventListener("load", function() {
$.ajax({
url: '../php/getIP.php',
type: 'POST',
success: function(result)
{
setTimeout(function alertUser(){alert(result['ip']);}, 40);
}
});
}, false);
})();
(function() { //If any errors occur send them to a txt file
window.addEventListener("load", function() {
setTimeout(function() {
var timing = performance.timing;
console.log(timing.loadEventEnd - timing.responseEnd);
}, 0);
}, false);
})();


Now when I echo it in the PHP file it shows the IP but when I alert the value of it to test it I get undefined why is this happening?

Answer

Your output is a string:

echo $ip; //Just to check if it worked - it shows the IP
      ^---e.g. 127.0.0.1

and then you try to treat it as an array:

setTimeout(function alertUser(){alert(result['ip']);}, 40);
                                            ^^^^^^

Since it's not an array, this won't work. try just alert(result).