input button not getting set in the POST variable - php

I have a page with two forms. I need to know which button is submitting the form. When the form gets submitted I am checking the set status of the button, but it doesn't seem to be set. Can anyone help?
HTML
<div id="contact-wrapper" class="">
<h1 style="color: white">Send me an email.</h1>
<div id="msg-status"></div>
<form id="contact" method="post">
<div class="contact-title">Email Address</div>
<input type="email" name="emailAddress" id="email-addr-txt" placeholder="Your Email Address" require>
<div class="contact-title">Subject</div>
<input type="text" name="emailSubject" id="email-subject-txt" placeholder="Subject" require>
<div class="contact-title">Message</div>
<textarea name="emailMessage" id="email-msg-txt" placeholder="Message" require></textarea>
<input type="submit" name="sendBtn" value="Send" id="send-msg-btn">
</form>
</div>
PHP
<?php
$phpconsole = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
if (isset($_POST["loginBtn"])) {
//Do Stuff
}
if (isset($_POST["sendBtn"])) {
//Do Stuff
}
$phpconsole = var_dump($_POST); }
?>
JavaScript
$('#contact').submit(function(e){
e.preventDefault();
email_regex = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
var msg = "";
if ($('#email-addr-txt').val() == ""){
msg += "<p>The email address is missing!</p>";
} else if (!email_regex.test($('#email-addr-txt').val())) {
msg += "<p>The email address is invalid!</P>"
}
if ($('#email-subject-txt').val() == "") {
msg += "<p>The Subject is missing!</p>";
}
if ($('#email-msg-txt').val() == "") {
msg += "<p>The message is missing!</p>"
}
var heightOfContactWrapper = $('#contact-wrapper').height();
if (msg != "") { // There were errors that need to be delt with before sending message.
msg = "<h2>There were errors.</h2>" + msg;
$('#msg-status').html(msg);
$('#msg-status').addClass('msg-status-fail');
var heightOfMsgStatus = $('#msg-status').height() + $('#contact-wrapper').height() + "px";
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
} else { //No errors found.
$('#msg-status').removeClass('msg-status-fail');
$('#msg-status').addClass('msg-status-success');
$('#msg-status').html("<h2>Message is sending. Please wait.</h2>")
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
$('#contact').unbind('submit').submit();
}
});
Output of var_dump is
array(3) { ["emailAddress"]=> string(13) "asdf#aedf.com"
["emailSubject"]=> string(4) "asdf" ["emailMessage"]=> string(4)
"asdf" }
Errors are:
Notice: Undefined index: loginBtn in /var/www/new-site/index.php on
line 5 Notice: Undefined index: SendBtn in /var/www/new-site/index.php
on line 5

The problem is that your Javascript code ends up being the thing that triggers the form submit, not your button. If you removed your JS code you'd see your sendBtn value.
Instead of calling e.preventDefault in your .submit() callback, you could just return true if you want the form submission to continue, or false if you don't. That way, you don't have to call $('#contact').submit() to get your form to submit, or even unbind your submit handler. Something like this:
$('#contact').submit(function(e){
email_regex = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
var msg = "";
if ($('#email-addr-txt').val() == ""){
msg += "<p>The email address is missing!</p>";
} else if (!email_regex.test($('#email-addr-txt').val())) {
msg += "<p>The email address is invalid!</P>"
}
if ($('#email-subject-txt').val() == "") {
msg += "<p>The Subject is missing!</p>";
}
if ($('#email-msg-txt').val() == "") {
msg += "<p>The message is missing!</p>"
}
var heightOfContactWrapper = $('#contact-wrapper').height();
if (msg != "") { // There were errors that need to be delt with before sending message.
msg = "<h2>There were errors.</h2>" + msg;
$('#msg-status').html(msg);
$('#msg-status').addClass('msg-status-fail');
var heightOfMsgStatus = $('#msg-status').height() + $('#contact-wrapper').height() + "px";
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
return false;
} else { //No errors found.
$('#msg-status').removeClass('msg-status-fail');
$('#msg-status').addClass('msg-status-success');
$('#msg-status').html("<h2>Message is sending. Please wait.</h2>")
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
return true;
}
});

