1

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

?>
0

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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.

1 Comment

Few mistakes but finally got there. Wanted to vote for your answer but I need reputation to be 15. Thank anyway.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.