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

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

    
$return = array("status" => "success""title" => "Title sent = " $json['title']);
    echo 
json_encode($return);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>HTML Basic</title>
</head>
<body>

<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="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    console.log( "ready!" );

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

    $.ajax({
        type: "POST",
        url: "index.php?mode=api",
        dataType: "json",
        data: JSON.stringify(data),
        success: function(msg){
            console.log(msg.status);
            console.log(msg.title);
            $("#api_output").html(msg.title);
        }
    });
});
</script>

</body>
</html>

Hope this helps!