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" />
<script type="text/javascript">
function redirect_checkout(){
        $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;

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()?

  • how have you included your form inside 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 use window.location to POST submit a form
    – Tom J Nowell
    Mar 18, 2022 at 0:32
  • The form is included using shortcode from functions.php. It is wrapped inside a function. I was under the impression that I could only use AJAX to run javascript code, not to run php code
    – Griffin
    Mar 18, 2022 at 2:46
  • AJAX is when JS in the browser makes a new request to the server, which runs PHP and returns a response. By the time you're running javascript, all the PHP has already executed, JS/PHP can't be mixed inline like the code in your question, and JS doesn't run on the server. As far as PHP is concerned, your JS tags/code are just text, the same as HTML, not something to load and run as code, that's your browser on the device infront of you that does that. Your browser does not see the PHP either, only the server can see and run PHP code. There is no shared application state
    – Tom J Nowell
    Mar 18, 2022 at 14:21


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.