JavaScript Me Fetch API & AJAX Kya Hote Hain?
Bina page reload kiye server se data fetch karna sikhein.
1. AJAX Kya Hota Hai? (The Old Way)
AJAX ka matlab hai Asynchronous JavaScript and XML. Yeh ek web development technique hai jo browser aur server ke beech bina page reload kiye data exchange karne me madad karti hai. Isse web applications fast, responsive aur interactive banti hain.
Traditionally, AJAX XMLHttpRequest
(XHR) object ka use karke background me server requests bhejta hai. Jab aap Google par kuch likhna start karte hain aur suggestions automatic aate hain, woh AJAX ka hi ek example hai.
XMLHttpRequest Example:
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
xhr.onload = function () {
if (xhr.status == 200) {
console.log("Data fetched:", xhr.responseText);
}
};
xhr.send();
Problems: XHR ka syntax complex hota tha, readability kam thi, aur yeh callbacks par based tha, jisse "Callback Hell" ki problem ho sakti thi.
2. Fetch API: The Modern Solution
Fetch API ek modern JavaScript interface hai jo XMLHttpRequest
ka replacement hai. Yeh web servers se data request karne ka ek simple, powerful, aur flexible tarika hai. Fetch API Promises par based hai, jisse asynchronous code likhna bohot aasan ho jaata hai.
Basic Fetch Example (GET Request)
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
console.log("Data:", data);
})
.catch(error => {
console.log("Error:", error);
});
POST Request with Fetch
POST request ka use server par naya data create karne ke liye hota hai. Isme data request ki body
me bheja jaata hai.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 })
})
.then(res => res.json())
.then(data => console.log("Response:", data));
3. Fetch API with Async/Await
`async/await` syntax Fetch API ke saath use karne par code ko aur bhi clean aur readable bana deta hai.
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
getData();
AJAX (XHR) vs. Fetch API
Feature | AJAX (XMLHttpRequest) | Fetch API |
---|---|---|
Syntax | Complex, event-based | Simple, Promise-based |
Error Handling | Manual (status checks) | Built-in `.catch()` |
JSON Parsing | Manual `JSON.parse()` | Easy with `.json()` method |
Browser Support | Wide (very old browsers) | Modern browsers |
Key Takeaways
- AJAX ek technique hai, aur XMLHttpRequest (XHR) use implement karne ka purana tarika hai.
- Fetch API modern, powerful, aur Promise-based alternative hai XHR ka.
- Fetch API se GET, POST, PUT, DELETE jaise sabhi HTTP requests bheje jaa sakte hain.
- `async/await` ke saath Fetch API ka use karna code ko sabse readable banata hai.
Ek public API (jaise JSONPlaceholder) se data fetch karein aur use `console.log()` me print karein. Aap `async/await` ka use karne ki koshish karein.
Practice in JS EditorApni knowledge test karne ke liye is quick quiz ko dein.
Start Quiz