user12649691
user12649691

Reputation:

Redirect after form submission with pure javascript

In my form, I have a user enter in a link, and my goal is to redirect to that link. However, my problem is that whenever I try and get the user to redirect, the form wont redirect to the page. Several people have recommended this:

<form>
  <input type="text" name="blah blah blah" id="url">
  <input type="submit" onclick="return submit_form()">
</form>
function submit_form(){
  window.location.href="a url";
  return false;
}

However, when I do this, my server does not receive the input by the user. How can I fix this?

Edit: I have also tried this:

function submit(){
  url = getElementById("url").value;
  window.location.href = "url";

}

Upvotes: 1

Views: 306

Answers (1)

O. Jones
O. Jones

Reputation: 108806

When you use browser javascript to set window.location.href to a URL, your browser immediately navigates to that URL without intervention from your server. It's similar to typing a URL into the browser's location bar.

If you want your server to do the navigation you need a more complex setup. On your browser, something like this.

<form action="/your/server/route">
  <input type=hidden" name="redirect" value="https://example.com/where/to/redirect">
  <input type="text" name="blah blah blah">
  <input type="submit" >
</form>

Then in your node code handling /your/server/route ...

if (req.body.redirect) res.redirect(req.body.redirect)

That way your server tells the browser to redirect as part of handling the post of your form.

Security tip cybercreeps can misuse the situation where you pass a redirect URL from a browser to your server. Always validate req.body.redirect to make sure it matches what you expect before you use it to actually redirect.

Upvotes: 0

Related Questions