stevenvh
stevenvh

Reputation: 3159

Passing parameters from JavaScript

I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a submit button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page writing location = mail.php but it appears that the form parameters don't get passed to my PHP page this way.
How do I validate input in JavaScript and pass parameters to my PHP page when ok?
TIA
Steven

Upvotes: 2

Views: 642

Answers (5)

Your Friend Ken
Your Friend Ken

Reputation: 8872

The function validate() returns a bool. This will stop the submission if validate() returns false.

<input type="submit" onclick="return validate()" value="click" />

I am an aspx.net developer so I am used to putting the validation call on the button.

Upvotes: 1

Yuval Adam
Yuval Adam

Reputation: 165340

You should still use the submit button to submit the form, that is the correct behavior.

Input validation should be done using the <FORM>'s onSubmit event. It should look something like this:

<script>
    function validate() {
        var isFormValid = whatever; // validate form
        return isFormValid;
    }
</script>

<form action="your.php" method="POST" onSubmit="return validate()">
    <!---fields--->
</form>

Upvotes: 1

chobo2
chobo2

Reputation: 85865

If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.

Such as

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Upvotes: -2

ylebre
ylebre

Reputation: 3130

You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.

You'd have a javascript function something like this:

function check_it_all() { 
  if (all_ok) {
     return true;
  } else {
     return false;
  }
}

And the form

<form action=.....  onsubmit="return check_it_all();">
....
</form>

Upvotes: 7

Edward Dale
Edward Dale

Reputation: 30143

Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here.

Upvotes: 5

Related Questions