Related

Undefined variables in PHP after sending data via Ajax

I am trying to send data via Ajax to my php file and process it, I don't know where is the error Ajax seems to be Okay but after receiving data via $_POST in php file but when I am trying to echo my variables I am getting errors.
I am sending data using a POST;
here is my frontend code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- <form id="ArticleEnterForm" method="POST" action="ProcessFormData.php"> -->
<div id="warningsDiv">
wowowo
</div>
<label id="ArticleTitleLabel">Article title: </label>
<input id="ArticleTitleInputField" type="text" name="">
<div>
</div>
<iframe id="ArticleiFrame"></iframe>
<label>Enter article: </label>
<textarea id="ArticleContentTextArea"></textarea>
<label id="ArticleFileNameLabel">Enter file name(save as):</label>
<input id="ArticleFileNameInputField" type="text">
<button id="SubmitButton" name="submitButton">Submit</button>
<!-- </form> -->
<script>
function SubmitForm() {
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
//submitting using POST method
var sendDataRequest = new XMLHttpRequest();
sendDataRequest.open("POST", "ProcessFormData.php", true);
sendDataRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendDataRequest.onreadystatechange = function () {
if (sendDataRequest.readyState === 2) {
warningsDiv.innerHTML = "<strong>Loading...</strong>";
}
if (sendDataRequest.readyState === 4 && sendDataRequest.status === 200) {
console.log("dtatus: " + sendDataRequest.readyState);
warningsDiv.innerHTML = sendDataRequest.responseText;
}
}
var dataToSend = "ArticleTitleData=" + articleTitle + "&ArticleContentData=" + articleContent + "&ArticleFileNameData=" + articleFileName;
sendDataRequest.send(dataToSend);
}
var submitButton = document.getElementById('SubmitButton');
submitButton.addEventListener("click", SubmitForm);
</script>
</body>
</html>
and here is my PHP code:
<?php
ini_set('display_errors', 'On'); //to get errors displayed
$ArticleTitle = "";
$ArticleContent = "";
$ArticleFileName = "";
if(isset($_POST['ArticleTitleData'])){
$ArticleTitle = $_POST['ArticleTitleData'];
}else {
echo("no var artn ");
}
echo("data was entered successfully following data was entered: Title: " . $ArticleTitle );
?>
where is the error in this script.
the response text I am seeing on browser screen is:
data was entered successfully following data was entered: Title: undefined
The problem is that some of the variables you are using, are undefined in the scope you are trying to use them in:
function CheckFields() {
// The variables defined with `var` exist in the scope of this function
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
// No `ArticleTitle`, etc. here...
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
Note that you are defining your variables using var in the CheckFields() function. So the scope of these variables is that function and anything in it, they will not be available outside of the CheckFields() function.
To solve that, you can return them from or define them before the function.
For example:
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
// etc.
Note that if you need the warningsDiv outside of the function as well, you would need to treat it the same.
Yes, I figured out what was the problem
short answer:
when I was not calling the CheckFields(); properly
long answer:
Instead of if(CheckFields() == true){ //something } I was doing if(CheckFields == true){ //something }
I came to know this because when I was submitting the input field empty there was no change in warningsDiv as it was supposed to be when CheckFields(); function is called.
Thanks everyone for helping me...

Button Submit false works, but not the redirecting

Currently, I am working on a formula. I created the check function and they are all working. If the check function returns false nothing gets saved, but it still redirects to the congrats page?
here the code:
function check() {
var msg = "";
if ($_POST['Bustransfer'] == "ja" ) {
msg = "wrong\n";
document.formular.v6.style.backgroundColor = "#FF0000";
}
if (msg == "") return(true);
else {
alert(msg);
return(false);
}
}
and then I got the following in the body section:
<form method="post" action="Email.php" name="formular" onsubmit="return check()">
I don't get it, hope you can help me. Cheers!
You are mixing them(javascript & php) up. Should be '<?php echo $_POST['Bustransfer']; ?>' instead of $_POST['Bustransfer'] in the check.
function check() {
var msg = "";
if ('<?php echo $_POST['Bustransfer']; ?>' == "ja" ) {
msg = "wrong\n";
document.formular.v6.style.backgroundColor = "#FF0000";
}
if (msg == "") return(true);
else {
alert(msg);
return(false);
}
}

php echo keeps opening in new tab, not in jquery notification toastr.js

I cannot seem to find the problem in my code. I want the validation in php file to trigger the jquery notification plugin 'toastr', however, the php echo keeps publishing the php file message status to a new tab, instead. What am I doing wrong and how can I make the message appear in the notification, instead? The live version of my school site is here: Wright State University BMES Site and the problem can be replicated when submitting the Contact Us form. Thank you in advance :)
HTML:
<form action=send-contact.php method=post data-show-errors="true" class=contact-form id=contact-form-id data-parsley-validate>
<p class=half>
<input autofocus parsley-trigger="change" name=name required id=name placeholder="Type your name" class="testBox label_better" data-new-placeholder="Example: Sir Humphrey Charleston III" parsley-required="true">
</p>
<p class=half>
<input name=email id=email placeholder="Type your e-mail address" class="testBox label_better" data-new-placeholder="Example: humphrey.charleston#wright.edu" parsley-type="email" parsley-trigger="change" required parsley-required="true">
</p>
<p>
<select class="contactselect required" name=subject id=subject parsely-required="true" required parsley-trigger="change">
<option value="" parsley-trigger="change">Please select one topic:</option>
<option value="1" parsley-trigger="change">Information about BMES Chapter</option>
<option value="2" parsley-trigger="change">Information about upcoming events</option>
<option value="3" parsley-trigger="change">Other</option>
</select>
</p>
<p>
<textarea name=message id=message rows=12 cols=20 class="label_better_text" placeholder="Tell us what's on your mind." parsley-trigger="keyup" parsley-rangelength="[1,300]" required parsley-required="true"></textarea>
</p>
<p>
<button name=send type=submit onclick="$( '#contact-form-id' ).parsley('validate')" id=submit value=1>Send message</button>
<span class="color-red"><button onclick="$( '#contact-form-id' ).parsley( 'destroy' ); $('#contact-form-id').parsley();" name=reset type=reset value=1>Reset</button></span>
</p>
</form>
<script type=text/javascript>
jQuery(document).ready(function(c){
$('#contact-form').parsley();
$('#contact-form-id').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
$.post("send-contact.php", $(this).serialize());
toastr.success('Thank you, we will attend to your message shortly.');
$( '#contact-form-id' ).parsley( 'destroy' );
}
}); });
</script>
PHP:
<?php
$name = '';
$subject = '';
$email = '';
$message = '';
function getIp()
{if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip_address=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (!isset($ip_address)){
if (isset($_SERVER['REMOTE_ADDR']))
$ip_address=$_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
//taking the data from form
$name = addslashes(trim($_POST['name']));
$subject = addslashes(trim($_POST['subject']));
$email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
//form validation
$errors = array();
$fields = array();
if(!$name) {
$errors[] = "Please enter your name.";
$fields[] = "name";
}
$email_pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\#([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(!$email) {
$errors[] = "Please enter your e-mail address.";
$fields[] = "email";
} else if(!preg_match($email_pattern, $email)) {
$errors[] = "The e-mail address you provided is invalid.";
$fields[] = "email";
}
if(!$subject) {
$errors[] = "Please choose the subject of your message.";
$fields[] = "subject";
}
if(!$message) {
$errors[] = "Please enter your message.";
$fields[] = "message";
}
//preparing mail
if(!$errors) {
//taking info about date, IP and user agent
$timestamp = date("Y-m-d H:i:s");
$ip = getIp();
$host = gethostbyaddr($ip);
$user_agent = $_SERVER["HTTP_USER_AGENT"];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
$headers .= "From: $email\n";
$content = 'Subject: '.$subject.'<br>'.
'Name: '.$name.'<br>'.
'E-mail: '.$email.'<br>'.
'Message: '.$message.'<br>'.
'Time: '.$timestamp.'<br>'.
'IP: '.$host.'<br>'.
'User agent: '.$user_agent;
//sending mail
$ok = mail("my-email-address-normally-goes-here","BMES Website Contact Us ", $content, $headers);
if($ok) {
$response['msgStatus'] = "ok";
$response['message'] = "Thank you for contacting us. We will attend to your inquiry as soon as possible.";
} else {
$response['msgStatus'] = "error";
$response['message'] = "An error occured while trying to send your message. Please try again.";
}
} else {
$response['msgStatus'] = "error";
$response['errors'] = $errors;
$response['errorFields'] = $fields;
}
header('Content-type: application/json');
echo json_encode($response);
?>
Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var formTop = form.offset().top;
var url = form.attr("action");
var data = form.serialize();
form.find("input, select, textarea, span").removeClass("error");
form.find(".msg").remove();
button.html("Sending...");
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
form.prepend('<p class="msg success"><a class="hide" href="#">hide this</a>' + msg + '</p>');
form.find("input, select, textarea").val("");
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
form.prepend('<div class="msg error"><a class="hide" href="#">hide this</a><p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p></div>');
} else form.prepend('<p class="msg error"><a class="hide" href="#">hide this</a>' + msg + '</p>');
}
$(".msg a.hide").click(function(e){
e.preventDefault();
$(this).parent().slideUp();
});
button.html(buttonText);
window.scrollTo(0, formTop);
}, 'json');
})
});
Have you tried playing with your jquery a bit more? for instance, ajax instead of post.
something like this?
button.click(function () {
$.ajax({
url: url,
type: 'POST',
data: form.serialize(),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.msgSTatus == "ok"){
alert(data.message);
// play with html here once you know the page stays.
}
},
error: function (data) {
alert('Fail.');
}
});
});
As far as html appending goes, I would personally have an empty on the page already with an id, and just set the content of the div to the data that you receive, would make the js look much cleaner maybe..
Try including jquery before your other scripts. Also, use Firebug or build-in browser JS debugging tools to troubleshoot Javascript errors.
I have managed to solve the issue. Alterations are listed below for comparative purposes to not only help others but to also close this issue. A special thank you to #WhiteRuski for pointing me in the right direction. The PHP and HTML remain unchanged. Here is the new Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var url = form.attr("action");
var data = form.serialize();
// button.html("Sending...");
button.html('<i class="fa fa-cog fa-lg fa-spin"></i>' + ' Sending ... ');
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
toastr.success('<p>' + msg + '</p>');
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
// toastr.error('<p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p>'); This lists the specific errpr in the field
toastr.error('<p>There were a few errors in your form. Please resubmit with corrections.</p>');
} else toastr.error('<p>' + msg + '</p>');
}
button.html(buttonText);
}, 'json');
})
});

