JSON with PHP

JSON PHP

In the following example, we will request a URL to the web-server and receive a response.

Example

The following is the server-side coding using PHP.

json-receive.php
<?php $myObj->name = "Mike"; $myObj->age = 36; //convert object to string (JSON representation) $myJSON = json_encode($myObj); echo $myJSON; ?>

The following is the client-side coding to send a request and receive a response.

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <h1>JSON.parse()</h1> <p id="point"></p> <button onclick="myFunction()">Receive from Server</button> <script> var x = document.getElementById("point"); var data = {}; function myFunction(){ $.post("/json-receive.php",{ // send no data },function(serverData){ data = JSON.parse(serverData) x.innerHTML = data[0].name; }); } </script> </body> </html>

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author