DeveloperBreeze

JavaScript File Upload using Fetch API and FormData

javascript
// Get the file input element
const fileInput = document.querySelector('#file-input');

// Add an event listener for the 'change' event on the file input
fileInput.addEventListener('change', (event) => {
    // Get the selected file
    const file = event.target.files[0];

    // Create a FormData object and append the file to it
    const formData = new FormData();
    formData.append('file', file);

    // Use the Fetch API to send a POST request with the file data
    fetch('/upload', { method: 'POST', body: formData });
});

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

JavaScript in Modern Web Development

  • JavaScript enables features like dropdown menus, modal windows, sliders, and real-time updates.
  • Examples: Search suggestions, form validations, chat applications.
  • Using AJAX or Fetch API, JavaScript retrieves and updates data without reloading the page.
  • Example: Infinite scrolling on social media feeds.

Dec 10, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

  • We create a new XMLHttpRequest object and open a GET request to the JSONPlaceholder API (a fake online REST API).
  • When the request is successful (status code 200), we parse the JSON data and display it on the page.

The Fetch API is a modern alternative to XMLHttpRequest. It's easier to use, more flexible, and based on Promises, making it simpler to handle asynchronous requests.

Sep 18, 2024
Read More
Code
javascript

React Custom Hook for API Requests

import { useState, useEffect } from 'react';

function useFetch(url, options = {}) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let isMounted = true; // Track if component is mounted

        const fetchData = async () => {
            setLoading(true);
            try {
                const response = await fetch(url, options);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                if (isMounted) {
                    setData(result);
                }
            } catch (error) {
                if (isMounted) {
                    setError(error);
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };

        fetchData();

        return () => {
            isMounted = false; // Cleanup to avoid setting state on unmounted component
        };
    }, [url, options]);

    return { data, loading, error };
}

export default useFetch;

Here’s an example of how to use the useFetch hook in a React component to fetch and display data.

Aug 12, 2024
Read More
Code
javascript json

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>

Aug 04, 2024
Read More
Code
php

File Upload with Type Validation in PHP

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Fetch JSON Data from API in JavaScript

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Asynchronous Fetch in JavaScript using async/await

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Upload and Store File in Laravel

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Asynchronous Data Fetching in JavaScript using 'fetch'

No preview available for this content.

Jan 26, 2024
Read More
Code
bash

Various cURL Examples for API Interactions

No preview available for this content.

Jan 26, 2024
Read More
Code
php

PHP File Upload

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

POST Request with Fetch API and JSON Data

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!