DeveloperBreeze

Post Request Development Tutorials, Guides & Insights

Unlock 3+ expert-curated post request tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your post request skills on DeveloperBreeze.

AJAX with JavaScript: A Practical Guide

Tutorial September 18, 2024
javascript

<!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.

Simple Server-Side Handling of HTTP Methods

Code January 26, 2024
php

No preview available for this content.

POST Request with Fetch API and JSON Data

Code January 26, 2024
javascript


const apiUrl = 'https://api.example.com/data';
const requestData = {
    name: 'John Doe',
    age: 30,
};

// Send a POST request using fetch
fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json', // Specify JSON content type
    },
    body: JSON.stringify(requestData), // Convert data to JSON string
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Success:', data); // Handle successful response
    })
    .catch(error => {
        console.error('Error:', error); // Handle errors
    });