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...

if($_GET['mode'] == "api") {
$json json_decode(file_get_contents('php://input'), true);

$return = array("status" => "success""title" => "Title sent = " $json['title']);
<!DOCTYPE html>
    <title>HTML Basic</title>

<h1>POST RAW Json to PHP and Process Response</h1>

<p>Output from the api will appear below...</p>

<p id="api_output"></p>

<script src=""></script>
$(document).ready(function() {
    console.log( "ready!" );

    var data = {};
    data['title'] = "Testing RAW JSON";

        type: "POST",
        url: "index.php?mode=api",
        dataType: "json",
        data: JSON.stringify(data),
        success: function(msg){


Hope this helps!