50
1
0
How to Send and Receive JSON with PHP and AJAX

How to Send and Receive JSON with PHP and AJAX

Published on July 3, 2025 by OBSCountdown Editorial

Send and Receive JSON with PHP and AJAX

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 to application/json
  • Use HTTPS to encrypt data transmission
  • Log any unexpected errors or failed requests
Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
50
1
0
Join Our OBS Community

Loading...

Join Now