Dave Lynch
Dave Lynch

Reputation: 65

How to post to url BUT redirect to other location?

My form is doing a POST to its action URL perfectly but when I submit the form it takes me to the URL of the POST.

I was wondering if I could still post to the action URL but redrect to another page?

I've tried using return false; but I'm still taken to the action URL.

Here's my code so far:

<form id="login" onSubmit="return login();">
  <input id="username" type="text" name="username" id="username" placeholder="Username">
  <input type="password" name="password" id="password" placeholder="Password">
  <input id="login-btn" type="submit" value="Login">
</form>

<script>
function login() {
  var url="actionurl";
  location.href=url;
  return false;
}
</script>

so i used this script on another app which posts to a php url and sends an email without leaving the page of the form

<script type="text/javascript">
  $(document).ready( function () {
    $('form').submit( function () {
        var formdata = $(this).serialize();
         $.ajax({
              type: "POST",
              url: "http://myurl.com/email-form/send_form_email.php",
              data: formdata,
           });
         return false;
     });
 });
</script>

is there a way of modifying this to add the username and password variables entered from my login form on the this url https://www.myurl.com/index.php?option=com_hoicoiapi&task=login&

just a thought as it works on my email form.

PS it is important ?option=com_hoicoiapi&task=login& is on the url and that &username=test&pass=1234 comes from the form.

Upvotes: 1

Views: 424

Answers (2)

adeneo
adeneo

Reputation: 318302

You'd have to send the form with a GET request, which is what you're using, with ajax, and then redirect

var url_to_send_to  = 'actionurl';
var url_to_redirect = 'otherurl';

$('#login').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        url  : url_to_send_to,
        type : "POST",
        data : $(this).serialize()
    }).done(function() {
        window.location.href = url_to_redirect
    });
});

And remove the inline event handler ,,,

Upvotes: 3

HaukurHaf
HaukurHaf

Reputation: 13816

No, you cannot to that unless you perform the POST using AJAX and in the callback, you can redirect the browser using Javascript (document.location.href = 'someurl').

The only way to do this without resorting to Javascript is to have the POST url do a server-side redirect to your desired URL.

Upvotes: 2

Related Questions