const apiUrl = 'https://api.chucknorris.io/jokes/random';
fetch(apiUrl)
.then(response => response.json())
.then(data => console.log('Chuck Norris Joke:', data.value))
.catch(error => console.error('Error:', error));Fetching Chuck Norris Jokes from API in JavaScript
Related Posts
More content you might like
Code
javascript
Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling
initComplete: Adds custom classes to dropdowns and inputs in the DataTables UI for consistent styling.
drawCallback: Applies custom classes to various table elements (e.g., rows, headers, cells) after each table draw to enhance the appearance.
Oct 24, 2024
Read More Tutorial
php
Handling HTTP Requests and Raw Responses in Laravel
Laravel's Http facade simplifies making POST requests to external APIs. Here’s how you can send a basic POST request with some data:
use Illuminate\Support\Facades\Http;
$response = Http::post('https://api.example.com/endpoint', [
'key1' => 'value1',
'key2' => 'value2',
]);
dd($response->body()); // Display the raw response bodyOct 24, 2024
Read More Article
javascript
20 Useful Node.js tips to improve your Node.js development skills:
No preview available for this content.
Oct 24, 2024
Read More Tutorial
javascript
AJAX with JavaScript: A Practical Guide
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>POST Request with Fetch</title>
</head>
<body>
<form id="postDataForm">
<input type="text" id="title" placeholder="Enter title" required>
<input type="text" id="body" placeholder="Enter body" required>
<button type="submit">Submit</button>
</form>
<div id="postDataOutput"></div>
<script>
document.getElementById('postDataForm').addEventListener('submit', function(e) {
e.preventDefault();
const title = document.getElementById('title').value;
const body = document.getElementById('body').value;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: title,
body: body
})
})
.then(response => response.json())
.then(data => {
document.getElementById('postDataOutput').innerHTML = `
<h3>Data Submitted:</h3>
<p>Title: ${data.title}</p>
<p>Body: ${data.body}</p>
`;
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>- The form is submitted without a page reload by preventing the default form submission behavior.
- We send a POST request to the API using
fetch(), including the form data as JSON in the request body. - The server's response is displayed on the page.
Sep 18, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!