JavaScript

Using Native Fetch With Alpine.js and PHP9 min read

The fetch API can be used in Alpine.js to interact with REST APIs and perform common operations such as sending and receiving data. By using the fetch API, you can make HTTP requests to retrieve or send data from or to a REST API. This data can then be used to populate a form or perform other actions in your Alpine.js application. The fetch API is widely supported across modern browsers and provides a simple and efficient way to interact with REST APIs.

In this application, I will perform the task of querying and saving data using the table below that I created with PHP.

sample db




Here you can see the final outcome. We utilize the built-in JavaScript fetch in an Alpine.js component to gather data and fill in the form. You can modify the form data, and by clicking the “save” button, we are sending a POST request to an API endpoint with the saved information. The endpoint is not actually available, so it returns an error, but the purpose of this example is to demonstrate how to use fetch to make a POST request.

Making a GET Request in Alpine.js

In Alpine.js, you can use the built-in fetch API or an external library like Axios to perform AJAX requests and retrieve data from an API. The x-data attribute allows you to define the data object in your component, where you can store the result of the API request. The x-init attribute can be used to run code during the initialization phase of the component, which can be used to call the method that retrieves the data. By using fetch or Axios, you can make a GET request to the API endpoint and retrieve the data, which can then be stored in the users key within the data object.

The above code is an Alpine.js component that retrieves data from a PHP endpoint and stores it in a data property named “users”. The component uses the “x-data” attribute to define the data properties of the component, in this case the “users” array. The “x-init” attribute is used to run some JavaScript code when the component is first initialized, which is where the data retrieval takes place.

The first line of the code includes the Alpine.js library from a content delivery network (CDN).

The code defines a custom component with the x-data directive, which creates a reactive data property users and sets it to an empty array.

Finally, the getUsers function is invoked to execute the request when the component is first loaded.

With Alpine.js, the users property is automatically updated whenever it changes, and any parts of the HTML that are bound to it will be automatically updated as well. This makes it easy to create dynamic, reactive UIs with a minimal amount of code.

The template block inside the component uses the x-for directive to loop through the array of users and display their data in a table. The x-text directive is used to bind the text content of each table cell to the corresponding property of the user object. The table is only displayed if the users array is not empty, which is checked by the x-if directive.

db.php: MySQL Database Connection(Local)

user.php

This PHP code performs a GET request and retrieves data from a user database. If the GET request includes a query parameter of “q” equal to 1, the code will execute the following steps:

  1. Prepare a SELECT statement to retrieve all records from the “user” table using the prepare method of the PDO object $dbh.
  2. Execute the prepared statement using the execute method.
  3. Fetch the results of the query as an associative array using the fetchAll method and the constant PDO::FETCH_ASSOC.
  4. Encode the results as a JSON string using the json_encode function.
  5. Echo the JSON string to the output.

The purpose of this code is to retrieve data from the “user” table and return it as a JSON response, which can then be processed by a client-side application such as a JavaScript front-end. The json_encode function is used to convert the associative array into a JSON string, which is a lightweight data interchange format that is easy to read and write for both humans and machines. The echoed JSON string is then returned as the response to the GET request.

In summary, this code demonstrates how to retrieve data from a database using a GET request and return it as a JSON response in PHP.

Making a POST Request in Alpine.js

To perform a POST request, which creates a new resource, by including the data in the body of the request. You can pass in the data by stringifying the object. After the fetch call, the returned data can be seen directly in the console logger.

Before write a POST request, change x-data attribute in the above like following.

The code is an HTML form that is using Alpine.js to perform a POST request when the form is submitted. When the form is submitted, it triggers the “createUser” function which is declared in the x-on attribute.

In the “createUser” function, it first makes a fetch request to the “user.php” URL with the method set to POST, headers set to “Content-Type: application/json”, and the body is the “newUser” object that is stringified.

Upon a successful fetch request, it then retrieves the response text and logs it to the console. Finally, it calls another function “getUsers()” which is assumed to retrieve all users data.

user.php

In this code, we are handling the creation of a new user resource in the system. The code first checks the content type of the request being made. If it is determined to be “application/json,” the code proceeds to retrieve the new user data from the request body. This is done by reading the contents of “php://input,” which is a read-only stream that allows you to read raw data from the request body.

Once the new user data is retrieved, it is decoded from JSON into a PHP array using the json_decode function. This allows us to easily access the individual properties of the new user, such as name, last name, and age.

Next, the code prepares an SQL INSERT statement to insert the new user data into the “user” database table. The execute method is then called on the statement, passing in an array of values for the new user properties.

Finally, the code checks the status of the insertion operation. If it was successful, a JSON response with a “success” property of “OK” is returned. If there was an error, a JSON response with a “success” property of “ERR” is returned.

The server-side PHP code above is used to save the user data that was sent from the front-end. It starts by checking if the content type of the request is application/json. This ensures that the data that is being sent is in a JSON format, which is the format that is expected.

The code then uses file_get_contents("php://input") to retrieve the JSON data that was sent in the request body. The data is then decoded using json_decode($newUserJSON, true) to convert it into an array that can be easily used.

Next, a prepared statement is created using $dbh->prepare("INSERT INTO user values(NULL,?,?,?);"). The VALUES placeholder in the statement is then populated with the values from the $newUserArr array.

Finally, the statement is executed using $stmt->execute([$newUserArr['name'],$newUserArr['lastname'],$newUserArr['age']]), which inserts the new user into the user table. The status of the operation is then checked, and a JSON object indicating the success or failure of the operation is returned to the front-end.

With the knowledge you’ve gained from this tutorial, you’re now equipped to make Ajax Requests with Alpine.js. I hope this guide was helpful for you. If you found it useful, make sure to share it with your friends and colleagues. Here’s to more coding adventures! Cheers!

Leave a Comment