AJAX Example with JSONPlaceholder

JSONPlaceholder is a free fake API for testing and prototyping. Here's an example of using jQuery AJAX with JSONPlaceholder to fetch and display data.

Setup

  • Use jQuery for AJAX operations.

  • Include the following in your HTML file:

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX CRUD with JSONPlaceholder</title>
</head>
<body>
    <h1>AJAX CRUD Operations</h1>

    <!-- Create -->
    <h2>Create Post</h2>
    <input type="text" id="title" placeholder="Title">
    <textarea id="body" placeholder="Body"></textarea>
    <button id="create">Create Post</button>

    <!-- Read -->
    <h2>Posts</h2>
    <button id="read">Get Posts</button>
    <ul id="posts"></ul>

    <!-- Update -->
    <h2>Update Post</h2>
    <input type="number" id="update-id" placeholder="Post ID">
    <input type="text" id="update-title" placeholder="New Title">
    <textarea id="update-body" placeholder="New Body"></textarea>
    <button id="update">Update Post</button>

    <!-- Delete -->
    <h2>Delete Post</h2>
    <input type="number" id="delete-id" placeholder="Post ID">
    <button id="delete">Delete Post</button>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

AJAX Code

Save the following as script.js:


Explanation

  1. Create: A POST request sends new post data to the API.

  2. Read: A GET request fetches all posts and displays them in a list.

  3. Update: A PATCH request updates an existing post based on its ID.

  4. Delete: A DELETE request removes a post by its ID.


Output

  1. Create Post: Enter a title and body to create a new post.

  2. Fetch Posts: Displays a list of posts in the #posts section.

  3. Update Post: Modify an existing post using its ID.

  4. Delete Post: Remove a post by specifying its ID.

Note

Since JSONPlaceholder is a mock API:

  • Created/Updated/Deleted posts won’t persist beyond the current session.

Last updated