Post var javascript in PHP

Asked

Viewed 70 times

0

I got this in the 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 in the.php file:

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

But the POST never gets there. Someone helps?

  • Have you added jquery.js lib before? Because in mine your code worked

  • Unless, you want a return to your page

2 answers

1

The $.ajax jQuery needs to have Success or done functions set for it to be 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 case I used the .done to get the answer and the .fail to catch the error, if any error has occurred.

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 the.log() console to see if the variables are set to the right values.

console.log(userCountry);
console.log(userIp);
console.log(vw);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.