How to send JSON string using AJAX, fetchAPI to php and dealing with 403 error while using AJAX

Author image

Fashanu T.

13, Jan 2021

2 Minutes Read...

To send JSON data using ajax, we will be using fetchAPI synchronously and asynchronously.


 JavaScript object notation is a structured data using JavaScript object syntax. The only difference is, in JavaScript object, identifiers do not require the use of single and double quotes. It will also be a valid object if you use both quotes around the identifier.

For JSON, double quotes are required around its identifiers. i.e:

var json = {
"fruit": ['mango'],
"food": 'salad',
"sport": "football"
//valid JSON object

Below is a valid JavaScript object::

var obj = {
fruit: ['mango', 'orange', 'strawberry'],
"food": 'salad',
'sport': "football"
//valid javascript object


Ajax stands for asynchronous JavaScript And XML. It is a web technology associated with JavaScript. The basic functionality of AJAX is to allow communication between a browser and the server asynchronously, meaning it doesn't interfere with other processes that are happening.

Basically it is used for sending data between the user interface and the server without interfering like refreshing the browser or stopping other JavaScript processes for instance.


Like its name, its basically a browser API that lets you send and fetch data from the server. Its syntax are lighter and simple compared to using AJAX, and it works amazingly well with Promise, or async function.

We will be using fetchAPI predominantly here, but you can also use AJAX for this tutorial.

Below is the basic code to using AJAX

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
  };"GET", "", true);

With all that out of the way, lets get to the core of this tutorial πŸ˜ƒ.

403 error while using AJAX or fetch API

You can get a 403 error for various reasons::

Incorrect permission to file

To solve this, head over to your control panel and change permission access. For folder holding your PHP script, change it to 755 and the PHP script itself to 644.

Using special character or reserved keyword

If your JSON string contains html tags and sometimes reserved keywords like select, https://..... or more, a 403 error may be thrown once in awhile. This is because you are not using the correct content type header in sending your JSON data.

Browsers sets a default Content-type of application/x-www-form-urlencoded.

While there is little to nothing when it comes to debugging why this should throw an error, if you are sending JSON string, use application/json Content-type instead, and avoid using FormData API as it was design to use use form Content-type also.

Below is a sample json data sent using fetch API synchronously.

var data = {
"request": "userDetails",
"property": ['Fashanu Tosin', 23, 'Football']
var json = JSON.stringify(data);

method: 'POST',
headers: {'Content-type: application/json '},
body: json

For asynchronously fetch, use the code below::

β€”It is a good idea to use a Promise or asynchronous function for all your FETCH/AJAX, because you can never tell when the task will be completed. Using asynchronous function however, lets other task execute while waiting for a response.

Using asynchronous function with fetch API::

var json = JSON.stringify({"request": 'imgType', "data": 'jpg'});
const request = async (url,data) => { const res = await fetch(url, {
method: 'POST',
headers: {'Content-type: application/json '},
body: data
}); const data = await res.json();
console.log(data); } request('', json);

If you haved worked with AJAX or fetch API in the past without header or setting a Content-type like application/x-www-form-urlencoded, or multipart/form-data, you will be able to get data from the above using the PHP code below::

if( isset($_POST['request']) && $_POST['request'] == 'imgType' ) {
$type = $_POST['data'];
//header('Content-type: application/json');
//further processing here..... header above is for json response see more about setting header in php below......

The above will not work for Content-type header of application/json. So, to work with JSON in PHP script, use the code below::

header('Content-type: application/json');
$json = json_decode(file_get_contents('php://input'));
if ($json->request && $json->request == 'imgType') {
$type = $json->data;
//echo json_encode(array('submitted'=>'yes'));
//do your processing here

Setting Content-type header in PHP

The Content-type header from the code above means you are sending json_encoded string back to the browser. You can see this by opening Firefox browser and try echoing JSON string from a PHP script, the interface you get will be different, compared to when you did not use the header.


JSON response from using JSON header in PHP

Rest API

Representational state transfer is a structural standard for data representation and interaction.

For this tutorial, the interaction uses Rest API because, we are sending and receiving structured data in JSON format, using application/json header, as well as using the end point i.e php-script.php.

For any other application, it might be XML format, plain text or any other structured data format, we then use different headers to handle these application requests.