Blog>
Snippets

Submitting Data with AJAX Post Request

Showcases how to submit form data using fetch API for an AJAX Post request, handling submission events in a React component.
import React, { useState } from 'react';

function AddPost() {
    const [title, setTitle] = useState('');

    async function handleSubmit(event) {
        event.preventDefault();
        // Constructing the form data
        const postData = { title };
        try {
            // Making the POST request using the Fetch API
            const response = await fetch('https://example.com/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(postData),
            });
            const responseData = await response.json();
            console.log('Server Response:', responseData);
            // Handle the response data as needed...
        } catch (error) {
            console.error('Error submitting post:', error);
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <input
                type='text'
                name='title'
                value={title}
                onChange={(e) => setTitle(e.target.value)}
            />
            <button type='submit'>Submit</button>
        </form>
    );
}

export default AddPost;
This code example shows how to create a simple form in a React component to submit a post title. It uses the useState hook to manage form state and handle changes to the form. The handleSubmit function is called when the form is submitted. It uses the Fetch API to make a POST request, sending JSON data to a server endpoint and handles the asynchronous operation with async/await syntax. The server response is then logged, demonstrating how to process the result of the AJAX call.