movecx
movecx

Reputation: 55

AJAX for redirecting to external domain when submitting form

I have a form as so, which submits data to an outside domain:

<form action="https://EXTERNALdomain.com/register" id="form_register" method="POST">

  <input type="text" id="first-name" name="first-name" value="" placeholder="First Name" required/>
  <input type="text" id="last-name" name="last-name" value="" placeholder="Last Name" required/>
  <input type="email" id="email" value="" name="email" placeholder="Email Address" required/>
  <input type="password" id="password" name="password" placeholder="Password" required/>

  <input type="submit" value="Create Account" />

</form>

However, I'm trying to be able to submit the form AND redirect it to a different page, also externally. So far, my attempts have been unsuccessful with AJAX.

<script type="text/javascript">
function sform() {
    $.ajax({
        url: "https://EXTERNALdomain.com/home",
        data: $('#request').serialize(),
        type: 'POST',
        success: function (resp) {
            alert(resp);
        },
        error: function(e) {
            alert('Error: '+e);
        }  
   });
}

I've then been calling the form as so:

<form onsubmit="sform()" id="request">

This isn't working. I just get a long URL, and the form doesn't actually post, the page just reloads

Upvotes: 0

Views: 539

Answers (1)

tcooc
tcooc

Reputation: 21209

This is because you're letting the form submit, which changes the page url and POSTs data there.

From "submit the form AND redirect it to a different page" I assume you want to submit the form to https://EXTERNALdomain.com/register and redirect to https://EXTERNALdomain.com/home. To do this, you need to use $.ajax to submit the form, them change the location on success.

function sform() {
    $.ajax({
        url: $('#request').attr("action"),
        data: $('#request').serialize(),
        type: $('#request').attr("method"),
        success: function (resp) {
            location.href = "https://EXTERNALdomain.com/home"; // redirect
        },
        error: function(e) {
            alert('Error: '+e);
        }  
   });
   return false; // cancel default action
}

Upvotes: 1

Related Questions