简体   繁体   中英

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!

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;

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 (eg in database queries), you should escape received data to avoid injections!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM