Sending JSON Headers from PHP

I ♥ data. My favorite way of sending data to the front end is of course, JSON. So here’s a quick snippet to get you up and running with some JSON destined for the front end.

First off, PHP is great with arrays. Luckily there’s a nifty little function PHP includes called “json_encode()”. It takes a multidimensional PHP array and converts it to JSON. However, in order to interact with it correctly on the front end, your AJAX script is going to need to know it’s “content-type” JSON. So here goes….

$arr = array('data', 'data2' => 'more data', 'data3' => array('even', 'more', 'data'));

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($s_floors);

Basically all I’m doing is filling an array with some string data and setting some headers to make sure the client browser recognizes the data as JSON. The most important header is the last one “application/json” tells the browser to expect something it can work with in Javascript. Then in the front end you might do something like…

$.get('example.php', function(data) {
                    console.dir(data);
                }, "json");

This script (requires jQuery) grabs data and expects to receive JSON. That’s it!

K, bored, bai!

One thought on “Sending JSON Headers from PHP

  1. You are encoding the incorrect variable (probably a typo)

    echo json_encode($arr);

    😉

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.