Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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?