Alexey B.
Alexey B.

Reputation: 3

Javascript: sendind json data via ajax to php

i got stuck with JSON , the client side code:

  $.getJSON('http://freegeoip.net/json/?callback=?', function(userData) {
                console.log(JSON.stringify(userData, null, 2));
                });

            $.ajax({ 
                    type: "POST", 
                    url: "listener.php",  
                    data: JSON.stringify($.userData),   
                    success: function(res) {      
                    alert(res);
                    }
            })

and php server side code:

$data = json_decode($_POST['userData']);
$response = 'I got parameters '.count($data).'\n';
foreach ($data as $key=>$value) {
    $response .= 'key: '.$key.'; value: '.$value.'\n';
}
echo $response;

the point is that i got no errors but looks like php didnt got any data or cant serialize it, I just started to learn web programming and I will be glad to any advice, thanks!

Upvotes: 0

Views: 70

Answers (2)

André
André

Reputation: 477

Javascript:

 $.getJSON('http://freegeoip.net/json/', function(userData) {
        console.log(JSON.stringify(userData, null, 2));
        $.ajax({
                type: "POST",
                url: "listener.php",
                data: userData,
                success: function(res) {
                    alert(res);
                }
        })
});

PHP:

$data = $_POST;
$response = 'I got parameters '.count($data).'\n';
foreach ($data as $key=>$value) {
    $response .= 'key: '.$key.'; value: '.$value.'\n';
}
echo $response;
  1. You should remove the callback param or at least remove the question mark behind.
  2. You should send the Ajax request inside the getJSON callback. Otherwise it is running parallel... and does not know about userData.
  3. You should not stringify your results, so you get a working array in PHP.

Note: For further usage (e.g. in database queries), you should escape received data to avoid injections!

Upvotes: 0

TailsxKyuubi
TailsxKyuubi

Reputation: 49

JavaScript:

$.ajax({ 
  type: "POST", 
  url: "listener.php",  
  data: {'foo':'bar'},   
  success: function(res) {      
    alert(res);
  }
});

PHP:

$data = $_POST;
$response = 'I got parameters '.count($data).'\n';
foreach ($data as $key=>$value) {
   $response .= 'key: '.$key.'; value: '.$value.'\n';
}
echo $response;

Upvotes: 0

Related Questions