简体   繁体   中英

Reading json object sent via ajax in php file

I am trying to solve one problem with reading json object sent via ajax request in php file and I am keep gettin null in the console.

Javascript file

//create function to send ajax request
function ajax_request(){
  console.log("hello");
 var post_data = {
    "news_data" : 'hello',
    "news_date" : '1st march'
}
$.ajax({
    url : 'index.php',
    dataType : 'json',
    type : 'post',
    data : post_data,
    success : function(data){
        console.log(data);
    }
 });
}

//on click event
$('#news_post_button').on('click', ajax_request);

and php file which is only for testing to see what i get

<?php
 header('Content-Type: application/json');



  $aRequest = json_decode($_POST);

  echo json_encode($aRequest[0]->news_data);

?>

Try using json_last_error function. And print out Your post as a string:

print_r($_POST);
echo '<br /> json_last_error: '.json_last_error();

This way You will see what You got and what potentially had gone wrong.

For testing this kind of things I suggest Postman chrome extension.

You aren't sending a JSON object at all.

You are passing jQuery an object, so it will serialise it using standard form encoding.

<?php
   header('Content-Type: application/json');
   echo json_encode($_POST["news_data"]);
?>

If you want to actually send a JSON text, then you need to:

  • Set the content type of the request
  • Encode the data as JSON and pass it as a string to data

See this answer for an example .

To read the JSON, you would then need to read from STDIN and not $_POST as per this answer /

You can read properties of objects directly in $POST var, like this:

$_POST['news_data'] and $_POST['news_date']

You can check the post vars through the developer tools of the browser, in network tab.

The dataType property of the $.post options specifies the format of data you expect to receive from the server as a response, not the format of the data you send to the server. If you send data by the method POST - just like you do, if you use $.post - there is no need to call $aRequest = json_decode($_POST); on the serverside. The data will be available as a plain PHP array.

If you just want to get the news_data field as a response from the server, your serverside script should look something like this:

<?php
header('Content-Type: application/json');
$post = $_POST;
echo json_encode($post['news_data']);
?>

Notice, that you should check for the key news_data whether it is set.

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