Get JSON data from PHP file

Retrieve JSON data from a PHP file with ease using this step-by-step guide. Learn how to use built-in PHP functions to convert data into JSON format and return it to the client-side JavaScript. Improve your web development skills and create more dynamic and interactive web applications by incorporating JSON data from PHP files.

Having a PHP file spit out JSON as its main function can be really useful when you want to execute an AJAX call so you can refresh some content on the page, without reloading the page. Since the development of AJAX calls, a long wished dream was fulfilled for almost every web artisan. Being able to fully change parts of the content on a page without reloading everything was huge and certainly made each project more instant, direct and user friendly for users then and users now. So how can we put the work and create an approach that can simulate such functionalities?

Well, the first thing is to generate or collect the data of your choice so you can decide how you want to serve it from the script. Once you have the data, it is suggested to use an associative array for a more accurate serving and even easier way to parse them later on from the frontend (JS side).

So, how do you create a PHP script to spit out JSON whenever you open it up directly from the browser? It is simple. You generate some arbitrary data and then you use json_encode() to convert it into JSON notation. If you don’t know how to do that, check this article first. A simple example is demonstrated below.

/* data.php */
$data = array(
'name' => 'PHP',
'callsign' => 'Artisan',
'est' => '2022',
'tutorial' => 'return json from php'
);
echo json_encode($data);

Now that you have the data served in JSON notation, the next order of business is to consume. One great way to complete such task is to setup an xmlhttp request to that specific file (data.php), parse the data into JSON and display its contents accordingly.

/* index.php */
<div id="content"></div>
<script>
    var req = new XMLHttpRequest();
    req.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            var res = JSON.parse(req.responseText);            
            document.getElementById('content').innerHTML = 'The ' + res.name + ' ' + res.callsign;
        }
     };
    req.open('get', 'data.php');
    req.send();
</script>

The first step is to create an instance of the XMLHttpRequest object. Then we handle the onreadystatechange event and bind an anonymous function to it using the equal operator and the keyword function. If you don’t remember what an anonymous function is, read the related article here. You can also do that using an arrow function:

req.onreadystatechange = ( ) => { . . . . }

The most important step in this process is the conditional checks to the request status and ready state callback property. If the readyState equals to 4 and the request status is 200 (no errors) then the responseText object is available for parsing. Since we’ve used the json_encode function implementing the php script, we’re going to parse it as JSON, hence the JSON.parse( . . .) portion. The next step is up to you but in this case we’re just building a string and display it to the div.

However, there’s a key point to be mindful of and that’s the actual request. What we’ve done with the anonymous function definition and data so far is to handle the response case assuming a request has been executed. The actual request takes place below:

req.open('get', 'data.php');
req.send();

The first line sets up the HTTP method that we want to execute the request with. The HTTP method of choice’s called GET. What that means is that we use the URL to get the data. You can confirm that a get method works as expected if you hit the URL of the data.php directly. If you see text displayed as a JSON object it means that the get method works and doesn’t break. The second line simply sends the request to the designated file.

Async/Await and Promises with JS

There’s another way to get the data and leverage something more straight forward than the plain XMLHttpRequest object and that is an asynchronous promise.

<div id="content"></div>
<script>
async function getData(url) {
const obj = document.getElementById('content');
await fetch(url)
.then(resp => { return resp.json() })
.then(dt => {
obj.innerHTML = 'The ' + dt.name + ' ' + dt.callsign;
})
}
getData('data.php');
</script>

A promise is essentially a transaction and as you may know, the main goal of a transaction is to reach some defined state. Since we’re doing an async call to that data.php file we absolutely need to label our function with the async keyword. You cannot use await without casting the outer function with the async keyword. Once we’ve setup the name and the parameter we carefully select our object so we can display the parsed data later on. The the fun part begins!

await fetch(url)
.then(resp => { return resp.json() })
.then(dt => {
obj.innerHTML = 'The ' + dt.name + ' ' + dt.callsign;
})

Instead of using the XMLHttpRequest object here, we use fetch(). Fetch is a built in function and what it does is to send requests to a specific endpoint of your choice. Depending the method that we designate, its syntax may vary. You can read more about fetch() here.

Once the request has been sent successfully we’ll receive a response of type promise. To the first promise response, we encode the data we get into JSON. Afterwards a new promise is been triggered and now it’s time to use the fetched data in a meaningful context. You can always use whatever technique you deem fit and sits best with you but I strongly recommend the last one. It’s a great building block towards JS frameworks and what not.