Page 1 of 1

Javascript doesn't stop form.php after submit.

Posted: Tue Apr 27, 2010 5:41 pm
by marcelcolt
I have a php mailform in which i included some javascript (jQuery) for form-validation purposes.
At first i included the JS in an external script, but that didn't work.
But even with the script inside the same page it won't work.

Problem is that when the submit-button is pressed, a JS check-function should stop the php from sending the mail (or give a error-page), but it doesn't.
I included a "return", but i don't know if a JS-return gives the same result as a PHP-return and if both understands each others return.

I included JS to show messages if a field is empty or faulty after submitting, so i tried removing the "method" from the form-tag.
Just to check how and if my JS was working.
What happens next is...nothing!
Tried showing (.show) the error-messages on submitting (as a test) and that works...for a split second.
Then the page refreshes/reloads and the error-message disapears again.

Please help!

This is what i got sofar:

Code: Select all

<form action="mailformulier.php" method="post">

	<table cellspacing="10" class="contact">
		<tr><td>Naam:</td><td><input name="klant_naam" class="inputfield" id="name" value="<?php echo $_SESSION['naam']; ?>"></td><td><span id="nameSyntax">Er is iets mis met Uw naam.</span><span id="nameEmpty">U heeft geen naam ingevoerd.</span></td></tr>
        <tr><td>Email:</td><td><input name="klant_mail" class="inputfield" id="mail" value="<?php echo $_SESSION['mail']; ?>"></td><td><span id="mailSyntax">Er is iets mis met Uw mailadres.</span><span id="mailEmpty">U heeft geen mailadres ingevoerd.</span></td></tr>
        <tr><td>Onderwerp:</td><td><SELECT NAME="klant_subject">
									<OPTION <?php echo $_SESSION['select1']; ?> >Copyright-vraag</OPTION>
                                    <OPTION <?php echo $_SESSION['select2']; ?> >Bestelling plaatsen</OPTION>
									<OPTION <?php echo $_SESSION['select3']; ?> >Vraag over een foto</OPTION>
									<OPTION <?php echo $_SESSION['select4']; ?> >Vraag over een verhaal</OPTION>
									<OPTION <?php echo $_SESSION['select5']; ?> >Suggesties</OPTION>
									<OPTION <?php echo $_SESSION['select6']; ?> >Algemeen</OPTION>
									</SELECT></td></tr>
		<tr><td valign="top">Bericht:</td><td><textarea name="klant_bericht" cols="50" rows="10"><?php echo $_SESSION['bericht']; ?></textarea></td><td><span id="messageEmpty">U heeft geen bericht ingevoerd.</span></td></tr>
		
		<tr>
			<td></td>
			<td>
				<input type="submit" value="Verstuur mijn bericht!" onSubmit="return formCheck();">
			</td>
		</tr>
	</table>

</form>
And this in the included javascript-file:

Code: Select all

function formCheck (){

//set vars
	var checkNameSyntax = "/[a-z0-9_&-]+/i";
	var checkMailSyntax = "/^[a-z0-9\'\\.\^+_-]+@[a-z0-9-]+\\.+[a-z0-9]{2,6}$/i";

//check for errors
	//check name
	if (klant_naam.test(checkNameSyntax) == false){
		if (klant_naam.test("") == true){
			jQuery('#nameEmpty').show();
		}
		else {
			return false;
			jQuery('#nameSyntax').show();
		};
	}
	
	//check mail
	else if (klant_mail.test(checkMailSyntax) == false){
		if (klant_mail.test("") == true){
			jQuery('#mailEmpty').show();
		}
		else {
			return false;
			jQuery('#mailSyntax').show();
		};
	}
	
	//check message
	else if (klant_bericht.test("") == true){
		return false;
		jQuery('#messageEmpty').show();
	}
	
	else {
		return true;
	}

}

Re: Javascript doesn't stop form.php after submit.

Posted: Tue Apr 27, 2010 6:19 pm
by califdon
I'm afraid you are confused about client-side and server-side languages. There is no interaction because one (PHP) is executed BEFORE anything is sent to the browser, the other (Javascript) is executed AFTER the browser receives the page. They cannot possibly communicate with each other.

