/    Sign up×
Community /Pin to ProfileBookmark

First validate form and only after that load thank you page

Hello,

I have a form and depending on what checkboxes are selected in the form, it loads a custom thank you page when the form is submited. No problem with this. The problem is that the form loads the thank you page BEFORE the form validating function is completed. How do I fix that? Example below:

***HTML form***

<form action=”my cgi script” name=”example” method=”post” onsubmit=”return validate(this)”>

Boring form data, checkboxes and text fields.

<input type=”submit” onclick=”redirect(this.form,’group1′)” value=”example” name=”example” />

*** Close HTML form***

***Javascript***

function validate(form) {
Many, boring, validation functions
}

function redirect (form, group) {
var numberClicked = [];
for (var i=0; i<form.elements.length; i++) {
if (form.elements[i].name == group && form.elements[i].type == ‘checkbox’ && form.elements[i].checked)
numberClicked.push(i);
}
var min=Math.min.apply(Math, numberClicked)+1;
var max=Math.max.apply(Math, numberClicked)+1;
location.href=min+”-“+max+”.htm”
}

***Close Javascript***

Thanks!

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@rtretheweyOct 19.2012 — The 'onclick' function on the Submit button sends the user to the destination page immediately when the user clicks on it, so the <form> data never gets submitted. In theory, you could use AJAX to submit the <form> and then redirect the user, but that's bad practice because you'd always be saying "Thank-you" to the user regardless of the results of the script that processes the form data. Better to have your script redirect the user based on the results of processing the form.
×

Success!

Help @apod42 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...