Reputation: 3
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
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;
Note: For further usage (e.g. in database queries), you should escape received data to avoid injections!
Upvotes: 0
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