How To POST RAW JSON to a PHP API using jQuery and AJAX Function

Gordon McNevin
29-12-2018 09:00:00

Here is a super simple example of how to quickly and easily post RAW JSON to a PHP API file using jQuery and Ajax, and get a response back in JSON and write this to the browser.

What are we doing?

We first create a simple Javascript dictionary and set a title. Next we convert this dictionary into a JSON string and send it via jQuery Ajax POST to the same file but setting the mode to API. We then wait for a response.

The PHP file checks for the API mode, reads the body of the POST and converts this RAW JSON into an array. It then creates a simple array, sets the title to something similar to the raw input, outputs this array as a JSON string and then exits.

The simple page then reads the response from the API and writes the title to the page.

See the source code for this below...

Hope this helps!