Javascript doesn't stop form.php after submit.

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
marcelcolt
Forum Newbie
Posts: 22
Joined: Tue Mar 02, 2010 5:56 am

Javascript doesn't stop form.php after submit.

Post 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;
	}

}
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

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

Post 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.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

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

Post 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.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

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

Post 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.
marcelcolt
Forum Newbie
Posts: 22
Joined: Tue Mar 02, 2010 5:56 am

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

Post by marcelcolt »

Thanks Pytrin, but the function doesn't seem to work.

How should it work and stop the submitting?
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

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

Post 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.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

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

Post 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
marcelcolt
Forum Newbie
Posts: 22
Joined: Tue Mar 02, 2010 5:56 am

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

Post 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?).
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

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

Post 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/
marcelcolt
Forum Newbie
Posts: 22
Joined: Tue Mar 02, 2010 5:56 am

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

Post 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!
Post Reply