0

Hello guys!
I have a form and when the user sumbit it a javascript function will be called using onsubmit event. I need to call the function because I need some AJAX code to be executed. And after it's finished, the page needs to be redirected to another page. But I don't know how to do it.
If the new page was something constant I could have put its address in "action" of the form, but the new page is changeable and depends on the input the user has entered.
I tried to use "location.href=..." at the end of javascript function but it didn't work.
Is there any way to do it?

Thanks.

Edited by Soben: n/a

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Airshow
1

Soben,

There's essentially two ways to do this, depending on whether or not you need the form to be submitted.

  1. To submit the form to a dynamically determined url: In the onsubmit handler, include a line of the format form.action = url; , and return true to allow form submission.
  2. To perform a redirect to a dynamically determined url without submitting the form: In the onsubmit handler, include a line of the format location = url; and return false to suppress form submission.

Airshow

Edited by Airshow: n/a

0

Thanks buddy.
First one worked, but second one didn't. Would you please write the code?

0

Soben,

The oft omitted bit is a return in the HTML.

<form name="myform" action="..." method=..." onsubmit="return myOnsubmitHandler();">

In general it's better to attach handlers in javascript rather than HTML, eg.

onload = function() {
  ...
  document.myform.onsubmit = function() {
    ...
    return false; //or true, to control whether or not the form is to be submitted.
  };
  ...
}

Or, the same thing in jQuery:

$(document).ready(function() {
  ...
  $('form[name="myform"]').submit(function() {
    ...
    return false; //or true, to control whether or not the form is to be submitted.
  });
  ...
});

Airshow

Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.