AnushkaM AnushkaM - 5 months ago 25
Javascript Question

How to POST jQuery variables to PHP in same page?

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>

Answer
<?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