Skip to content

Instantly share code, notes, and snippets.

@git-bhanu
Created September 1, 2020 12:50
Show Gist options
  • Select an option

  • Save git-bhanu/7091ddb279e5e57796ac2fc7e6704664 to your computer and use it in GitHub Desktop.

Select an option

Save git-bhanu/7091ddb279e5e57796ac2fc7e6704664 to your computer and use it in GitHub Desktop.
Example : Using Alpine Js to set WordPress AJAX method.
<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>
// 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.
})
},
}
}
@git-bhanu

Copy link
Copy Markdown
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment