My form looks like the following, it's inside functions.php
<form style="text-align: center;" action="https://website/checkout/" method="POST" onsubmit="return redirect_checkout()">
<div style="position:relative; right: 107px">Where should we send it to? (postcode)<span style="color: red"> *</span></div>
<input type="text" class="form-text" size="70" name="where" id="where" />
<input type="submit" class="elementor-button elementor-size-sm" id="searchsubmit" name="searchsubmit" value="PROCEED TO CHECKOUT" />
</div>
</form>
<script type="text/javascript">
function redirect_checkout(){
<?php
$user = wp_get_current_user();
$id = $user->ID;
update_user_meta( $id, "shipping_postcode", $_POST['where'] );
?>
window.location.href = "https://website.com/checkout";
return true;
}
</script>
The problem is that the function redirect_checkout doesn't seem to run if I call action->redirect in the form fields, and the form doesn't redirect if I rely on window.location.href in the function. How can I get the form to redirect only after it runs the php code inside redirect_checkout()?
functions.php
? Is it wrapped inside a function? A shortcode? Hook? AJAX? The PHP code runs when the output is generated, not when the javascript function is called. PHP runs on the server when the page is generated, javascript runs on your computer in the browser, if you want PHP code to run when something happens in javascript then you have to make a new request to the server, that's what AJAX is for. Also a redirect and a form submission are not the same thing, you cannot usewindow.location
to POST submit a form