Posts Learn Components Snippets Categories Tags Tools About
/

How to Make Ajax Request in Alpine.js

Learn how to make an Ajax request in Alpine.js the easy way. Get to know how to make POST, GET, PATCH, PUT and DELETE requests in Alpine.js

2 years ago

10 mins read

29137 views

In this post, you'll learn how to make an Ajax request in Alpine.js and we'll cover all the POST, GET, PATCH, PUT and DELETE requests with simple code examples. For the API endpoints, we'll be calling the "Json Placeholder by Typicode" so let's get started.
API ENDPOINT: https://jsonplaceholder.typicode.com/
Do note that the path that's available to be called is listed below:

Available API Routes

All of the HTTP methods are supported by JsonPlaceholder and you can use HTTP or HTTPS for your requests.

GET | /posts
GET | /posts/1
GET | /posts/1/comments
GET | /comments?postId=1
POST | /posts
PUT | /posts/1
PATCH | /posts/1
DELETE | /posts/1

Install Alpine.js or Reference CDN Links


First, you will have to install Alpine.js to your project using NPM or by including the CDN link within your head tag.
npm install alpinejs
CDN Link for Alpine.js Version 3.
<html>
  <head> 
    <script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
  </head>
  <body>
    <!-- your code here -->
  </body>
</html>

Making a GET Request in Alpine.js


Let's start by making a GET request in Alpine.js and you can perform the ajax using "Javascript Fetch API". By default, you can create an object within the "x-data" attribute and then specify the "posts" key which will store the array of posts and then have another function to retrieve the posts.

To perform the Ajax in Alpine.js you can make use "fetch()" function or "Axios" if you have it installed on your project. By using the "x-init", it will allow you to hook into the initialization phase of any element in Alpine hence you can call the method that you have defined on the data.
<div
    x-data="{
        posts: {},

        async retrievePosts() {
            this.posts = await (await fetch('https://jsonplaceholder.typicode.com/posts')).json();

            // log out all the posts to the console
            console.log(this.posts);
        }
    }"
    x-init="retrievePosts">
</div>
This will happen instantly which means that after opening or loading the page, the code will be executed and you can view the "Console DevTools" to see the Ajax response.
Ajax for getting a resource in Alpine.js

Making a POST Request in Alpine.js


To perform a POST request which is creating a new resource, you can write your code like the following. Since by default a POST request has a body, you can structure your code to pass in the data by stringifying the object like below. Upon performing the ajax it will return back the data and in this case, we can see it directly from the console logger.
<div
    x-data="{
        newpost: {},

        async createPost() {
            this.newpost = await (await fetch('https://jsonplaceholder.typicode.com/posts', {
              method: 'POST',
              body: JSON.stringify({
                title: 'foo',
                body: 'bar',
                userId: 1,
              }),
              headers: {
                'Content-type': 'application/json; charset=UTF-8',
              },
            })).json();

            console.log(this.newpost);
        },
    }"
    x-init="retrievePosts"
></div>
The response to the POST request will be as follows:
Ajax for creating a resource in Alpine.js

Making a PUT Request in Alpine.js


To perform an update request you can use the PUT method and then specify the data to update. Do pay attention to the URL itself where the posts ID is set to 1 and the value of the request body.
<div
    x-data="{
        updatedpost: {},
        
        async updatePost() {
            this.updatedpost = await (await fetch('https://jsonplaceholder.typicode.com/posts/1', {
              method: 'PUT',
              body: JSON.stringify({
                id: 1,
                title: 'foo',
                body: 'bar',
                userId: 1,
              }),
              headers: {
                'Content-type': 'application/json; charset=UTF-8',
              },
            })).json();

            console.log(this.updatedpost);
        },
    }"
    x-init="updatePost"
></div>
The response to the PUT request will be as follows:
Ajax for Updating a resource in Alpine.js

Making a PATCH Request in Alpine.js


To update a resource you can use the PATCH method and just like the PUT request, the URL will require to have the ID of the resource which in this case is 1.
<div
    x-data="{
        patchedpost: {},

        async patchPost() {
          this.patchedpost = await (await fetch('https://jsonplaceholder.typicode.com/posts/1', {
            method: 'PATCH',
            body: JSON.stringify({
              title: 'foo',
            }),
            headers: {
              'Content-type': 'application/json; charset=UTF-8',
            },
          })).json();

          console.log(this.patchedpost);
        },
    }"
    x-init="patchPost"
></div>
The response to the PATCH request will be as follows:
Ajax for Patching a resource in Alpine.js

Making a DELETE Request in Alpine.js


To delete a request you can use the "DELETE" method and then the resource will be deleted. Do note that the resource will not be really updated on the server but it will be faked as if.
<div
    x-data="{
        async deletePost() {
            let res = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
              method: 'DELETE',
            });

            console.log(res);
        }
    }"
    x-init="deletePost"
></div>
The response to the DELETE request will be as follows:
Ajax for Deleting a resource in Alpine.js

Full Code Example


The code above can be written in one Alpine.js code and this is how the full code looks like. Do note that you can extract out the "data" object into Alpine global "Alpine.data()" function so that it's reusable and be compiled using your build tools.
<div
    x-data="{
        newpost: {},

        updatedpost: {},

        patchedpost: {},

        posts: [],

        async retrievePosts() {
            this.posts = await (await fetch('https://jsonplaceholder.typicode.com/posts')).json();

            console.log(this.posts);
        },

        async createPost() {
            this.newpost = await (await fetch('https://jsonplaceholder.typicode.com/posts', {
              method: 'POST',
              body: JSON.stringify({
                title: 'foo',
                body: 'bar',
                userId: 1,
              }),
              headers: {
                'Content-type': 'application/json; charset=UTF-8',
              },
            })).json();

            console.log(this.newpost);
        },

        async updatePost() {
            this.updatedpost = await (await fetch('https://jsonplaceholder.typicode.com/posts/1', {
              method: 'PUT',
              body: JSON.stringify({
                id: 1,
                title: 'foo',
                body: 'bar',
                userId: 1,
              }),
              headers: {
                'Content-type': 'application/json; charset=UTF-8',
              },
            })).json();

            console.log(this.updatedpost);
        },

        async patchPost() {
          this.patchedpost = await (await fetch('https://jsonplaceholder.typicode.com/posts/1', {
            method: 'PATCH',
            body: JSON.stringify({
              title: 'foo',
            }),
            headers: {
              'Content-type': 'application/json; charset=UTF-8',
            },
          })).json();

          console.log(this.patchedpost);
        },

        async deletePost() {
            let res = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
              method: 'DELETE',
            });

            console.log(res);
        }
    }"
    x-init="retrievePosts"
></div>
By now you should be able to Make Ajax Request in Alpine.js and if you find this tutorial to be helpful do make sure to share it with your friends. Cheers!

Other Reads

Alternative Tags

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Make Ajax Request in Alpine.js

new

PostSrc Code Snippets

Learn new snippets today, level up your Laravel, Alpine JS, Vue JS, Tailwind CSS skills and more.

Learn New Snippets

Sponsors 👑

+ Add Yours
new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)