Search code examples
javascripthtmlzapier

How to post form submission to a URL and redirect on submission to a different URL


I would like to post the form fields to 1 url and redirect to a different url. The code i have posts to the url i want but how to i redirect to a different one? URL I want to post the submissions to: www.mywebsite.com/submissions URL I want to redirect the user to on submission: www.anotherwebsite.com/confirmation

Here's what i have so far:

<form action="https://mywebsite.com/submissions" 
method="post">

    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">

</form>

Solution

  • There are two ways to do this:

    1. Submit the form using Ajax, and after success, redirect from Javascript
    2. Submit the form normally, and send redirect response from server, with new url

    (2) depends on your serverside language - be it PHP or Java.

    Some kind of redirect feature will be available in your backend language or library. It will send a HTTP 301 response with an alternate URL. The browser will automatically load the new URL provided.

    Edit:

    For (1) you can handle button click, prevent default behavior, and post the form manually via Ajax. Once completed, you redirect the page.

    // this is the id of the form
    $("#FormID").submit(function(e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.
        var form = $(this);
        var url = form.attr('action');
        $.ajax({
               type: "POST",
               url: url,
               data: form.serialize(), // serializes the form's elements.
               success: function(data)
               {
                   alert(data); // show response 
                   window.location.href = "www.anotherwebsite.com/confirmation";
               }
             }); 
        });
    

    Adapted from this SO answer: https://stackoverflow.com/a/6960586/1364747