Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jairusjoer
Last active March 27, 2023 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jairusjoer/3ee74ce0635eecc2b70c3610512f2c4f to your computer and use it in GitHub Desktop.
Save jairusjoer/3ee74ce0635eecc2b70c3610512f2c4f to your computer and use it in GitHub Desktop.
Post data to a PHP endpoint and dynamically display a response with Alpine.js

Post and reply

Post data to a PHP endpoint and dynamically display a response with Alpine.js

HTML

<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>

JavaScript

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;
    }
    
    // ...
    
  }));
});

PHP

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment