JSON with Server (PHP/HTML)
JSON is widely used to exchange data between a client (browser) and a server. You can send JSON from HTML/JavaScript to a server-side language like PHP, and receive JSON back for dynamic updates.
- JSON is language-independent. PHP and JavaScript can both encode/decode JSON easily.
- Use
json_encode()
in PHP to convert arrays/objects to JSON strings. - Use
json_decode()
in PHP to parse JSON strings from the client. - On the client, use
JSON.stringify()
to send data, andJSON.parse()
to read JSON. - Always set the header
Content-Type: application/json
when returning JSON from PHP.
Sending JSON from Client to Server
You can send JSON data using AJAX or the Fetch API.
Example using Fetch API
<!DOCTYPE html>
<html>
<body>
<h2>Send JSON to PHP</h2>
<script>
const data = {
name: "John",
age: 30,
city: "New York"
};
// Send JSON to server
fetch("process.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log("Server Response:", result))
.catch(error => console.error("Error:", error));
</script>
</body>
</html>
Receiving JSON in PHP
In PHP, you can read the incoming JSON and decode it into an associative array or object.
process.php
<?php
// Read raw JSON data from the request
$json = file_get_contents("php://input");
// Decode JSON into a PHP array
$data = json_decode($json, true);
// Access values
$name = $data['name'];
$age = $data['age'];
$city = $data['city'];
// Send a JSON response back to client
$response = array(
"status" => "success",
"message" => "Hello $name, your data is received!"
);
header('Content-Type: application/json');
echo json_encode($response);
?>
Sending JSON from PHP to HTML/JavaScript
You can also send JSON directly from PHP to JavaScript when generating HTML.
Example
<?php
$users = array(
array("name" => "John", "age" => 30),
array("name" => "Anna", "age" => 25),
array("name" => "Peter", "age" => 35)
);
$jsonUsers = json_encode($users);
?>
<!DOCTYPE html>
<html>
<body>
<h2>Display JSON Data from PHP</h2>
<script>
// Parse JSON generated by PHP
const users = JSON.parse('<?php echo $jsonUsers; ?>');
users.forEach(user => {
console.log(user.name + " - " + user.age);
});
</script>
</body>
</html>