Send Data to a Web Server

Learning Objectives

Section 24.1: Sending Data: The Basics

POST Request with fetch()

let data = {
    name: "Alice",
    email: "alice@example.com"
};

fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log("Success:", result))
.catch(error => console.error("Error:", error));

Response Handling

fetch("/api/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({name: "Bob"})
})
.then(response => {
    if (response.status === 201) {
        return response.json();
    } else if (response.status === 400) {
        throw new Error("Invalid input");
    } else {
        throw new Error("Server error");
    }
})
.then(data => console.log("Created:", data))
.catch(error => console.error(error));

Section 24.2: Sending Form Data

FormData Object

<form id="myForm">
    <input type="text" name="name">
    <input type="email" name="email">
    <textarea name="message"></textarea>
    <button type="submit">Send</button>
</form>

<script>
document.getElementById("myForm").addEventListener("submit", async function(event) {
    event.preventDefault();
    
    let formData = new FormData(this);
    
    let response = await fetch("/api/contact", {
        method: "POST",
        body: formData  // No need to stringify
    });
    
    let result = await response.json();
    console.log(result);
});
</script>

Sending as JSON Instead

document.getElementById("myForm").addEventListener("submit", async function(event) {
    event.preventDefault();
    
    let formData = new FormData(this);
    let data = Object.fromEntries(formData);
    
    let response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
    });
    
    let result = await response.json();
    console.log(result);
});

Section 24.3: Sending JSON Data

Complete Example

async function submitArticle() {
    let article = {
        title: "JavaScript Tips",
        content: "10 tips for better code",
        author: "Alice",
        tags: ["javascript", "coding"]
    };

    try {
        let response = await fetch("/api/articles", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + token
            },
            body: JSON.stringify(article)
        });

        if (!response.ok) {
            throw new Error(`Error: ${response.status}`);
        }

        let result = await response.json();
        console.log("Article created:", result.id);
        
    } catch (error) {
        console.error("Failed to create article:", error);
    }
}

submitArticle();

PUT/PATCH for Updates

async function updateUser(userId, updates) {
    let response = await fetch(`/api/users/${userId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updates)
    });
    
    return await response.json();
}

// Usage
updateUser(1, { name: "Bob", email: "bob@example.com" });

Coding Challenges

Challenge 24.1: New Article

Task: Create a form to submit articles to a server

Challenge 24.2: Visited Countries

Task: Submit a list of visited countries and save to database

Key Takeaways

✅ Use POST method to send data
✅ JSON.stringify() converts data to JSON string
✅ FormData for file and form submissions
✅ Always include Content-Type header
✅ Handle errors gracefully
✅ Provide user feedback on success/failure

Quiz Questions


Next Module: Module 25 - Discover Node.js