PHP – Accessing data sent over POSTed AJAX

The more I work with PHP, the crazier it becomes.

I was working on the contact form of my new personal site last week when I decided I would submit it over AJAX to make it all nice and fancy. It would be simple: just nab the input values in JavaScript then POST to the PHP for validation and sending by sending the values though JSON.

Since the JSON would be transmitted via POST, I assumed the following line would work:

json_decode($_POST, true);

You can imagine my surprise when the resulting decoding returned NULL and $_POST turned out to be empty.

Naturally after this I set out to solve this issue and receive my data. That is when I came across this Stack Overflow post which was similar to my issue. As I looked through it and other sites, I kept coming across the following line, which I decided to test:

json_decode(file_get_contents('php://input'), true);

To my surprise, this worked! However, it makes no sense to me. The documentation on file_get_contents() is about reading a file on the server or getting the contents of another website- not accessing data POSTed using AJAX! Where does php://input come from? There is no mention of it in the documentation. Why does POSTed via AJAX data get piped through here instead of $_POST as one might logically expect?

I still do not have answers for these questions, and if I did I am sure they would make more sense than PHP’s behavior here, but I wrote this post to remind me how to accessed data sent using this method but also so you can know and learn how to do it too, that is, if you ever need to do it. 🙂

-Caleb

Advertisements

Triangular Reactions

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s