Robert Marczak
Robert Marczak

Reputation: 11

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);

?>

Upvotes: 1

Views: 130

Answers (4)

ILCAI
ILCAI

Reputation: 1234

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.

Upvotes: 0

Juan de Parras
Juan de Parras

Reputation: 778

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.

Upvotes: 0

Quentin
Quentin

Reputation: 944442

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/

Upvotes: 0

T.Z.
T.Z.

Reputation: 2172

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.

Upvotes: 1

Related Questions