Multiple fields in PHP contact form - javascript

I'm creating a form which dynamically adds additional fields as necessary.
How I can register those dynamic fields in my contact forms PHP?
Also, why does the remove button result in an error with Bootstrap core jQuery?
The form:
<form action="%3C?php%20bloginfo('template_url');%20?%3E/contactengine.php" class="form-horizontal cd-form" method="post">
<div class="col-md-12">
<h3>Ditt navn og adresse</h3>
</div>
<div class="col-md-12 medlem-form">
<div class="form-group">
<label class="col-sm-12 control-label" for="inputEmail3">Fornavn*</label>
<div class="col-sm-12">
<input class="form-control" id="Fornavn" name="Fornavn" placeholder="Fornavn" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputPassword3">Etternavn*</label>
<div class="col-sm-12">
<input class="form-control" id="Etternavn" name="Etternavn" placeholder="Etternavn" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputEmail3">Fødselsdato*</label>
<div class="col-sm-12">
<input class="form-control" id="Fodselsdato" name="Fodselsdato" placeholder="Fødselsdato" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputPassword3">Adresse*</label>
<div class="col-sm-12">
<input class="form-control" id="Adresse" name="Adresse" placeholder="Adresse" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputPassword3">Post nummer*</label>
<div class="col-sm-12">
<input class="form-control" id="Postnummer" name="Postnummer" placeholder="Post nummer" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputPassword3">Post sted*</label>
<div class="col-sm-12">
<input class="form-control" id="Poststed" name="Poststed" placeholder="Post sted" type="text">
</div>
</div>
</div><!-- end form -->
<div class="col-md-12">
<h3>e-post og telefon nummer</h3>
</div>
<div class="col-md-12 medlem-form">
<div class="form-group">
<label class="col-sm-12 control-label" for="inputEmail3">Navn foresatt</label>
<div class="col-sm-12">
<input class="form-control" id="Navnforesatt" name="Navnforesatt" placeholder="Nanv Foresatt" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputPassword3">E-post *</label>
<div class="col-sm-12">
<input class="form-control" id="Epost" name="Epost" placeholder="E-Post" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="inputEmail3">Mobil nummer</label>
<div class="col-sm-12">
<input class="form-control" id="Mobilnummer" name="Mobilnummer" placeholder="Mobil nummer" type="text">
</div>
</div>
</div><!-- end form -->
<div class="col-md-12">
<h3>Velg en medlemskapstype</h3>
</div>
<div class="col-md-12 medlem-form">
<div class="radio">
<label class="radio-inline"><input id="inlineRadio1" name="inlineRadioOptions" type="radio" value="option1"> Støttemedlem (kr 300,-)</label> <label class="radio-inline"><input id="inlineRadio2" name="inlineRadioOptions" type="radio" value="option2"> Enkelt medlem (kr 1.500,-)</label> <label class="radio-inline"><input name="multi_note" onclick="showMe('div1', this)" type="checkbox" value="1"> Familemedlem (kr 2.500,-)</label>
</div><!-- third level ends here -->
<!-- Hidden form starts here -->
<div id="div1" style="display:none">
<hr>
<div class="clonedInput" id="input1" style="margin-bottom:4px;">
<div class="form-group">
<label class="col-sm-12 col-xs-12 control-label" for="inputEmail3">Fornavn*</label>
<div class="col-sm-12">
<input class="form-control" id="inputEmail3" placeholder="Email" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 col-xs-12 control-label" for="inputPassword3">Etternavn*</label>
<div class="col-sm-12">
<input class="form-control" id="inputPassword3" placeholder="Password" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-12 col-xs-12 control-label" for="inputEmail3">Fødselsdato*</label>
<div class="col-sm-12">
<input class="form-control" id="inputEmail3" placeholder="Email" type="text">
</div>
</div>
<hr>
</div>
<div id="send-BTN">
<input id="btnAdd" type="button" value="+ Legg en til"> <!--<input type="button" id="btnDel" value="remove name" />-->
<input id="fieldnumber" type="hidden" value="1">
</div>
</div><!-- end Hidden form -->
</div><!-- end form -->
<div class="col-md-12 bottom-hack">
<input type="submit" value="Send Message">
</div>
</form>
and here's the PHP
<?php
$EmailFrom = "nett#martin.no";
$EmailTo = "martin#martin.no";
$Subject = "Ny Medlem";
$Fornavn = Trim(stripslashes($_POST['Fornavn']));
$Etternavn = Trim(stripslashes($_POST['Etternavn']));
$Fodselsdato = Trim(stripslashes($_POST['Fodselsdato']));
$Adresse = Trim(stripslashes($_POST['Adresse']));
$Postnummer = Trim(stripslashes($_POST['Post nummer']));
$Poststed = Trim(stripslashes($_POST['Post sted']));
$Navnforesatt = Trim(stripslashes($_POST['Navn Foresatt']));
$Epost = Trim(stripslashes($_POST['E-post']));
$Mobilnummer = Trim(stripslashes($_POST['Mobil nummer']));
$Medlemskaptype = Trim(stripslashes($_POST['Medlemskapstype']));
$FamilieMedlemFornavn = Trim(stripslashes($_POST['Familie Medlem Fornavn']));
$FamilieMedlemEtternavn = Trim(stripslashes($_POST['Familie Medlem Etternavn']));
$FamilieMedlemFodselsdato = Trim(stripslashes($_POST['Familie Medlem Fødselsdato']));
// validation
$validationOK = true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Fornavn: ";
$Body .= $Fornavn;
$Body .= "\n";
$Body .= "Etternavn: ";
$Body .= $Etternavn;
$Body .= "\n";
$Body .= "Fodselsdato: ";
$Body .= $Fodselsdato;
$Body .= "\n";
$Body .= "Adresse: ";
$Body .= $Adresse;
$Body .= "\n";
$Body .= "Post nummer: ";
$Body .= $Postnummer;
$Body .= "\n";
$Body .= "Post sted: ";
$Body .= $Poststed;
$Body .= "\n";
$Body .= "Navn Foresatt: ";
$Body .= $Navnforesatt;
$Body .= "\n";
$Body .= "E-post: ";
$Body .= $Epost;
$Body .= "\n";
$Body .= "Mobil nummer: ";
$Body .= $Mobilnummer;
$Body .= "\n";
$Body .= "Medlemskapstype: ";
$Body .= $Medlemskaptype;
$Body .= "\n";
$Body .= "Familie Medlem Fornavn: ";
$Body .= $FamilieMedlemFornavn;
$Body .= "\n";
$Body .= "Familie Medlem Etternavn: ";
$Body .= $FamilieMedlemEtternavn;
$Body .= "\n";
$Body .= "Familie Medlem Fødselsdato: ";
$Body .= $FamilieMedlemFodselsdato;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
} else {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
The javascript:
<script type="text/javascript">
$(document).ready(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled', '');
$('#fieldnumber').val(num + 1);
// business rule: you can only add 5 names
if (newNum == -1)
$('#btnAdd').attr('disabled', 'disabled');
});
$('#btnDel').click(function () {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled', '');
//Take one from value of hidden field
$('#fieldnumber').val(num - 1);
// if only one element remains, disable the "remove" button
if (num - 1 == 1)
$('#btnDel').attr('disabled', 'disabled');
});
$('#btnDel').attr('disabled', 'disabled');
});
</script>

