Create an interactive front-end using AJAX and PHP to send and receive JSON data for dynamic web applications.
๐ Why Use AJAX with JSON in PHP?
AJAX allows you to send and receive data asynchronously without reloading the page. Combining it with JSON , the most popular data exchange format , and PHP on the server creates responsive and modern web applications.
๐ Step 1: HTML Form
<form id="userForm" onsubmit="submitForm(event)"> <input type="text" name="username" placeholder="Enter username" required> <input type="email" name="email" placeholder="Enter email" required> <button type="submit">Submit</button> </form> <div id="response"></div>
๐ Step 2: JavaScript AJAX Request
<script> function submitForm(event) { event.preventDefault(); const form = document.getElementById("userForm"); const formData = new FormData(form); const data = Object.fromEntries(formData); fetch("handler.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => { document.getElementById("response").innerText = result.message; }) .catch(error => { console.error("Error:", error); }); } </script>
๐ ๏ธ Step 3: PHP Handler
<?php // handler.php header("Content-Type: application/json"); $data = json_decode(file_get_contents("php://input"), true); if (isset($data['username'], $data['email'])) { $username = htmlspecialchars($data['username']); $email = htmlspecialchars($data['email']); // Simulate storing in database or sending email $response = [ "status" => "success", "message" => "Received data for $username at $email." ]; } else { $response = [ "status" => "error", "message" => "Invalid input received." ]; } echo json_encode($response); ?>
The PHP script reads JSON input, processes it, and returns a JSON response.
๐ Security Tips
- Always sanitize and validate user inputs
- Set
Content-Type
toapplication/json
- Use HTTPS to encrypt data transmission
- Log any unexpected errors or failed requests