Json Php in JavaScript
Using JSON with PHP and JavaScript
What is JSON PHP in JavaScript?
Often, PHP scripts generate or serve data as JSON.
JavaScript fetches this JSON data (usually via AJAX) and processes it on the client side.
This allows dynamic web apps to communicate with the server easily.
How to Send JSON from PHP
Example PHP code to send JSON:
<?php$data = [ "name" => "Alice", "age" => 28, "skills" => ["PHP", "JavaScript", "HTML"]];// Set content type header to JSONheader('Content-Type: application/json');// Encode PHP array/object as JSON string and outputecho json_encode($data);?>How to Receive JSON in JavaScript (Fetch API)
fetch('path/to/your/phpfile.php') .then(response => response.json()) // Parse JSON response .then(data => { console.log(data.name); // "Alice" console.log(data.skills); // ["PHP", "JavaScript", "HTML"] }) .catch(error => console.error('Error:', error));How to Send JSON Data from JavaScript to PHP
JavaScript (sending JSON data):
const userData = { name: "Bob", age: 30 };fetch('process.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData)}).then(response => response.text()).then(data => console.log(data)).catch(error => console.error('Error:', error));PHP (receiving JSON data):
<?php// Get raw POST data$json = file_get_contents('php://input');// Decode JSON to PHP array/object$data = json_decode($json, true);$name = $data['name'];$age = $data['age'];echo "Received: $name, $age years old";?>Summary
| Task | PHP Side | JavaScript Side |
|---|---|---|
| Send JSON to client | echo json_encode($data); | fetch(...).then(res => res.json()) |
| Receive JSON from client | json_decode(file_get_contents('php://input'), true) | JSON.stringify(data) in fetch body |
Want me to help with a full working example with PHP and JavaScript?