have multiple alert boxes in a contact form - javascript

Hello i am trying to do a contact form that gives me an alert box when i press the submit button (e.g. one alert box for "form could not be submitted" and one for "form was successfully submitted")
How can i do this? Does it work with if/else ?
I worked with html/php/js for the form, below is my code (sorry for german)
$anrede = $vorname = $nachname = $anschrift = $postleitzahl = $stadt = $email = $telefon = $nachricht = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["anrede"])) {
$anredeErr = "* Anrede wird benötigt";
} else {
$anrede = test_input($_POST["anrede"]);
}
if (empty($_POST["vorname"])) {
$vornameErr = "* Vorname wird benötigt";
} else {
$vorname = test_input($_POST["vorname"]);
if (!preg_match("/^[a-zA-Z]*$/",$vorname)) {
$vornameErr = "* Nur Buchstaben erlaubt";
}
}
if (empty($_POST["nachname"])) {
$nachnameErr = "* Nachname wird benötigt";
} else {
$nachname = test_input($_POST["nachname"]);
if (!preg_match("/^[a-zA-Z]*$/",$nachname)) {
$nachnameErr = "* Nur Buchstaben erlaubt";
}
}
if (empty($_POST["anschrift"])) {
$anschriftErr = "* Anschrift wird benötigt";
} else {
$anschrift = test_input($_POST["anschrift"]);
}
if (empty($_POST["postleitzahl"])) {
$postleitzahlErr = "* Postleitzahl wird benötigt";
} else {
$postleitzahl = test_input($_POST["postleitzahl"]);
if (!preg_match("/^[0-9]*$/",$postleitzahl)) {
$postleitzahlErr = "* Nur Zahlen erlaubt";
}
}
if (empty($_POST["stadt"])) {
$stadtErr = "* Stadt / Ort wird benötigt";
} else {
$stadt = test_input($_POST["stadt"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$stadt)) {
$stadtErr = "* Nur Buchstaben und Leerzeichen erlaubt";
}
}
if (empty($_POST["email"])) {
$emailErr = "* E-Mail wird benötigt";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Falsches E-Mail Format";
}
}
if (empty($_POST["telefon"])) {
$telefon = "";
} else {
$telefon = test_input($_POST["telefon"]);
if (!preg_match("/^[0-9]*$/",$telefon)) {
$telefonErr = "* Nur Zahlen erlaubt";
}
}
if (empty($_POST["nachricht"])) {
$nachrichtErr = "Nachricht wird benötigt";
} else {
$nachricht = test_input($_POST["nachricht"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="kontaktformular-container">
<h2 class="h2-body3">Schreiben Sie uns eine E-Mail.<br></h2>
<h1 class="h1-body3">Kontaktformular</h1>
<form class="kontaktformular" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="anrede" name="anrede" placeholder="Anrede *" value="<?php echo $anrede ?>">
<span class="error"><?php echo $anredeErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="vorname" name="vorname" placeholder="Vorname *" value="<?php echo $vorname ?>">
<span class="error"><?php echo $vornameErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="nachname" name="nachname" placeholder="Nachname *" value="<?php echo $nachname ?>">
<span class="error"><?php echo $nachnameErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="anschrift" name="anschrift" placeholder="Anschrift *" value="<?php echo $anschrift ?>">
<span class="error"><?php echo $anschriftErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="postleitzahl" name="postleitzahl" placeholder="Postleitzahl *" value="<?php echo $postleitzahl ?>">
<span class="error"><?php echo $postleitzahlErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="stadt" name="stadt" placeholder="Stadt / Ort *" value="<?php echo $stadt ?>">
<span class="error"><?php echo $stadtErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="email" name="email" placeholder="E-Mail-Adresse *" value="<?php echo $email ?>">
<span class="error"><?php echo $emailErr;?></span>
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<input class="form-input" type="text" id="telefon" name="telefon" placeholder="Telefon" value="<?php echo $telefon ?>">
<br>
</div>
<div class="form-div">
<i class="fas fa-pen"></i>
<textarea class="form-input" id="nachricht" name="nachricht" rows="10" placeholder="Ihre Nachricht *"><?php echo $nachricht ?></textarea>
<span class="error"><?php echo $nachrichtErr;?></span>
<br>
</div>
<br>
<p class="p-kontakt">Mit einem * markierte Felder sind Pflichtfelder.</p>
<br>
<p class="p-kontakt">Mit dem Absenden des Formulares akzeptieren Sie die <span class="datenschutz"><a class="a-kontakt" href="#">Bestimmungen zum<br>Datenschutz</a></span> und willigen ein von uns per E-Mail/Telefon kontaktiert zu werden.</p>
<br>
<input class="form-submit" onclick="submitted()" type="submit" name="anfrage absenden" value="Anfrage absenden">
<script>
function submitted() {
alert("Nachricht erfolgreich abgeschickt!");
}
</script>```

I can't add a comment because I'm new and have no reputation
If this is the solution or not, please let me know.
At first give form id='contact'
then give submit input id='anfrage'
This code will check the entries if they are empty or not and will give an alert for each entry.. In the end it will give a warning that the command has been completed successfully and will send the forms.
js code:
<script>
if($('#contact').length){
$('#anfrage').click(function(){
var o = new Object();
var form = '#contact';
var anrede = $('#contact #anrede').val();
var vorname = $('#contact #vorname').val();
var nachname = $('#contact #nachname').val();
var anschrift = $('#contact #anschrift').val();
var postleitzahl = $('#contact #postleitzahl').val();
var stadt = $('#contact #stadt').val();
var email = $('#contact #email').val();
var telefon = $('#contact #telefon').val();
var nachricht = $('#contact #nachricht').val();
if(anrede == '')
{
alert("Nachricht erfolgreich abgeschickt1!");
return false;
}
else if(vorname == '')
{
alert("Nachricht erfolgreich abgeschickt2!");
return false;
}
else if(nachname == '')
{
alert("Nachricht erfolgreich abgeschickt3!");
return false;
}
else if(anschrift == '')
{
alert("Nachricht erfolgreich abgeschickt4!");
return false;
}
else if(postleitzahl == '')
{
alert("Nachricht erfolgreich abgeschickt5!");
return false;
}
else if(stadt == '')
{
alert("Nachricht erfolgreich abgeschickt!");
return false;
}
else if(email == '')
{
alert("Nachricht erfolgreich abgeschickt!");
return false;
}
else if(telefon == '')
{
alert("Nachricht erfolgreich abgeschickt!");
return false;
}
else if(nachricht == '')
{
alert("Nachricht erfolgreich abgeschickt!");
return false;
}
else{
alert("checked!");
return true;
}
});
}

Related

contactus form submit email dont send

I'm using a template website that is practically finished, but the form submit dont work.
Pls anyone can help me?
Here is my basic html:
<form action="#" class="form-contact" id="contactForm">
<div class="row">
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="p_name" placeholder="* Nome" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="email" class="form-control" id="p_email" placeholder="* Email" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="p_phone" placeholder="* Telefone">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="p_subject" placeholder="* Assunto">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group">
<textarea id="p_message" class="form-control" rows="6" placeholder="* Mensagem"></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div id="success"></div>
<button type="submit" class="btn btn-primary">ENVIAR</button>
</div>
</form>
here is my form-process.php:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// SUBJECT
if (empty($_POST["subject"])) {
$errorMSG .= "Subject is required ";
} else {
$subject = $_POST["subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "myemail#outlook.com";
$Subject = $subject;
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Here is my ajax/javascript for sending the email:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#p_name").val();
var email = $("#p_email").val();
var subject = $("#p_subject").val();
var message = $("#p_message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#success").removeClass().addClass(msgClasses).text(msg);
}
I was never able to send a form, I always get the error "Did you fill in the form properly?"

Php form validation with Ajax and jQuery

Everything works fine with php ,error messages function properly but if i try to do it with ajax it doesnt work. I used diffrent jQuery codes and plain javascript but i was only able to prevent the button's default reaction and stop the page from relaoding but i couldnt get the error-messages to show. i am aware that you have to get the error-messages display with javascript and run the php as backend script but i couldnt get it to work. i would appreciate any help.
here is my html form code:
<?php require('contact-script.php');
?>
<div class="container">
<form id="contact" action="index.php" method="POST">
<h3 id="test" >Contact Form</h3>
<h4>Contact us for custom quote</h4>
<span class="error" ><?php echo $errors['first']; ?></span>
<fieldset>
<input id="first" placeholder="First Name" name="first" type="text" value="<?php echo $first ?>" tabindex="1" >
</fieldset>
<span class="error" ><?php echo $errors['last']; ?></span>
<fieldset>
<input id="last" placeholder="Last Name" name="last" type="text" value="<?php echo $last ?>" tabindex="1" >
</fieldset>
<span class="error" ><?php echo $errors['mail']; ?></span>
<fieldset>
<input id="mail" placeholder="Your Email Address" name="mail" type="text" value="<?php echo $mail ?>" tabindex="2" >
</fieldset>
<span class="error" ><?php echo $errors['subject']; ?></span>
<fieldset>
<input id="subject" placeholder="Subject" name="subject" type="text" value="<?php echo $subject ?>" tabindex="2" >
</fieldset>
<fieldset>
<textarea id="message" placeholder="Type your message here...." name="message" type="text" value="<?php echo $message ?>" tabindex="5" ></textarea>
</fieldset>
<span class="error" ><?php echo $errors['message']; ?></span>
<fieldset>
<button id="formBtn" name="submit" type="submit" >Submit</button>
</fieldset>
</form>
</div>
here is my php code:
//defining Variables
$first = $last = $mail = $message = $subject = "";
$name_error = ""; $mail_error = ""; $message_error = "";
$errors = array( 'mail'=>'' , 'first'=> '' , 'last'=>'', 'subject'=>'', 'message'=>'');
if (isset($_POST['submit'])) {
$mail = htmlspecialchars($_POST['mail']);
$first = htmlspecialchars($_POST['first']);
$last = htmlspecialchars($_POST['last']);
$subject = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message']);
//check mail
if (empty($_POST['mail'])) {
$errors['mail'] = 'Bitte geben Sie eine E-mail Adresse an <br />';
}
else {
$mail = $_POST['mail'];
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$errors['mail'] = 'Bitte geben Sie eine gültige E-mail an';
}
}
//check first name
if(empty($_POST['first'])) {
$errors['first'] = 'Bitte geben Sie einen Namen an <br />';
}
else {
if(!preg_match('/^[a-zA-Z\s]+$/', $first)) {
$errors['first']= 'Name darf nur Buchstaben und Lehrzeichen enthalten ';
}
}
//check last name
if(empty($_POST['last'])) {
$errors['last'] = 'Bitte geben Sie einen Nachnamen an <br />';
}
else {
if(!preg_match('/^[a-zA-Z\s]+$/', $last)) {
$errors['last']= 'Name darf nur Buchstaben und Lehrzeichen enthalten';
}
}
if(empty($_POST['subject'])) {
$errors['subject'] = 'Bitte geben Sie ein Anliegen an <br />';
}
else {
if(!preg_match('/^[a-zA-Z\s]+$/', $subject)) {
$errors['subject']= 'Anliegen darf nur Buchstaben und Lehrzeichen enthalten ';
}
}
//check for message
if(empty($_POST['message'])) {
$errors['message']= 'Bitte schreiben Sie eine Nachricht <br />';
}
if (array_filter($errors)) {
}else {
$mailTo = "info#blanc-code.de";
$headers = "From: ".$mail;
$text = "Sie haben eine e-mail von ".$first." ".$last." erhalten.\n\n".$message;
mail($mailTo, $subject, $text, $headers);
}
i tryed this code for example:
function submitForm() {
getBtn = document.querySelector('#formBtn');
getBtn.disabled = true;
let formdata = new FormData();
formdata.append("mail", document.querySelector('mail').value);
formdata.append("first", document.querySelector('first').value);
formdata.append("last", document.querySelector('last').value);
formdata.append("subject", document.querySelector('subject').value);
let http = new XMLHttpRequest();
http.open("POST", "contact-script.php");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
if(http.responseText == "success") {
}else {
getBtn.disabled = false;
}
}
}
http.send(formdata);
or this:
$(document).ready(function(){
$("form").submit(function(event) {
event.preventDefault();
var first = $("#first").val();
var last = $("#last").val();
var mail = $("#mail").val();
var subject = $("#subject").val();
var message = $("#message").val();
$(".error").load("contact-script.php", {
first: first,
last: last,
mail: mail,
subject: subject,
message: message
});
});
});
there was more but this should give you a clue

Errors after form submission

A have a working form which being validated both in JavaScript/PHP .After submitting the form I got my success message , however if I filling same form after submission its shows me strange symbols errors when the field filled wrong,see attached 1: https://i.stack.imgur.com/uj73P.jpg
I am not sure whether its coming from PHP or Javascript.Please advise.
My form:
<section class="inspiration" id="three">
<div class="overlay">
<div class="container">
<div class="row">
<article class="col-md-12 text-center">
<div class="intermediate-container">
<div class="heading wow fadeInUp">
<h2>יש לכם שאלה? צרו איתי קשר</h2>
</div>
<div class="row">
<div class="col-md-3 col-sm-3"></div>
<div class="col-md-6 center-block col-sm-6 ">
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 wow fadeInUp">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
<span class='error-message' id='subject-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
<span class='error-message' id='message-error'></span>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button class="btn btn-custom-outline wow fadeInUp" id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<span class="success">הודעתך נשלחה בהצלחה!</span>
</form>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
</section>
My Javasript:
function sendForm() {
$('[id*="-error"]').text(''); // default hide all error messages
event.preventDefault(); // prevent form submission and therefore page reload
$.ajax({
type: 'POST',
url: './send.php',
data: $("#mc-form").serialize(),
success: function(data) {
if(data.hasOwnProperty('error')) {
Object.keys(data['error']).forEach(function(key) {
producePrompt(data['error'][key], key+'-error', 'red');
});
}
if(data.hasOwnProperty('mail_error')) {
alert('Could not send mail');
}
if(data.hasOwnProperty('success')) {
alert(data['success']);
$('.success').show();
$("#name").val('');
$("#phone").val('');
$("#email").val('');
$("#subject").val('');
$("#message").val('');
}
}
});
}
My PHP:
<?php
$error_msg = array();
$success_msg = array();
$data = '';
// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error_msg['name'] = "שדה זה הינו חובה";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$error_msg['name'] = "אותיות ורווחים בלבד";
}
}
if (empty($_POST["email"])) {
$error_msg['email'] = "שדה זה הינו חובה";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg['email'] = "דואר אלקטרוני לא תקין";
}
}
if (empty($_POST["phone"])) {
$error_msg['phone'] = "שדה זה הינו חובה";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$error_msg['phone'] = "טלפון לא תקין";
}
}
if (empty($_POST["subject"])) {
$error_msg['subject'] = "שדה זה הינו חובה";
}
if (empty($_POST["message"])) {
$error_msg['message'] = "שדה זה בינו חובה";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if (empty($error_msg)){ // note that $lastname_error does not exists
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'XXXXXXXb#gmail.com';
$subjectm = 'Contact Form Submit';
$feedback = "שם: $name. טלפון: $phone. דואר אלקטרוני :$email. הודעה : $message";
if (mail($to, $subjectm, $feedback)){
$success_msg = "הודעתך נשלחה בהצלחה,תודה !";
$name = $email = $phone = $message = $subject = '';
} else {
$mail_error_msg = 'לא ניתן לשלוח אימייל';
}
}
// set output data accordingly
if(!empty($success_msg)) {
$data = array('success'=>$success_msg);
} else if(!empty($error_msg)) {
$data = array('error'=>$error_msg);
} else if(!empty($mail_error_msg)) {
$data = array('mail_error'=>$mail_error_msg);
}
// output json that you can parse with jquery
header('Content-Type: application/json');
echo json_encode($data);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
A have a working form which being validated both in JavaScript/PHP .After submitting the form I got my success message , however if I filling same form after submission its shows me strange symbols errors when the field filled wrong,see attached enter image description here
I am not sure whether its coming from PHP or Javascript.Please advise.

How to run PHP Mail Form Script only when someone Successfully Submit the Form?

I have the following code for my HTML Form with PHP on the same page. Actually, the problem is that when anybody opens the website it automatically runs the PHP Mail() script and send me an empty mail.
I want it to work only when somebody successfully submits the form. Please help.
<!--HTML FORM--><form method="post" name="contactform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateform()">
<input type="text" name="fullname" class="fullname" placeholder="Full Name*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Full Name*';}">
<input type="text" name="email" class="email" placeholder="Email Address*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Email Address*';}">
<textarea placeholder="Your Message*:" name="message" class="message"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Your Message*';}"></textarea>
<input type="submit" name="submit" value="Submit" />
</form><!--/HTML FORM> <!--Contact Form PHP-->
<?php
// define variables and set to empty values
$fullname = $email = $message = "";
$subject="Message from Website Visitor:".test_input($_POST["fullname"]);
$to="camadhusudanmishra#gmail.com";
$headers = "From:".test_input($_POST["email"]);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$email = test_input($_POST["email"]);
$message = test_input($_POST["message"]);}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
$message = str_replace("\n.", "\n..", $message);
mail($to,$subject,$message,$headers);
?>
<!--/Contact Form PHP-->
JS Code for Validation:
function formValidation() {
var fullname = document.contactform.fullname;
var email = document.contactform.email;
var message = document.contactform.message;
if(validateName(fullname))
{
if(validateEmail(email))
{
if(validateMessage(message))
{
}
}
}
return false;
}
function validateName(fullname)
{
var letters = /^[A-Za-z]+$/;
if(fullname.value.match(letters) && fullname.value.length >= 3 && fullname.value.length <= 30)
{
return true;
}
else {
alert('Please enter a valid name');
return false;
}
}
function validateEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
return false;
}
}
function validateMessage(message)
{
if(message.value.length >=5 && message.value.length <=300)
{
alert('Form Succesfully Submitted');
window.location.reload();
return true;
}
else
{
alert("Please type a valid message.");
return false;
}
}
You can use following code.
<?php
if(isset($_POST['submit']))
{
// Add here function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
// define variables and set to empty values
$fullname = $email = $message = "";
$subject="Message from Website Visitor:".test_input($_POST["fullname"]);
$to="camadhusudanmishra#gmail.com";
$headers = "From:".test_input($_POST["email"]);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$email = test_input($_POST["email"]);
$message = test_input($_POST["message"]);}
$message = str_replace("\n.", "\n..", $message);
mail($to,$subject,$message,$headers);
}
?>
<!--/Contact Form PHP-->
<!--HTML FORM-->
<form method="post" name="contactform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateform()">
<input type="text" name="fullname" class="fullname" placeholder="Full Name*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Full Name*';}">
<input type="text" name="email" class="email" placeholder="Email Address*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Email Address*';}">
<textarea placeholder="Your Message*:" name="message" class="message"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Your Message*';}"></textarea>
<input type="submit" name="submit" value="Submit" />
</form><!--/HTML FORM> <!--Contact Form PHP-->

Javascript Submit is not Sending SUBMIT POST to php file

I'm trying to create a form without a real submit button, but with a styled a href and javascript, but I'm unable to POST the form itself.
If I do var_dump($_POST); then I get an array of 4 items (3 inputs and 1 text area). The form itself is not there, so if (isset($_POST['submit'])) valuates to false. I also tried if (isset($_POST['ContactForm'])) but its not working either
form code:
<form name='ContactForm' id='ContactForm' action='verzendvraag.php' method='POST'>
<input type="text" class="col-md-6 col-xs-12 name" id="naam" name='naam' placeholder='Naam *' value="<? echo $_SESSION['naam']; ?>" required/>
<input type="email" class="col-md-6 col-xs-12 Email" id="email" name='email' placeholder='Email *' value="<? echo $_SESSION['email']; ?>" required/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' id='Subject' placeholder='Onderwerp'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" id="vraag" name="vraag" placeholder='Bericht *' style="left: 0px; top: 0px" required><? echo $_SESSION['vraag']; ?></textarea>
<div class="cBtn col-xs-12">
<ul>
<li class="clear"><i class="fa fa-times"></i>ledig vakjes</li>
<li class="send"><i class="fa fa-share"></i>Verstuur bericht</li>
</ul>
</div>
</form>
javascript:
function submitForm(e) {
if (validateForm())
{
document.getElementById("ContactForm").submit();
}
e.preventDefault();
}
php:
session_start();
//Validatie serverside => bescherming inbouwen voor als iemand zijn javascript uitschakelt. Javascript echter wel nodig om de server en netwerktraffic te ontlasten.
if (isset($_POST['submit']))
{
$naam = $_POST['naam'];
//$bedrijf = $_POST['bedrijf'];
$subject = $_POST['Subject'];
$email = $_POST['email'];
$vraag = $_POST['vraag'];
//In session steken zodat we bij een eventuele terugkeer naar de form de reeds ingevulde gegevens kunnen terug zetten.
$_SESSION['naam'] = $_POST['naam'];
//$_SESSION['bedrijf'] = $_POST['bedrijf'];
$_SESSION['Subject'] = $_POST['Subject'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['vraag'] = $_POST['vraag'];
$isOK = true;
$error = '0';
$atpos = strrpos($email,"#");
$dotpos = strrpos($email,".");
if(is_null($naam) || $naam == '')
{
$isOK = false;
echo('NAAM NIET OK ');
$error .= ',1';
}
if(is_null($email) || $email == '')
{
$isOK = false;
echo('EMAIL NIET OK '.$email);
$error .= ',2';
}
else
{
//checken geldig e-mailadres
if ($atpos === false || $dotpos === false || $dotpos < $atpos+2 || $dotpos+2 >= strlen($email)) //=== moet => http://php.net/manual/en/function.strpos.php en http://www.php.net/manual/en/language.operators.comparison.php
{
$isOK = false;
echo("Ongeldig e-mailadres ");
$error .= ',3';
}
}
if(is_null($vraag) || $vraag== '')
{
$isOK = false;
echo('VRAAG NIET OK ');
$error .= ',4';
}
}
if(!($isOK))
{
echo("<script>location.href='index.php?error=$error'</script>");
exit;
}
else
{
.....
}
I checked Javascript Submit is not Sending POST to php file and he says his code works, so I don't understand mine won't.
Since you don't have any button or input named submit so it does not exist in $_POST variable. I think you should check what you have in the form so use .
if (isset($_POST['naam'])){
// your code
}
Instead of
if (isset($_POST['submit'])){
// your code
}
you should also change this if (isset($_POST['submit'])) to if (isset($_POST['naam']))
Use ajax request like this
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "receive.php",
data: $("#ContactForm").serialize(),
success: function(response) {
if (response) {
alert('Successfully posted.');
}
else {
alert('Successfully not posted.');
}
}
});
Just use ajax for submiting form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form name='ContactForm' id='ContactForm' action='verzendvraag.php' method='POST'>
<input type="text" class="col-md-6 col-xs-12 name" id="naam" name='naam' placeholder='Naam *' value="<? echo $_SESSION['naam']; ?>" required/>
<input type="email" class="col-md-6 col-xs-12 Email" id="email" name='email' placeholder='Email *' value="<? echo $_SESSION['email']; ?>" required/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' id='Subject' placeholder='Onderwerp'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" id="vraag" name="vraag" placeholder='Bericht *' style="left: 0px; top: 0px" required><? echo $_SESSION['vraag']; ?></textarea>
<div class="cBtn col-xs-12">
<ul>
<li class="clear"><i class="fa fa-times"></i>ledig vakjes</li>
<li class="send"><i class="fa fa-share"></i>Verstuur bericht</li>
</ul>
</div>
</form>
<script>
function submitForm(e) {
alert('working');
var naam = $("#naam").val();
var email = $("#email").val();
var Subject = $("#Subject").val();
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "verzendvraag.php",
data: {"naam":naam,"email":email,"Subject":Subject},
success: function(response) {
if (response) {
alert(response);
alert('Successfully posted.');
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
</body>
</html>
verzendvraag.php
<?php session_start();
//Validatie serverside => bescherming inbouwen voor als iemand zijn javascript uitschakelt. Javascript echter wel nodig om de server en netwerktraffic te ontlasten.
if (isset($_POST))
{
$naam = $_POST['naam'];
//$bedrijf = $_POST['bedrijf'];
$subject = $_POST['Subject'];
$email = $_POST['email'];
//$vraag = $_POST['vraag'];
//In session steken zodat we bij een eventuele terugkeer naar de form de reeds ingevulde gegevens kunnen terug zetten.
$_SESSION['naam'] = $_POST['naam'];
//$_SESSION['bedrijf'] = $_POST['bedrijf'];
$_SESSION['Subject'] = $_POST['Subject'];
$_SESSION['email'] = $_POST['email'];
//$_SESSION['vraag'] = $_POST['vraag'];
$isOK = true;
$error = '0';
$atpos = strrpos($email,"#");
$dotpos = strrpos($email,".");
if(is_null($naam) || $naam == '')
{
$isOK = false;
echo('NAAM NIET OK ');
$error .= ',1';
}
if(is_null($email) || $email == '')
{
$isOK = false;
echo('EMAIL NIET OK '.$email);
$error .= ',2';
}
else
{
//checken geldig e-mailadres
if ($atpos === false || $dotpos === false || $dotpos < $atpos+2 || $dotpos+2 >= strlen($email)) //=== moet => http://php.net/manual/en/function.strpos.php en http://www.php.net/manual/en/language.operators.comparison.php
{
$isOK = false;
echo("Ongeldig e-mailadres ");
$error .= ',3';
}
}
/* if(is_null($vraag) || $vraag== '')
{
$isOK = false;
echo('VRAAG NIET OK ');
$error .= ',4';
}*/
}
if(!($isOK))
{
echo("<script>location.href='index.php?error=$error'</script>");
exit;
}
else
{
echo "SUCCESS";
}
?>

Categories

Resources