Php form validation with Ajax and jQuery - javascript

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

Related

have multiple alert boxes in a contact form

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

PHP,jQuery,HTML form with ajax is not working

I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax
From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH

PHP js alert message when form was sent ok

I'm trying to show an alert box saying the message was sent OK, but for some reason I don't see the message. I do get the one saying to check the captcha. What am I doing wrong? All the code is in my index.php file. All the if's at the beginning where attempts to avoid resubmitting the form.
Also, how can I style the alert box? I've tried using Bootbox. Js but without luck.
<?php
$message['message'] = "";
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit'])) {
if (isset($_POST['g-recaptcha-response']) && ($_POST["g-recaptcha-response"] != '')) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--secretKey--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
$to = "info#someone.com.ar";
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['asunto'];
$subject2 = 'Copia de: '.$_POST['asunto'];
$message = $name . " " . "escribio lo siguiente:" . "\n\n" . $_POST['message'];
$message2 = "Le enviamos una copia de su mensaje " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $email;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($email,$subject2,$message2,$headers2);
//echo "La consulta se envió correctamente. Gracias! " . $name . ", lo contactaremos a la brevedad.";
echo '<script type="text/javascript">alert("El mensaje se envió correctamente. Muchas gracias!");</script>';
//Back to the web
header('Location: index.php');
}
} else {
echo '<script type="text/javascript">alert("Por favor tildar el captcha!");</script>';
//$_SESSION['form'] = filter_input_array(INPUT_POST);
}
}
?>
Form:
<div class="col-md-4 to-animate">
<h3 class="section-title">Escribinos</h3>
<form class="contact-form" action="" method="post" id="form">
<div class="form-group">
<label for="name" class="sr-only">Nombre</label>
<input type="name" class="form-control" name="name" id="name" placeholder="Nombre y Apellido" required title="Por favor ingrese su nombre y apellido" value="<?php echo (isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''); ?>" />
</div>
<div class="form-group">
<label for="asunto" class="sr-only">Asunto</label>
<input type="asunto" class="form-control" name="asunto" id="asunto" placeholder="Asunto" required title="Por favor ingrese el asunto" value="<?php echo (isset($_POST['asunto']) ? htmlspecialchars($_POST['asunto']) : ''); ?>" />
</div>
<div class="form-group">
<label for="email" class="sr-only">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required title="Por favor ingrese un mail" value="<?php echo (isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''); ?>" />
</div>
<div class="form-group">
<label for="message" class="sr-only">Mensaje</label>
<textarea class="form-control" id="message" name="message" rows="7" placeholder="Mensaje" required title="Por favor ingrese un mensaje mayor a 10 caractéres."><?php echo (isset($_POST['message']) ? htmlspecialchars($_POST['message']) : ''); ?></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" id="btn-submit" class="btn btn-send-message btn-md" value="ENVIAR">
</div>
<div class="g-recaptcha" data-sitekey="--Sitekey--" data-callback="callback"></div>
</form>
</div>
Don't know about the rest of the code or if this is the problem - but you shouldn't use "AND" in the 'if' statetement - it should be :
if (isset($data->success) && $data->success==true) {...
After removing the
header('Location: index.php');
The message appears. Don't ask me why.

Contact Form opening PHP file instead of showing Popup

I have a contact form on my website that with the current code sends an email to the sender and the receiver, and all works fine. However, once completing the form, the page opens email.php instead of showing a popup that I hoped it would. I have no idea how to fix as I'm not used to writing for php and JS. Below is my code.
<form method="post" action="email.php" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_self" novalidate>
<input type="text" value="" name="full_name" class="fullname" id="mce-name" placeholder="full name" required>
<input type="text" value="" name="phone_num" class="phonenum" id="mce-phone" placeholder="phone number" required>
<br>
<input type="email" value="" name="email" class="email" id="mce-EMAIL" placeholder="email address" required>
<div style="position: absolute; left: -5000px;"><input type="text" name="b_cdb7b577e41181934ed6a6a44_e65110b38d" value=""></div>
<div class="clear"><input type="submit" value="Submit" name="submit" id="mc-embedded-subscribe" class="button"></div>
</form>
<?php
if(isset($_POST['submit'])){
$to = "email#help.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$full_name = $_POST['full_name'];
$phone_num = $_POST['phone_num'];
$subject = "Title";
$subject2 = "Copy of your form submission";
$message = "Message";
$message2 = "Message2";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
if ($_POST['submit']) {
if ($name != '' && $email != '' && $subject != '' && $message != '') {
}
} else {
echo '<script>function displayPopup()
{
alert("Form submitted!");
}<script>';
}
}
?>
because you only declare the popup function, you did not run displayPopup()
try to change to
if ($_POST['submit']) {
if ($name != '' && $email != '' && $subject != '' && $message != '') {
} else {
echo '<script>function displayPopup(){alert("Form submitted!");}';
echo 'displayPopup();</script>
';
}
}

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