← Back to PHP Course | Chapter 15: Web Development | Lesson 7 of 12

PHP AJAX Handling

AJAX एक web page को बिना reload किए server से कुछ माँगने देता है, class चलते समय teacher को एक note पास करने जैसा। PHP request receive करता है और सिर्फ छोटा answer वापस भेजता है।
Syntax
php
header("Content-Type: application/json");
$input = json_decode(file_get_contents("php://input"), true);   // JSON body
echo json_encode($response_data);

PHP में AJAX Handling क्या है?

जब एक browser एक AJAX request भेजता है, यह exactly वैसे ही एक PHP script को hit करता है जैसे एक normal page load करता -- PHP खुद को अंतर नहीं पता।

Distinction पूरी तरह इस बारे में है कि script क्या वापस भेजती है: एक पूरे HTML page के बजाय, एक AJAX endpoint आमतौर पर एक छोटा JSON payload return करता है जिसे page पर JavaScript पढ़ता है और बिना reload के DOM update करने के लिए इस्तेमाल करता है।

उदाहरण: What Is AJAX Handling in PHP?

php
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["message" => "Same script, JSON response instead of full HTML"])` to the output
echo json_encode(["message" => "Same script, JSON response instead of full HTML"]);
?>

Incoming Request पढ़ना

एक form-encoded AJAX POST exactly एक regular form submission जैसे $_POST में आता है।

एक JSON-body AJAX request (fetch() से JSON.stringify(data) भेजने के साथ common) $_POST को populate नहीं करता -- आप raw body को file_get_contents("php://input") से पढ़ते हैं और खुद json_decode() से decode करते हैं।

उदाहरण: Reading the Incoming Request

php
<?php
file_put_contents("php_input_sim.json", '{"name": "Alice"}');
$raw = file_get_contents("php_input_sim.json"); // stands in for php://input
$data = json_decode($raw, true);
echo $data['name'];
?>

एक JSON Response Return करना

result represent करने वाला एक PHP array या object बनाएँ, फिर इसे echo json_encode($data) से भेजें।

किसी भी output से पहले header("Content-Type: application/json") set करना browser (और response पढ़ने वाले JavaScript) को बताता है कि body को plain text मानने के बजाय JSON की तरह parse करे।

उदाहरण: Returning a JSON Response

php
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Declare `$data` as an array: `["result" => "ok"]`
$data = ["result" => "ok"];
// Print `json_encode($data)` to the output
echo json_encode($data);
?>

Success और Failure Signal करना

एक JSON API response में आमतौर पर एक success boolean और या तो एक data key या एक error message शामिल होती है, ताकि calling JavaScript cleanly branch कर सके।

JSON body के साथ http_response_code(400) (या 404, 500, वगैरह) से सही HTTP status code set करना fetch() के response.ok check को भी सही से काम करने देता है।

उदाहरण: Signaling Success and Failure

php
<?php
// Call `http_response_code(400)`
http_response_code(400);
// Print `json_encode(["success" => false, "error" => "Missing field"])` to the output
echo json_encode(["success" => false, "error" => "Missing field"]);
?>

एक पूरे REST API के साथ Contrast

यह single-endpoint request/response pattern server communication का सबसे simple form है -- एक पूरा REST API (site के dedicated REST API topics में covered) resource-oriented URL design, प्रति resource कई HTTP methods, और कई endpoints में consistent conventions add करता है।

एक page की live search या form validation के लिए एक quick AJAX handler को उस structure की ज़रूरत नहीं।

उदाहरण: Contrast with a Full REST API

php
<?php
header("Content-Type: application/json");
echo json_encode(["success" => true, "data" => "search results"]);
// A full REST API would add multiple methods and consistent conventions across many endpoints
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. JSON responses के लिए Content-Type: application/json header set करना भूल जाना।
  2. JSON से पहले HTML या warnings जैसा extra output भेजना, जो client पर parsing तोड़ देता है।
  3. इसे इस्तेमाल करने से पहले request method या input check न करना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.