There are several ways to handle client-side form data validation. The way I recommend in your case is this:
  • Assign a name to your form (<form name='myform' action='...' method='...'>)
  • Do NOT have a type='submit' button. Instead, have a type='button' button with an onClick event which is your Javascript function (<input type='button' value='Verstuur mijn bericht!' onClick='formCheck();'>)
  • In your Javascript function, when all validation is satisfactory, call the submit method of your form (document.myform.submit();)
The problem you are experiencing is because you are using a type=Submit button, which insures that when it is clicked, IT WILL SUBMIT YOUR DATA to the action= script on the server! The fact that you also call a Javascript function is just an extra action for it to perform. If you want the possibility of NOT submitting your data, you must NOT use a type=Submit button.

Re: Javascript doesn't stop form.php after submit.

Posted: Tue Apr 27, 2010 7:12 pm
by Eran
Actually, the correct way is to use a submit button and attach a submit event to the form. Replacing the submit button with a regular button will prevent the form from being submitted the standard way if Javascript is disabled, and in any case won't prevent the form from being submitted by pressing the "enter" key in any of the text inputs.

using jquery, you should do something like this:

Code: Select all

$('form').submit(function(e) {
     e.preventDefault(); //Prevents the form from being submitted
     if( formCheck() ) {
         $(this)[0].submit(); // Submit the form if it passed validation
     }
});
Of course, you should back this up with server side validation regardless to prevent malicious or unintended abuse of your form.

Re: Javascript doesn't stop form.php after submit.

Posted: Tue Apr 27, 2010 7:19 pm
by califdon
Thanks for the better advice, pytrin, and the reasoning behind it. And yes, I forgot to mention the importance of server-side validation. I don't use jquery (yeh, I know...), so that didn't occur to me. But I'm glad to pick up some good info on the form submit operation.

Re: Javascript doesn't stop form.php after submit.

Posted: Tue Apr 27, 2010 11:58 pm
by marcelcolt
Thanks Pytrin, but the function doesn't seem to work.

How should it work and stop the submitting?

Re: Javascript doesn't stop form.php after submit.

Posted: Wed Apr 28, 2010 12:02 am
by califdon
Do you have the jquery library? You must understand that you can't just copy a piece of code that someone shows you to illustrate the principle and expect it to work in your script. Programming is something that must be learned in considerable depth, not just copied, a little bit at a time.

Re: Javascript doesn't stop form.php after submit.

Posted: Wed Apr 28, 2010 3:13 am
by Eran
Thanks Pytrin, but the function doesn't seem to work.

How should it work and stop the submitting?
You need to make sure you attach events after the document is ready. Using the ready() event on the document or something similar

Code: Select all

$(document).ready(function() {
  //Attach form event
});
http://docs.jquery.com/Tutorials:Introd ... eady%28%29

Re: Javascript doesn't stop form.php after submit.

Posted: Wed Apr 28, 2010 6:13 am
by marcelcolt
No, i do know a little by now.

So yes i have jQuery "installed (i have a sliding photo-gallery too).
And yes i will always keep checking the forms with regex's in php (i actually know several people who have JS switched off).

I just wanted to know how "e.preventDefault(); " works; what does it do (is that even correct english?).

Re: Javascript doesn't stop form.php after submit.

Posted: Wed Apr 28, 2010 7:54 am
by Eran
I'm not sure what do you mean by having jquery "installed", but what I've shown is something different. Regarding preventDefault() - it does exactly what it says, prevents the event default action from taking place.
http://api.jquery.com/category/events/event-object/

Re: Javascript doesn't stop form.php after submit.

Posted: Fri Apr 30, 2010 5:02 pm
by marcelcolt
With having it installed i mean having the js-file on the server and calling it in every page i need and use it in.

Well, i figured it out diferently.
The preventDefault() function actually did nothing; the php-script kept doing whatever it liked.
So i tought my brains out and came up with a solution php-style!

The form is submitted to mailform.php, wich is redirected back to index.php (using $_SESSION) to display error-messages.
Mailform.php also called a jQuery (.css) to display a background-image (red rectangle or something like that).
Using php will always show at least the error-message, even if the user has JS switched off.

Upon submitting and succesfully sending the e-mail the user gets redirected back to index.php, using $_SESSION['redirect']
while sending

Code: Select all

<meta http-equiv="refresh" content="0;URL=mailsent.php">
into the "HEAD" of the index.php-page, instantly redirecting the user to a page displaying a "thank you"-message.

And thus a solution is born.

Nevertheless a lot of thanks to all of you!