Created
September 1, 2020 12:50
-
-
Save git-bhanu/7091ddb279e5e57796ac2fc7e6704664 to your computer and use it in GitHub Desktop.
Example : Using Alpine Js to set WordPress AJAX method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <form method="POST" x-data="checkoutGuestForm()" @submit.prevent="submitData"> | |
| <p> | |
| <span> | |
| <input type="email" | |
| placeholder="Enter Email" | |
| name="email" | |
| x-model="formData.email" | |
| required | |
| > | |
| </span> | |
| </p> | |
| <p x-show ="existingCustomer"> | |
| <span class="passowrd"> | |
| <input type="password" | |
| placeholder="Password" | |
| name="password-checkout" | |
| x-model="formData.password" | |
| > | |
| </span> | |
| </p> | |
| <p> | |
| <span><button :disabled="loading" x-text="buttonLabel"></button></span> | |
| </p> | |
| <p> | |
| <span class="error" x-text="message"></span> | |
| </p> | |
| </form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Need to use window otherwise, Alpine JS will not recognize this. Out of scope | |
| window.checkoutGuestForm = function () { | |
| return { | |
| formData: { | |
| email: '', | |
| password: '', | |
| }, | |
| message: '', | |
| submitData() { | |
| fetch(localizedObject.ajaxurl, { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Cache-Control': 'no-cache' }, | |
| body: 'action=checkout_guest_form&nonce='+crush_ajax.nonce+'&email='+this.formData.email+'&password='+this.formData.password, | |
| credentials: 'same-origin', | |
| }) | |
| .then((response) => { | |
| response.json().then(data => { | |
| // This is where you get your response back in "data" variable | |
| }); | |
| }) | |
| .catch(() => { | |
| this.message = 'Ooops! Something went wrong!' | |
| }) | |
| .finally(() => { | |
| // Fires when you have finally got the response. | |
| }) | |
| }, | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is not tested to run out of the box, there are certain data that I have not added. You will have to remove certain x-data variables in order to make it work.