DeveloperBreeze

JavaScript Code Snippet: Fetch and Display Data from an API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch API Example</title>
</head>
<body>
    <h1>User Information</h1>
    <ul id="user-list"></ul>

    <script>
        async function fetchUserData() {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/users');
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const users = await response.json();
                displayUsers(users);
            } catch (error) {
                console.error('Fetch error:', error);
            }
        }

        function displayUsers(users) {
            const userList = document.getElementById('user-list');
            users.forEach(user => {
                const listItem = document.createElement('li');
                listItem.textContent = `${user.name} - ${user.email}`;
                userList.appendChild(listItem);
            });
        }

        fetchUserData();
    </script>
</body>
</html>

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

JavaScript in Modern Web Development

  • Tools like React Native enable building native apps using JavaScript.
  • Example: Facebook's mobile app.
  • Frameworks like Electron allow creating cross-platform desktop apps.
  • Example: Visual Studio Code.

Dec 10, 2024
Read More
Tutorial
javascript

History and Evolution

No preview available for this content.

Dec 10, 2024
Read More
Tutorial
php

Exporting Table Row Data to CSV in JavaScript

Here is the JavaScript code to achieve this:

// Select all export buttons
const exportButtons = document.querySelectorAll('.export-btn');

// Add event listener to each export button
exportButtons.forEach(button => {
    button.addEventListener('click', () => {
        // Get the parent row of the clicked button
        const row = button.closest('tr');

        // Get all cells in the row except the last one (which contains the export button)
        const cells = Array.from(row.querySelectorAll('td'));
        cells.pop(); // Remove the last cell (the button cell)

        // Extract the text content of each cell and wrap them in double quotes (CSV format)
        const cellValues = cells.map(cell => `"${cell.textContent}"`);

        // Create the CSV data by joining cell values with commas
        const csvData = cellValues.join(',');

        // Create a temporary anchor element for the download
        const anchor = document.createElement('a');
        anchor.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvData);
        anchor.download = 'row_data.csv';

        // Programmatically click the anchor to trigger the download
        anchor.click();
    });
});

Oct 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

الفرق بين let و const و var في JavaScript

  • نطاق الكتلة: المتغيرات التي يتم تعريفها باستخدام let تكون محصورة داخل الكتلة التي تم تعريفها فيها (مثل داخل if أو for).
  • رفع المتغير: يتم رفع المتغيرات المُعلنة باستخدام let، لكن لا يمكن الوصول إليها قبل الإعلان عنها بشكل صريح؛ أي أن استخدامها قبل الإعلان يؤدي إلى خطأ.
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 7;

Sep 26, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

عند استلام بيانات JSON من خادم، يمكنك تحويل هذه البيانات إلى كائنات JavaScript باستخدام JSON.parse(). هذه الدالة تأخذ سلسلة JSON وتحولها إلى كائن JavaScript يمكنك التعامل معه.

const jsonString = '{"name":"أحمد","age":30,"isMarried":false,"children":["سارة","علي"]}';

const person = JSON.parse(jsonString);
console.log(person.name);  // أحمد
console.log(person.age);   // 30

Sep 26, 2024
Read More
Tutorial
javascript

البرمجة الكائنية (OOP) في JavaScript: المفاهيم الأساسية والتطبيقات

console.log(myCar.brand);  // Toyota
console.log(myCar.model);  // Corolla
console.log(myCar.year);   // 2020

التغليف هو عملية إخفاء تفاصيل التنفيذ الداخلية للكائن عن العالم الخارجي. يمكن تحقيق ذلك في JavaScript باستخدام الفئات والفئات الخاصة (private classes).

Sep 26, 2024
Read More
Tutorial
javascript

Easy JavaScript Tutorial for Beginners

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript Example</title>
</head>
<body>
    <button id="myButton">Click Me</button>

    <script>
        document.getElementById('myButton').addEventListener('click', function() {
            alert('Hello from JavaScript!');
        });
    </script>
</body>
</html>

Place JavaScript in an external file and link it in the HTML file:

Sep 18, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

When working with AJAX, it’s important to handle errors properly. Both XMLHttpRequest and Fetch API provide mechanisms to catch and handle errors.

fetch('https://jsonplaceholder.typicode.com/invalid-url')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });

Sep 18, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

This tutorial assumes a basic understanding of JavaScript, including functions, objects, and inheritance. If you're new to these concepts, it may be helpful to review them before proceeding.

JavaScript classes are essentially syntactic sugar over JavaScript’s existing prototype-based inheritance. They provide a cleaner and more intuitive way to create objects and handle inheritance.

Sep 02, 2024
Read More
Tutorial
javascript

MDN's In-Depth JavaScript Guide: A Comprehensive Resource for Developers

The reference section is an invaluable resource for both beginners and experienced developers, serving as a comprehensive dictionary for JavaScript.

MDN’s JavaScript Guide also includes best practices for writing clean, efficient, and maintainable code. It highlights common pitfalls that developers should avoid, such as:

Aug 30, 2024
Read More
Tutorial
javascript

Understanding ES6: A Modern JavaScript Tutorial

Async/await is a syntactical sugar over promises, making asynchronous code look and behave more like synchronous code.

Async/Await Example:

Aug 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

const element = document.getElementById('myElement');
element.remove(); // Removes the element from the DOM

One of the most powerful features of the DOM is the ability to respond to user interactions through events. JavaScript allows you to attach event listeners to elements to handle these interactions.

Aug 30, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

   curl -X DELETE http://localhost:8000/books/b1

In this tutorial, we built a simple RESTful API using Go and Gorilla Mux. We covered:

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

No preview available for this content.

Aug 12, 2024
Read More
Code
javascript json

How to Deep Clone a JavaScript Object

No preview available for this content.

Aug 12, 2024
Read More
Code
json python

Python Code Snippet: Simple RESTful API with FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Book(BaseModel):
    title: str
    author: str

# Sample data
books_db = [
    Book(title="The Catcher in the Rye", author="J.D. Salinger"),
    Book(title="To Kill a Mockingbird", author="Harper Lee"),
    Book(title="1984", author="George Orwell")
]

@app.get("/books/", response_model=List[Book])
async def get_books():
    return books_db

@app.post("/books/", response_model=Book)
async def add_book(book: Book):
    books_db.append(book)
    return book

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Aug 04, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

Create a file named app.py and add:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Flask REST API!"

if __name__ == '__main__':
    app.run(debug=True)

Aug 03, 2024
Read More
Code
javascript

Password Toggle

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

JavaScript Add Animation to HTML Element

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!