Now we're going to make it a wire protocol.
This is an important slide.
It would almost be easier if this was 40 lines of code on this slide.
Because then you would expect that it's difficult and challenging and
amazing things are happening.
This is amazing.
It's just four lines of code.
Okay, so and
I'll go through this in a demonstration as well in addition to just these slides.
So we're going to have a file called json.php.
And so sleep(2) just makes it so this thing slows down a little bit so
you can see what's happening as you're watching it in your developer console.
If we're going to send json back to the browser,
we want to tell it the content type.
And if we go all the way back, way, way, way back, content type can be text,
it can be HTML, it can be a JPEG, it can be a PNG.
So this is a response header that tells the browser
what it is that this next blob of stuff is.
And we can tell it, this is json.
Let me tell that utf-8 in case we have Asian characters or whatever.
That's a header and just like anything inside PHP, we're in PHP now,
anything in PHP, before you produce any output, you gotta set all your headers.
So that's why that's first.
So now I have some PHP code.
Now really, this will do something, maybe read some stuff from the database,
but we don't worry about that right now.
For now, we're just going to make an array.
This is a php array, first maps to first things, second maps to second thing.
This is when we're inside of php, and
then we're going to serialize, and then we got the wire protocol.
We're going to send the wire protocol, and then we're going to receive that, and
then we're going to parse it in JavaScript.
That's exactly what we're doing in this picture right now.
The act of serializing a PHP array
uses a function that's built into PHP called json_encode.
You pass in an array.
It can either be a linear array or a key value array, and
it automatically makes the right JSON.
In this case it's a key value array, so it makes a JSON object with key, key value,
value, right.
And then this, This
is what gets echoed, I mean literally the output is this when you look at it.
That is serialized version of a php array.