I’m currently hacking my way through a Shopify theme. There is a form like this:
<form action="/cart" method="post">
...
<button type="submit">Checkout</button>
</form>
When this button is clicked you are taken to the checkout page. Fairly standard.
However, I want to display a popup before the form action is completed. Not a browser API alert
box something I can style and have control over in the browser.
So I’ve updated the form and added some JavaScript:
<form action="/cart" method="post">
...
<button onclick="confirmTerms(event)">Checkout</button>
</form>
<script>
const confirmTerms = (event) => {
// confirmTerms shows a popup box with an accept and deny buttons and stops the event from firing.
document.getElementsByClassName('background-cover')[0].style = "display: flex; opacity: 1";
event.preventDefault()
}
const termsAccept = () => {
//terms accept is connected to the acceptance button on the form that is displayed by confirmTerms.
const form = document.getElementById("chart-checkout-form");
form.submit() // <- this is the specific method that I'm trying to work through I've tried all the iterations listed below.
}
Based on the user’s choice in the popup, I want to then submit the POST request and be directed to the checkout page.
So what is need is something with the functionality of form.requestSubmit
but that works with all major browsers (including Safari which requestSubmit
does not). Any ideas of something that will let me do what requestSubmit
does?
That’s my question in a nutshell, for further context feel free to read the rest of the post:
First I reached for:
form.submit()
But this took me to /cart
rather than /checkout
which I assume is because the form’s action is cart
and it’s not taking into account the method="post"
.
So then I tried:
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "/cart", false);
xhttp.send();
No errors, but when the button is hit nothing happens. Lastly, I tried an async function with fetch
and had the same issue as xhttp
.
The only thing I have gotten to work is form.requestSubmit
but that is not supported by Safari so it’s a no go. But that’s what I need, essentially the same functionality one gets from form.requestSubmit
.