I can't get my form to validate AND submit using jQuery validation

I have been digging around on here and other sites for a while and am stuck. I'm trying to use jQuery to validate my form (concurrently as the user fills out the form) and, if the form is valid have it submit to a php page I have created to process the contents of the form. I have been able to have it validate but I can't have it also submit it...if I put a value in for the form action parm then it bypasses the validation. Please help...
I apologize, in advance, for the bad coding.
Here is my jquery-validate.js:
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage())
return true;
else
return false;
});
My form code is pasted here:
<form method="post" id="customForm" action="rcv-form1.php">
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<span id="nameInfo">What's your name?</span>
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" />
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</div>
<div>
<label for="pass1">Password</label>
<input id="pass1" name="pass1" type="password" />
<span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
</div>
<div>
<label for="pass2">Confirm Password</label>
<input id="pass2" name="pass2" type="password" />
<span id="pass2Info">Confirm password</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="" rows=""></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</form>
And here is my php that receives the form (this is just for testing now. i will email or insert into mySQL once i know i can properly validate stuff):
<html><head>
<title>Display form values</title>
</head>
<body>
<?
//$valid_form = TRUE;
//$bad_field_count = 0;
$table1_beg = '<center><table align="center" bordercolor="#F00" width="600px" border="3" cellspacing="1" cellpadding="1"><caption>Form status</caption><tr><th scope="col">Field Name</th><th scope="col">Field Value</th></tr>';
$row_beg = '<tr><td>';
$td = '</td><td>';
$row_end = '</td></tr>';
$table1_end = '</table></center>';
function checkEmail($field)
{
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
//echo "This ($field) email address is considered valid.";
return $field;
} else {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
//global $bad_field_count; $bad_field_count++;
return $field;
}
}
function SanitizeString($field)
{
$field = filter_var($field, FILTER_SANITIZE_STRING);
//if(is_null($field) || $field == '') { global $bad_field_count; $bad_field_count++;}
return $field;
}
// ensure form data is valid
$name=SanitizeString($_POST['name']);
//$email=$_POST['email'];
$email = checkEmail($_POST['email']);
$pass1=SanitizeString($_POST['pass1']);
$pass2=SanitizeString($_POST['pass2']);
$message=SanitizeString($_POST['message']);
echo $table1_beg;
echo $row_beg . "Name" . $td . "<u>" . $name . "</u>" . $row_end;
echo $row_beg . "Email" . $td . "<u>" . $email . "</u>" . $row_end;
echo $row_beg . "Password 1" . $td . "<u>" . $pass1 . "</u>" . $row_end;
echo $row_beg . "Password 2" . $td . "<u>" . $pass2 . "</u>" . $row_end;
echo $row_beg . "Message" . $td . "<u>" . nl2br($message) . "</u>" . $row_end;
//echo $row_beg . "Number of bad fields" . $td . "<b>" . $bad_field_count . "</b>" . $row_end;
echo $table1_end;
//}
?>
</body></html>
Problem 1: When I have form action="" I can validate the form only after hitting submit...it doesn't say it's invalid until after submitting when I thought it should do it concurrently as it is typed in.
Problem 2: If I have my form action set to anything but "" it will ignore the jQuery validation all together.
I'm new to the form validation stuff. Can someone point me in the right direction? Thanks, in advance!
You have a few problems, your form submit code doesn't have curly brackets around it, and you don't have a function for validate email, try this:
//global vars
var form = $("#customForm");
var fname = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName() {
//if it's NOT valid
if (fname.val().length < 4) {
fname.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
fname.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass2() {
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if (pass1.val() != pass2.val()) {
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else {
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validatePass1() {
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if (pass1.val().length < 5) {
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else {
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
return true;
}
}
function validateEmail(){
//add validation for email here
return true;
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
fname.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
fname.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function() {
if (validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage()) {
return true;
}
else {
return false;
}
});
I've gave you an easy way to validate your all inputs/textarea within one function but you have to complete it, I've just gave you the structure and only name validation has done as an example for you and I hope you can understand it easily. If you need more help/difficulties just leave a message. This should be placed inside ready event.
var info={
'nameInfo':$("#nameInfo"),
'emailInfo':$("#emailInfo"),
'pass1Info':$("#pass1Info"),
'pass2Info':$("#pass2Info")
}
$('#customForm input,textarea').not("#send").bind('blur keyup', function(e)
{
e.stopPropagation();
var el=$(e.target);
var id=el.attr('id');
if(el.attr('id')=='message' && e.type=="keyup")
{
return false;
}
else
{
if(id=="name")
{ if(el.val().length < 4)
{
el.addClass("error");
info.nameInfo.text("We want names with more than 3 letters!");
info.nameInfo.addClass("error");
return false;
}
else
{
el.removeClass("error");
info.nameInfo.text("What's your name ?");
info.nameInfo.removeClass("error");
return true;
}
}
if(id=="email")
{
// Your email validation code
}
if(id=="pass1")
{
// Your pass1 validation code
}
if(id=="pass2")
{
// Your pass2 validation code
}
if(id=="message")
{
// Your message validation code
}
}
});

jQuery getting these functions to work together

I'm new to jQuery and have tried looking around for an answer on how to do this. I have 2 functions and I would like both to work together. The one function is submitHandler and its used to hide a form and at the same time add a class to a hidden element to unhide it - ie a thank you for submitting h1. The other function is to grab the input data and display it onsubmit in the form. So the problem is that I can get that one to work but then the other doesnt. Ie on form submit I can see the data input but not the h1 Thank you message.
Here are the functions:
SubmitHandler:
submitHandler: function() {
$("#content").empty();
$("#content").append(
"<p>If you want to be kept in the loop...</p>" +
"<p>Or you can contact...</p>"
);
$('h1.success_').removeClass('success_').addClass('success_form');
$('#contactform').hide();
},
onsubmit="return inputdata()"
function inputdata(){
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
return true;
},
The form uses PHP and jQuery - I dont know about AJAX but after some reading even less sure. Please help me out I dont know what I'm doing and at the moment I am learning but its a long road for me still.
Thank you
The form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform" onsubmit="return inputdata()">
<div class="_required"><p class="label_left">Name*</p><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><p class="label_left">E-mail address*</p><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<p class="label_left">Message</p><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<input type="submit" value="submit" name="submit" id="submit" />
</form>
The PHP bit:
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The Jquery Validate bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
Here is the full jQuery bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
});
});
Latest edit - Looks like this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
function submitHandler() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
function inputdata() {
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
},
$(document).ready(function(){
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
});
});
I know this question has already been answered and this isn't directly regarding the question itself; more so regarding the code in the question. However, I can't post comments as I'm a brand new member, but I just thought I'd highlight a few things in your code! Mainly consistency regarding the use of jQuery.
In the function supplied for 'submitHandler' - you empty $('#content') and then append HTML to it. This will work, but an easier method would be using the .html() function; note that this function can be used to return the HTML contained inside an element; but that's when no arguments are supplied. When you supply an argument, it re-writes the content of the html element. Additionally, I would most likely use the .show() method on the h1 success element; if only for code readability.
For example:
submitHandler: function(){
$('#content').html( "<p>If you want to be kept in the loop...</p>"
+ "<p>Or you can contact...</p>");
$('h1.success_').show();
$('contactform').hide();
}
As for inputdata() - you seem to have strayed off of the jQuery ethos here a little again, I'd aim for consistency when using jQuery personally - but also as the jQuery syntax makes the traditional javascript 'document.getElemen...' object look a bit outdated/it's extra to type. At its most basic jQuery is essentially best viewed as a wrapper for the document object - just with added syntactical sugar. Additionally, it allows you to chain methods - so the last two expressions can essentially be "dressed up" to look as one when using jQuery.
I'd personally use .val(), .html() and .css() functions; example:
function inputdata(){
var usr = $('#contactname').val();
var eml = $('#email').val();
var msg = $('#message').val();
$('#out').html( usr + " " + eml + msg )
.css('display', 'block');
return true;
}
Your submitHandler function isn't called. That's why it doesn't work.
Add this to your code:
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
EDIT:
try this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
CHange return true, to return false in the inputdata function

Categories