Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Robert Marczak
Robert Marczak
12,358 Points

Json and php

How do I read json object send with $.ajax in php file. One of the arguments send within $.ajax is data: post_data. In js file post_data is an a js object with some static values.

var post_data = {
    "news_data" : 'hello',
    "news_date" : '1st march'
  }

and ajax request

$.ajax({
    url : 'news.php',
    dataType : 'json',
    type : 'post',
    data : post_data,
    success : function(data){
        console.log(data);
    }
  });
}

I can't figure out how to read sent data in php file

3 Answers

I think you are looking for json_decode(). news.php will receive post_data in $_POST. Use json_decode() on that to get an object or array that you can work with in php. See:

http://php.net/manual/en/function.json-decode.php

Robert Marczak
Robert Marczak
12,358 Points

I decode it in php than encode it back and send it back to js file and print it in the console to see what I have. I get null. This is my full code

//create function to send ajax request
function ajax_request(){
  console.log("hello");
var post_data = {
    "news_data" : 'hello',
    "news_date" : '1st march'
  }

  $.ajax({
    url : 'news.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

<?php
header('Content-Type: application/json');
$aRequest = json_decode($_POST);

echo json_encode($aRequest);

?>

Php code is purely for testing.

Is the data by chance stored in $_POST["post_data"] instead of just $_POST?