简体   繁体   中英

Can't post a JSON using $.ajax() or can't read it using php

I can't figure out where the problem is. This is my JS function to post the JSON:

function send(var1, var2) {
    var result;
    att = window.location;
    $.ajax({
        'crossDomain': true,
        'type': 'POST',
        'async': false,
        'global': false,
        'data': {
            "event_id": var1,
            "status": var2
        },
        'url': att + 'post.php',
        'dataType': 'json',
        success: function (data) {
            result = data['result'];
        }
    });
}

On the server side, this (file: post.php):

<?php
    echo $_POST;
?>

only prints "Array". The problem is that I have to send "data" in that exact format (I can't stringify it and then use the php json_decode() function). I also tried the « file_get_contents("php://input") » way, but still nothing. I don't understand if the problem is that I can't properly post the json or that I'm not able to read it php-side. Experiments with the GET method were fine. Sorry for my bad english and thanks everyone for the attention.

To print array you can make use of print_r() function in php

<?php
print_r(json_encode($_POST)); //use json_encode() since dataType in ajax call is json
?>

To print individual values, you can make use of echo()

<?php
 echo(json_encode($_POST['event_id']));
?>

try the following js function :

function send(var1,var2) {
   $(document).ready(function(){
      $.ajax(
      {
              url:"post.php",
        data:{event_id: var1,status: var2},
        success:function (data, textStatus){
          alert(data['status']);
        }, 
        type:"post",
                dataType: 'json'
      }
      );   
    }); 
}

and in server side "post.php" :

echo json_encode($_POST);

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