Fetching Wikipedia Articles with jQuery AJAX: A Comprehensive Guide
Wikipedia is one of the largest repositories of publicly available knowledge. Using its MediaWiki API, developers can fetch and display Wikipedia articles dynamically on a web page. This guide will walk you through how to use jQuery and AJAX to fetch and display Wikipedia articles dynamically.
π What Youβll Learn
β Understanding the Wikipedia API
β Setting up jQuery in your project
β Using AJAX to fetch Wikipedia data
β Handling API responses
β Displaying Wikipedia search results dynamically
β Enhancing the user experience
β Implementing error handling and security best practices
1οΈβ£ Understanding the Wikipedia API
Wikipedia provides a public API that allows developers to fetch articles, search Wikipedia, and get metadata about articles.
π Wikipedia API Endpoint
The Wikipedia API endpoint for searching articles is:
https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch={SEARCH_TERM}
πΉ action=query
β Indicates a search query request
πΉ format=json
β Returns data in JSON format
πΉ list=search
β Performs a search
πΉ srsearch={SEARCH_TERM}
β The search term entered by the user
π Example search query for βNASAβ:
https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=NASA
Wikipedia API Restrictions:
- Wikipedia does not support CORS (Cross-Origin Resource Sharing) by default, so we need to use JSONP (JSON with Padding) to bypass CORS issues.
2οΈβ£ Setting Up Your Project
Required Tools
β
A text editor (VS Code, Sublime, Notepad++, etc.)
β
A web browser (Chrome, Firefox, Edge, etc.)
β
Basic knowledge of HTML, CSS, and JavaScript
Adding jQuery to Your Project
You can add jQuery in two ways:
β Option 1: Using a CDN (Recommended)
Add this line inside your <head>
tag:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
β Option 2: Downloading jQuery Locally
- Download jQuery from https://jquery.com/download/.
- Save it in your project folder.
- Link it in your HTML file:
<script src="jquery-3.6.0.min.js"></script>
3οΈβ£ Writing jQuery Code to Fetch Wikipedia Articles
Step 1: Basic AJAX Request to Wikipedia API
$(document).ready(function() {
var searchQuery = "NASA"; // Change this to any topic
$.ajax({
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
format: "json",
list: "search",
srsearch: searchQuery
},
dataType: "jsonp", // Wikipedia does not support CORS, so we use JSONP
success: function(response) {
console.log(response);
},
error: function(error) {
console.log("Error fetching Wikipedia articles:", error);
}
});
});
β Explanation:
url
β The Wikipedia API endpoint.data
β Parameters includingaction
,format
,list
, andsrsearch
.dataType: "jsonp"
β Used to handle CORS issues with Wikipedia API.success(response)
β Displays the API response.error(error)
β Handles errors if the request fails.
4οΈβ£ Handling and Displaying Wikipedia API Response
π Example API Response (Shortened)
{
"query": {
"search": [
{
"title": "NASA",
"snippet": "NASA is the United States government agency responsible for space exploration.",
"pageid": 123456
},
{
"title": "NASA missions",
"snippet": "NASA has conducted numerous space missions since its founding in 1958.",
"pageid": 789012
}
]
}
}
π Displaying Wikipedia Search Results in HTML
Modify the script to display search results dynamically:
$(document).ready(function() {
$("#search-btn").click(function() {
var searchQuery = $("#search-input").val(); // Get user input
$.ajax({
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
format: "json",
list: "search",
srsearch: searchQuery
},
dataType: "jsonp",
success: function(response) {
$("#results").empty(); // Clear previous results
$.each(response.query.search, function(index, article) {
var articleTitle = article.title;
var articleSnippet = article.snippet;
var articleURL = "https://en.wikipedia.org/wiki/" + articleTitle.replace(/ /g, "_");
var resultHTML = `
<div class="article">
<h3><a href="${articleURL}" target="_blank">${articleTitle}</a></h3>
<p>${articleSnippet}...</p>
</div>
`;
$("#results").append(resultHTML);
});
},
error: function() {
$("#results").html("<p>Failed to fetch Wikipedia articles. Please try again.</p>");
}
});
});
});
π Updating the HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wikipedia Search</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Wikipedia Article Search</h1>
<input type="text" id="search-input" placeholder="Enter search term">
<button id="search-btn">Search</button>
<div id="results"></div>
</body>
</html>
β How It Works:
- User enters a search term and clicks the “Search” button.
- AJAX request fetches Wikipedia search results.
- Results are displayed dynamically with title, snippet, and a clickable link.
5οΈβ£ Enhancing User Experience
To improve the user experience, let’s add:
β
Loading Indicator
β
Error Handling
Modify the JavaScript:
$("#search-btn").click(function() {
var searchQuery = $("#search-input").val();
$("#results").html("<p>Loading...</p>"); // Show loading message
$.ajax({
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
format: "json",
list: "search",
srsearch: searchQuery
},
dataType: "jsonp",
success: function(response) {
$("#results").empty();
if (response.query.search.length === 0) {
$("#results").html("<p>No articles found.</p>");
return;
}
$.each(response.query.search, function(index, article) {
var articleTitle = article.title;
var articleSnippet = article.snippet;
var articleURL = "https://en.wikipedia.org/wiki/" + articleTitle.replace(/ /g, "_");
var resultHTML = `
<div class="article">
<h3><a href="${articleURL}" target="_blank">${articleTitle}</a></h3>
<p>${articleSnippet}...</p>
</div>
`;
$("#results").append(resultHTML);
});
},
error: function() {
$("#results").html("<p>Error fetching data. Try again later.</p>");
}
});
});
Using jQuery and AJAX, we successfully built a Wikipedia search tool that fetches articles dynamically.
Would you like to add animations or autocomplete suggestions? Let me know!