James
James

Reputation: 310

Submit form and redirect not working

EDIT: I should mention the form submits fine manually but with the javascript nothing seems to happen

I'm trying to get a form to autosubmit on page load and then redirect the user. Reason for this is this is part of a PHP page and the data needs to go into my database but then also POST the variables to a 3rd party SMS platform then return to the users dashboard.

My form looks like this:

<html>
   <form action="https://www.example.com" id="myForm" method ="POST">
      <input type="hidden" name="apiKey" value="withheld">
      <input type="hidden" name="message" value="<?php echo $club_name ?> have requested you to play for them this weekend. Please login to your account to see more information and accept.">
       <input type="hidden" name="to" value="<?php echo $to ?>">
       <input type="hidden" name="from" value="withheld">
       <input type="submit" name="submit" id="submit" value="Submit">
   </form>
</html>

This seems to work fine so I assume the Javascript is incorrect which is:

<script>
document.getElementById('myForm').submit();
    window.location.replace("https://www.example.com");
</script>

Upvotes: 0

Views: 4678

Answers (2)

Madhav Chaturvedi
Madhav Chaturvedi

Reputation: 621

In your code window.location.replace("https://www.example.com"); line won't make sense because submit() function will try to submit the form and will change the page and then replace function will prevent submitting the form and will redirect the page. The right way to do this via js can be, submit the form via ajax and in the success callback of Ajax run document.getElementById('myForm').submit()

Upvotes: 0

Oliver Erdmann
Oliver Erdmann

Reputation: 361

You have to use a different name than name="submit" as all name attributes are set as properties on the form, hence overriding the default "submit" property on the form, and the default form method "submit()" is gone.

https://developer.mozilla.org/de/docs/Web/API/HTMLFormElement "Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute)."

Upvotes: 2

Related Questions