简体   繁体   中英

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 PHP variable. Basically I am getting the IP address and logging how long it took that IP to load the page fully and then display it.

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 json_encode(array('ip' => $ip));
?>

Event listener that calls it

var IPAddresses = [];

//Anonymous functions - used for quality control and logging

(function() { //Used to test how long it took for a user to connect - uses a php script with it
    window.addEventListener("load", function() {
        $.ajax({
            url: '../php/getIP.php',
            type: 'POST',
            success: function(result) 
            {
                setTimeout(function alertUser(){IPAddresses.push(result.ip);}, 40);
            }
        });
    }, false);
})();
(function() {
    window.addEventListener("load", function() {
        setTimeout(function() {
            for (var i = 0; i < IPAddresses.length; i++)
            {
                var timing = performance.timing;
                console.log(IPAddresses[i] + " " + timing.loadEventEnd - timing.responseEnd);
            }
        }, 0);
    }, false);
})();

EDIT

Now I don't get errors but it does not seem to print the IP address or push it into the array at all. I am basically trying to get it to [ip] [loadtime] It gives a NaN error

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) .

try to use "json_encode"

echo json_encode(array('ip' => $ip));

and in ajax

   success: function(result) 
        {
            setTimeout(function alertUser(){alert(result.ip);}, 40);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM