Post data to a PHP endpoint and dynamically display a response with Alpine.js
<html x-data="utility">
<!-- ... -->
<form class="form" x-data="{response: false}" x-on:submit.prevent="handleForm">
<div class="form-message" style="display: none" x-show="response" x-bind:class="`is-${response?.state?.type}`" x-text="response?.state?.message" x-transition></div>
<fieldset class="form-row">
<input class="form-input" type="text" name="data" placeholder="Your data">
<button class="form-button">Submit</button>
</fieldset>
</form>
<!-- ... -->
</html>
import Alpine from 'alpinejs';
// ...
document.addEventListener('alpine:init', () => {
Alpine.data('utility', () => ({
// ...
async handleContact() {
const data = {
data: this.$el.querySelector('[name="data"]').value
// This is just an example for fetching input data
};
const response = await (
await fetch('Your API endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
).json();
this.$data.response = response;
}
// ...
}));
});
Based on: https://gist.github.com/jairusjoer/7541f79e03293005e2a29272f724d535
<?php
$response = (object) [];
$json = json_decode(file_get_contents('php://input'));
//...
if (!$json) {
$response->state = [
'code' => 400,
'type' => 'error',
'message' => 'Something went wrong. Please try again'
];
http_response_code($response->state['code']);
echo json_encode($response);
exit;
}
//...
$response->state = [
'code' => 200,
'type' => 'success',
'message' => 'Thank you for your submission',
];
http_response_code($response->state['code']);
echo json_encode($response);
exit;