如何在同一页面中将jQuery变量发布到PHP?

Both my jQuery code and PHP code are in the same PHP file (not two separate files).

I want to POST jQuery Variable to the php code.

But it Shows some errors ("undefined index") when running the php file.

PHP file is as follows (test.php).

<?php 
    $country = $_POST['userCountry'];
    $ip = $_POST['userIp'];

    echo $country;
    echo $ip;
?>

<html>
<head><title></title>
    <script src = "jquery.min.js"></script>
    <script>
        $.getJSON("http://freegeoip.net/json/", function(data) {
            var country = data.country_name;
            var ip = data.ip;

            $.ajax({
                method:"POST",
                url:"test.php",
                data:{userCountry:country, userIp:ip}
            });
        });
    </script>
</head>
<body></body>
</html>
<?php 
if(!empty($_POST)){
    $country = $_POST['userCountry'];
    $ip = $_POST['userIp'];

    echo $country;
    echo $ip;
}
?>

<html>
<head><title></title>
    <script src = "jquery.min.js"></script>
    <script>
        $(document).ready(function(){
        $.getJSON("http://freegeoip.net/json/", function(data) {
            var country = data.country_name;
            var ip = data.ip;
            $.ajax({
                method:"POST",
                url:"test.php",
                data:{userCountry:country, userIp:ip},
                success:function(result){
                    $('body').html(result);
                }

            });
           });
        });
    </script>
</head>
<body></body>
</html>

Try this code. Just Tested OK

I'm not sure this is the wanted result...
But it looks like it. So try this:

(EDITED)

<html>
<head><title></title>
    <script src = "https://code.jquery.com/jquery-1.12.0.min.js"></script>

</head>
<body>
<div id="result1"></div>
<br>
<div id="result2"></div>

<script>
$(document).ready(function(){
    var country;
    var ip;

    $.getJSON("http://freegeoip.net/json/", function(data) {
        country = data.country_name;
        ip = data.ip;
        console.log(country+" "+ip);

        $("#result1").append(country);
        $("#result2").html(ip);
    });
});
</script>

</body>
</html>

Notice that there is no PHP or $.ajax... Only $getJSON.

That's because PHP compiles on the server while jQuery compiles on client. You kept both in the same file. So by the time ajax runs PHP has already been compiled thus giving you the message undefined . Make a separate file for PHP part or use the isset() and refresh the page using jQuery once the data has been submitted.