Post var javascript in PHP

0

I have this in head:

<script>
    $(document).ready(function(){
    $.getJSON("http://freegeoip.net/json/", function(data) {
        var country = data.country_name;
        var ip = data.ip;
        var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        $.ajax({
            method:"POST",
            url:"file.php",
            data: {
                userCountry:country,
                userIp:ip,
                vw:w
            }
        });
       });
    });
</script>

This is no file.php:

$maxwidth = $_POST['vw'];
$maxcountry = $_POST['userCountry'];
$maxip = $_POST['userIp'];

But POST never gets there. Does anyone help?

    
asked by anonymous 02.07.2017 / 21:25

2 answers

1

% of jQuery% must have success or done functions set to that is triggered:

$(document).ready(function(){
    $.getJSON("//freegeoip.net/json/", function(data) {
        var country = data.country_name;
        var ip = data.ip;
        var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        $.ajax({
            method:"POST",
            url:"file.php",
            data:{userCountry:country, userIp:ip, vw:w},
        }).done(function (resposta) {
           console.log("sucesso", resposta);
        }).fail(function (erro) {
           console.log("erro", erro.status);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In this case, I used $.ajax to get the answer and .done to catch the error if any error occurred.

    
02.07.2017 / 21:57
0

You may have to use json_decode in php:

$data = json_decode(file_get_contents("php://input"));

if(property_exists($data, 'userCountry') || property_exists($data, 'userIp') || property_exists($data, 'vw')){

  $userCountry = $data->userCountry;
  $userIp = $data->userIp;
  $vw = $data->vw;

}

Also try using console.log (); to see if the variables are set to the right values.

console.log(userCountry);
console.log(userIp);
console.log(vw);
    
02.07.2017 / 22:05