You'll have the new fields in your $_POST variable and you can access each of them with $_POST['child4'] (don't make your input names digits only as you did). You may now come up with a loop like so
foreach($_POST as $key => $value) {
if (strpos($key, 'child') === 0) {
// value starts with book_
}
}

you can do it in jquery ajax ,the idea is this:
in jquery initialize a variable to 0.
after each addition of a Textarea increment variable .
in the end you have the number of fields just browse the textarea and insert the data into the database via ajax Requette

Related

posting data from javascript to php is not working

I'm writing a code that sends email from php with an attachment. And here is my code.
my main.php file
<form action="javascript:postData()" id="form">
<fieldset>
<!-- Form Name -->
<legend>Application</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Full Name">Full Name</label>
<div class="col-md-4">
<input id="FullName" name="FullName" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Email">Email</label>
<div class="col-md-4">
<input id="Email" name="Email" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="roleFor">Role Applying for</label>
<div class="col-md-4">
<input id="roleFor" name="roleFor" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobId">Job ID</label>
<div class="col-md-4">
<input id="jobId" name="jobId" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="uploadResume">Upload Resume</label>
<div class="col-md-4">
<input type="file" name="file" class="form-control">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="experience">Experience</label>
<div class="col-md-4">
<textarea class="form-control" id="experience" name="experience"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" type="submit" name="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
and my js is
function postData() {
const form = document.getElementById('form');
const data = new FormData();
data.append('FullName', form.FullName.value);
data.append('Email', form.Email.value);
data.append('roleFor', form.roleFor.value);
data.append('jobId', form.jobId.value);
data.append('experience', form.experience.value);
fetch('sendEmail.php', {method: 'POST', body: data}).then(response => {
if (!response.ok){
throw new Error('Network response was not ok.');
} else
{
console.log(response);
alert('New job posted');
document.getElementById("form").reset();
}
}).catch(err => console.log(err));
}
and my sendEmail.php is
<?php
$fName = $_POST['FullName'];
$emailAddr = $_POST['Email'];
$roleFor = $_POST['roleFor'];
$jobId = $_POST['jobId'];
$exp = $_POST['experience'];
if (!empty($fName) && !empty($emailAddr))
{
$statusMsg = '';
if (isset($_FILES["file"]["name"]))
{
$emailAddr = $_POST['Email'];
$fromemail = 'admin#admin.com';
$subject = 'Teesst Syubect';
$email_message = "<table><tr><td>Name: </td><td>" . $fName . "</td></tr> </table>";
$email_message .= "Please find CV in the attachment";
$semi_rand = md5(uniqid(time()));
$headers = "From: " . $fromemail;
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
if ($_FILES["file"]["name"] != "")
{
$strFilesName = $_FILES["file"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n";
$email_message .= "--{$mime_boundary}\n" . "Content-Type: application/octet-stream;\n" . " name=\"{$strFilesName}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $strContent .= "\n\n" . "--{$mime_boundary}--\n";
}
$toemail = "myEmail#gmail.com";
if (mail($toemail, $subject, $email_message, $headers))
{
$statusMsg = "Email send successfully with attachment";
header("Location:careers.php");
}
else
{
$statusMsg = "Not sent";
}
}
}
else
{
echo "Enter both Title and Desription";
die();
}
?>
Now the issues are,
when I do <form action="sendEmail.php" id="form" method="post">, it is sending the email as expected, but when I try to post it through javascript (as shown in my code), it isn't sending an email, but to my surprise, the response status is 200 OK.
Please let me know where I'm going wrong.
Thanks

Contact us form isn't sending all populated fields to email, only a few? PHP AJAX JS

So I've gone through a thread that helped me build this contact us form, but it talked about validating and making the fields required. There are two fields I have in my form that doesn't need to be required $organization and $budget, I can't seem to get the information in there to send with the email. The email shows those fields as blank but the other fields are populated.
I have practically zero experience in PHP outside of this form.
Expected output:
Name: xxx
Email: xxx#xxx.com
Organization: xxx
Budget: xxx
Message: xxx
What I actually receive in my email:
Name: xxx
Email: xxx#xxx.com
Organization:
Budget:
Message: xxx
Code:
<?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"];
}
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "example#mydomain.com";
$Subject = "Received msg from WIP contact form";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Organization: ";
$Body .= $organization;
$Body .= "\n";
$Body .= "Budget: ";
$Body .= $budget;
$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 "Sorry, something went wrong.";
} else {
echo $errorMSG;
}
}
?>
HTML:
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" placeholder="$50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JavaScript:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Please fill in the required fields.");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var organization = $("#organization").val();
var budget = $("#budget").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message + "&organization=" + organization + "&budget" + budget,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "We'll be in touch with you soon!")
}
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";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
EDIT
Thanks to Uxmal for suggesting the name="xxxx" in the input field. He said that by doing this, the $_POST is looking for inputs with name. Which made me realise I must be doing something else wrong. Turns out my ajax was poorly written and I was also missing the <form action aswell. Below is the corrected version of the form and ajax code.
<form action="form-process.php" method="POST" role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization name">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" name="budget" placeholder="50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" name="message" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JS:
function submitForm(){
$.ajax({
type: "POST",
url: "php/form-process.php",
data: $('#contactForm').serialize(),
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}
You PHP code at line
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
looks for inputs with name: organization and budget, no to for id organization and budget.
At you html is
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" placeholder="$50000">
without a tag: name="organization" and tag: name="budget".
So put those tags like
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" name="budget" placeholder="$50000">
and then your PHP code will get the data.

How do I creat a jquery form validator

I am trying to create a dynamic website using php. The site is uploaded to a free domain this is my first real world project so I want to put in as best as I can. I created a modal, in it there is a form and I want this from to validate and without refreshing the page. but I don't know why my mail() is not working please can someone tell me what I am doing wrong.
This is my fixed form inside the modal:
<div class="modal fade" id="myModal" tabindex="-1" role="form" aria-labelledby="#modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title " id="modalLabel">Send
<?php echo
$brandName; ?> a message</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="thumbnail">
<form action="contact_process.php" method="POST" role="form" autocomplete="off" class="form-container">
<small>
<i class="text-center
text-danger">all fields are required</i>
</small>
<div class="form-group has-danger">
<label class="sr-only" for="name">Name
</label>
<input type="text" name="name" placeholder="Your Name" class="form-control" id="mail-name" tabindex="1">
</div>
<div class="form-group has-danger">
<label class="sr-only" for="email">Email
</label>
<input type="email" name="email" placeholder="Your E-mail" class="form-control" id="mail-email" tabindex="2">
</div>
<div class="form-group has-danger">
<label for="tel" class="sr-only">Tell
no.
</label>
<input type="text" name="phone" placeholder="Your Phone Number" class="form-control" id="mail-
phone" tabindex="3">
</div>
<div class="form-group has-danger">
<label for="message" class="sr-only">
</label>
<textarea class="form-control
form-textarea" placeholder="Message" rows="5" spellcheck="true" name="message" id="mail-message" tabindex="4"></textarea>
</div>
<input type="button" class="btn
btn-danger" data-dismiss="modal" aria-label="Close" value="Cancel" tabindex="5">
<input id="mail-submit" type="submit" class="btn btn-primary" value="Send Message" name="submit" data- submit="...Sending" tabindex="6">
<p class="form-msg"></p>
</form>
</div>
<!--END thumbnail-->
</div>
<!--END col-->
</div>
<!--END row-->
</div>
<!--modal-body-->
</div>
<!--modal-content-->
</div>
<!--modal-dialog-->
</div>
<!---modal-->
This is the php form validation in my includes folder:
<pre>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorPhone = false;
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo "<span class='err'>Fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='err'>Invalid email please make sure you enter a
valid email address!</span>";
$errorEmail = true;
}
elseif (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?
\d{3}[\s-]?\d{4}$/i",$phone)) {
echo "<span class='err'>Please enter only a valid phone number!
</span>";
$errorPhone = true;
}
else{
// add resipeants
$to = "danjumashiwaju#gmail.com";
// create subject
$subject = "$name sent you a message from www.djshumzy.com";
// construct a message
$msg = "Name: $name\r\n";
$msg .= "Email: $email\r\n";
$msg .= "Tell: $phone\r\n";
$msg .= "Message: \r\n$message";
$msg = wordwrap($meg, 70);
//set mail header
$headers = "MINE-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=1so-8859-1\r\n";
$headers .= "From: $name <$email>\r\n";
$headers .= "X-priority: 1\r\n";
$headers .= "X-MSMail-priority: High1\r\n\r\n";
mail( $to, $subject, $msg, $headers);
} if (mail === 1) {
echo "<span class='suc'>Thank You!...Your Message has been Sent !
</span>";
}
}
?>
<script>
$("#mail-name, #mail-email, #mail-phone,
#mail-message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPhone = "<?php echo $errorPhone; ?>";
if (errorEmpty == true) {
$("#mail-name, #mail-email, #mail-phone,
#mail-message").addClass("input-error");
}
if (errorEmail == true) {
$("#mail-email").addClass("input-error");
}
if (errorPhone == true) {
$("#mail-phone").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false && errorPhone == false) {
$("#mail-name, #mail-email, #mail-phone, #mail-message").val("");
}
</script>
</pre>
Here is my jquery validation(.js)
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-msg").load("includes/contact_process.php", {
name: name,
email: email,
phone: phone,
message: message,
submit: submit
});
});
});// END FORM VALIDATING
Please what do I have to do to make this from submit to emails and validate at the same time.
Thus the form validates but it does not send the email and just gives an error message instead.
Use https://jqueryvalidation.org/
$( "#myform" ).validate({
rules: {
field: {
required: true
},
email: {
required: true,
email: true
}
},
messages: {
field: "Please Enter Your Name",
email: "Please Enter Your Email Address"
}
});
<link href="https://jqueryvalidation.org/files/demo/site-demos.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
<label for="field">Enter Name : </label>
<input type="text" class="left" id="field" name="field">
<br/>
<label for="email">Email Address: </label>
<input type="text" id="email" name="email">
<br/>
<input type="submit" value="Validate!">
</form>
This jQuery plugin makes simple clientside form validation easy.

Ajax sending data from other php file contact form

I am new to AJAX, i came from a code in internet about sending Ajax to php file. The problem is i dont know if the data is submitted or what happen. The alert box doesn't pop up if it was submited
success: function () {
alert('form was submitted');
}
Here is the full form from html :
<form class="form-horizontal">
<div class="form-group">
<label for="contact-name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name" name="name" placeholder="FULL Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-sm-2 control-label">Message</label>
<div class="col-sm-4">
<textarea name="message" class="form-control" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-primary" type="submit" value="submit" >Send Message</button>
</div>
</div>
</form>
here is the script :
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
and because i dont know where the problem is, please check also my php code. thank you stackoverflow,good programmers.
php code :
<?php
$name = $_POST['name'];
$email_from = $_POST['email'];
$comments = $_POST['message'];
$email_to = "jcjohn#gmail.com";
$email_subject = "Message from John Web";
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
echo "<script type='text/javascript'>alert('$message');</script>";
?>
am i doing right ? or maybe i was doing something that nothing goes.
Kindly Use ajaxForm Plugin and include jquery library.I think this will work fine for you.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function(data) {
alert(data);
});
});
</script>
</head>
<body>
<form id="myForm" action="comment.php" method="post">
<div class="form-group">
<label for="contact-name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name" name="name" placeholder="FULL Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-sm-2 control-label">Message</label>
<div class="col-sm-4">
<textarea name="message" class="form-control" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-primary" type="submit" value="submit" >Send Message</button>
</div>
</div>
</form>
</body>
</html>
and your PHP file code must be like this
<?php
$name = $_POST['name'];
$email_from = $_POST['email'];
$comments = $_POST['message'];
$email_to = "jcjohn#gmail.com";
$email_subject = "Message from John Web";
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
echo "Form Submitted";
?>

Wordpress PHP validation using Modal Contact form

Hi im just new to wordpress i'm just confused on how to link my php validation in wordpress.
i have a send.php in my root folder located in wordpress\wp-content\themes\myTheme. my problem is that whenever i click submit in my contact form. it redirects me to the pa Object not found which in fact the send.php is located. am i doing something wrong? or i linked it incorrectly? here is my code for my Modal Contact Form.
<div class = "modal fade" id = "contact" role = "dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h4>Message Me :3 </h4>
</div>
<div class = "modal-body">
<form class="form-horizontal" name="commentform" method="post" action="send.php">
<div class="form-group">
<label class="control-label col-md-4" for="first_name">First Name</label>
<div class="col-md-6">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="last_name">Last Name</label>
<div class="col-md-6">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="email">Email Address</label>
<div class="col-md-6 input-group">
<span class="input-group-addon">#</span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="comment">Question or Comment</label>
<div class="col-md-6">
<textarea rows="6" class="form-control" id="comments" name="comments" placeholder="Your question or comment here"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<button type="submit" value="Submit" class="btn btn-primary pull-right">Send</button>
</div>
</div>
</form>
</div>
and here is my send.php code
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "ccmanere#gmail.com";
$email_subject = "Your email subject line";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z\s.'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
sleep(2);
echo "<meta http-equiv='refresh' content=\"0; url=http://tutsme-webdesign.info/index.php\">";
?>
<?php
}
?>

Categories

Resources