JavaScript fetch API In Hindi

📔 : AJAX 🔗

JavaScript में XMLHttpRequest Object का use करके GET / POST Request send करने की बजाय JavaScript ने एक और facility provide की है fetch API Interface .


fetch API Interface , XMLHttpRequest की तरह ही server से interact करती है। fetch API XMLHttpRequest की तुलना में request को और easy to understand और clear बनाती है। इसके अलावा response को अच्छी तरह से handle भी कर सकते हैं। fetch API Interface के through हम दोनों type ( GET / POST ) की Request send कर सकते हैं।


fetch API request handle करने के लिए promises use करती है।

Understanding JavaScript Promise

Promise JavaScript में एक Object होता है , जो कि specially asynchronous operations handle करने के लिए use किये जाते हैं। Promises use करने से operations & errors को और अच्छी तरह से handle कर सकते हैं। इसे दो part से समझ सकते हैं -

  1. Producing Code - वह code जो run होने वाला है , और process में Time  ले सकता है।
  2. Consuming Code - वह code जो Producing Code के पूरी तरह से run होने का wait करता है , Producing Code run हो जाने के बाद ही Consuming Code Run होता है।

JavaScript Promise, Producing Code को Consuming Code के साथ लिंक करता है ताकि Producing Code के Run हो जाने के बाद ही Consuming Code Run हो और कोई error आने पर उसे handle किया जा सके।

JavaScript fetch API Send GET Request

File : fecth_request.php

Copy Fullscreen Close Fullscreen
<?php
   /** print json data
   * in PHP we use json_encode to convert Array to JSON Form
   * And use json_decode to convert JSON Format to PHP Array
   */
   echo json_encode([
 	'status' => true,
 	'msg' => 'Request Recieved',
 	'data' => [
 		'key' => 'value'
 	]
   ]);
?>

JS / HTML to send request

File : fetchapi.html

CopyFullscreenClose Fullscreen
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Fetch API</title>
</head>
<body>
<p><button id="button">Send Request</button></p>
<script type="text/javascript">
let button = document.getElementById('button');
button.addEventListener('click', function(event)
{
fetch('handle_request.php',{
type : 'GET'
}).
then((result)=> result.json()). /*convert response into JSON Format*/
then((result) => {
console.log('Success', result.msg); /* See result in console*/
}).
catch(error => {
console.log('Error', error); /* It will run if something went wrong*/
});
});
</script>
</body>
</html>

Explain : Example में button पर click eventListener add किया गया है जिससे button पर click होने पर GET Request को send किया जा सके। Fetch API के through GET Request send करने के लिए सिर्फ URL & type define करना होता है। fetch function just बाद ही then() का use किया है , जो simply define करता है कि request fetch होने के बाद ही यह code of block रन होगा।


fetch API हमें json() function भी provide कराती है , जो request data (key value data) को JSON Object में convert करता है।

Important
GET Request के साथ Data send करने के लिए simply URL के साथ query string में data append करते हैं।

https://www.example.com?product=product&id=5&other=other

JavaScript fetch API Send POST Request

Fetch API के through POST Request send करने के लिए हमें type POST देना होता है , headers define करना पड़ता है और जो डाटा send करना है उसे body में define करना पड़ता है।
See Example :

JS / HTML to send request

File : fetchapi.html

CopyFullscreenClose Fullscreen
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Fetch API POST Request</title>
</head>
<body>
<p>Open console to see output.</p>
<p><button id="button">Send Post Request</button></p>
<script type="text/javascript">
let button = document.getElementById('button');
button.addEventListener('click', function(event)
{
let send_data = {
name : 'Rahul Kumar',
age : 25,
website : 'learnhindituts.com',
about : 'Web Developer'
};
fetch('handle_request.php',{
method : 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(send_data) /*it converts json Object to string*/
}).
then((result)=> result.json()). /*convert response into JSON Format*/
then((result) => {
console.log('Success', result.msg); /* See result in console*/
}).
catch(error => {
console.log('Error', error); /* It will run if something went wrong*/
});
});
</script>
</body>
</html>

PHP File To Handle POST Request

File : handle_request.php

Copy Fullscreen Close Fullscreen
<?php 
        $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
	if ($contentType == "application/json;charset=utf-8") 
	{
		/** Receive the RAW post data. */
		$content = trim(file_get_contents("php://input"));
		$post_data = json_decode($content, true);
		/* If json_decode failed, the JSON is invalid. */
		if(is_array($post_data)) 
		{
			echo json_encode([
			 	'status' => true,
			 	'msg' => 'POST Request Recieved',
			 	'your_data' => $post_data
			]);
		} 
		else 
		{
		   echo json_encode([
			 	'status' => false,
			 	'msg' => 'Something went wrong'
			 ]);
		}
	}
	else
	{
		echo $contentType;
	}
?>

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers