Getting a form to send an selected option to email - javascript

Hi i have been trying for a good 2 hours to get this dropdown menu to get the selected result to go to email through post method im new to php and i think i could just do with abit of guidance ill post html php js code below.i have tried many ways this isnt my only edit ive literally tried everything i just need a little help
html
<div class="col-lg-3">
<div class="form-group mt-2">
<div class="dropdown" >
<select name="vehicles" id="vehicles" class="ddstyle">
<option value="motor" selected>Motorcycle</option>
<option value="Car">Car</option>
<option value="Small">Small Van</option>
<option value="Opel">Opel</option>
<option value="Midi">Midi Van</option>
<option value="SWB">SWB up to 2.4m</option>
<option value="MWB3">MWB up to 3m</option>
<option value="LWB4">LWB up to 4m</option>
<option value="XLWB4">XLWB 4m+</option>
<option value="Luton">Luton</option>
<option value="T5">7.5T</option>
</select>
</div>
</div>
</div>
PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$dod = $_POST['dod'];
$yourname = $_POST['yourname'];
$tel = $_POST['tel'];
$caddy = $_POST['caddy'];
$cpost = $_POST['cpost'];
$daddy = $_POST['daddy'];
$dpost = $_POST['dpost'];
$dofd = $_POST['dofd'];
$Car = $_POST['Car'];
$Small = $_POST['Small'];
$Opel = $_POST['Opel'];
$Midi = $_POST['Midi'];
$MWB = $_POST['MWB'];
$MWB3 = $_POST['MWB3'];
$LWB4 = $_POST['LWB4'];
$XLWB4 = $_POST['XLWB4'];
$Luton = $_POST['Luton'];
$T5 = $_POST['T5'];
//*$vehicles = $_POST['$vehicles'];**/
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
if(isset($_POST['vehicles']) && $_POST['vehicles']=='motor') echo $value;
if(trim($name) == '') {
echo '<div class="error_msg">You must enter your company name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_msg">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_msg">You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($dod) == '') {
echo '<div class="error_msg">Please enter your collection date.</div>';
exit();
}
if(trim($dofd) == '') {
echo '<div class="error_msg">Please enter your drop off deadline.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#example.net";
$address = "admin#ready2gologistics.co.uk";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = ' ' . $name . ' has a possible job!';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "$name wants a quote details are listed below." . PHP_EOL . PHP_EOL;
$e_content =
"
Company: $name
Name of Person: $yourname
Contacts email: $email
Contacts Telephone Number: $tel
Desired Collection Date: $dod
Drop Off Deadline: $dofd
Collection Address: $caddy
Collection Post Code: $cpost
Destination Address: $daddy
Destination Post Code: $dpost
Addtional Information: $comments
test: $value
" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_msg'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your quote has been submitted to us. To see how we use your information check out our <a href='PrivacyPolicy.html".$link_address."'>Privacy Policy</a></p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
JavaScript
//Contact
$('#working_form').submit(function() {
var action = $(this).attr('action');
$("#message").slideUp(750, function() {
$('#message').hide();
$('#submit')
.before('<img src="" class="gif_loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
dod: $('#dod').val(),
dofd: $('#dofd').val(),
yourname: $('#yourname').val(),
cpost: $('#cpost').val(),
caddy: $('#caddy').val(),
tel: $('#tel').val(),
daddy: $('#daddy').val(),
dpost: $('#dpost').val(),
vehicles: $('#vehicles').val(),
value: $('#value').val(),
},
function(data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.gif_loader').fadeOut('slow', function() {
$(this).remove()
});
$('#submit').removeAttr('disabled');
if (data.match('success') != null) $('#cform').slideUp('slow');
}
);
});
return false;
});

In $.post request pass send value
$.post(action, {
...other data
value: $('#value').val(),
send: $('#send').val(),
}
Because your $value vehicle data is depended on if(isset($_POST['send'])) check
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}

Related

What is missing from this AJAX call code?

I apologize for not providing the full code for context, I am VERY new to this. Here is the code for the signup.php file:
<?php
session_start();
include('connection.php');
$missingUsername='<p><strong>Please enter a username</strong></p>';
$missingEmail='<p><strong>Please enter your email address</strong></p>';
$InvalidEmail='<p><strong>Please enter a valid email address</strong></p>';
$missingPassword='<p><strong>Please enter a password</strong></p>';
$InvalidPassword='<p><strong>Your password should be at least 6 characters long and include one capital letter and one number</strong></p>';
$differentPassword='<p><strong>Passwords don\'t match</strong></p>';
$missingPassword2='<p><strong>Please confirm your password</strong></p>';
if(empty($_POST["username"])){
$errors .= $missingUsername;
}else{
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
}
if(empty($_POST["email"])){
$errors .= $missingEmail;
}else{
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors .= $InvalidEmail;
}
}
if(empty($_POST["password"])){
$errors .= $missingPassword;
}elseif(!(strlen($_POST["password"])>6 and preg_match('/[A-Z]/',$_POST["password"]) and preg_match('/[0-9]/',$_POST["password"]))){
$errors .= $InvalidPassword;
}else{
$password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
if(empty($_POST["password2"])){
$errors .= $missingPassword2;
}else{
$password2 = filter_var($_POST["password2"], FILTER_SANITIZE_STRING);
if($password !== $password2){
$errors .= $differentPassword;
}
}
}
if($errors){
$resultMessage = '<div class="alert alert-danger">' . $errors .'</div>'
echo $resultMessage;
}
$username = mysqli_real_escape_string($link, $username);
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$password = hash('sha256', $password);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
$results = mysqli_num_rows($result);
if($results){
echo '<div class="alert alert-danger">That username is already registered. Do you want to log in?</div>';
exit;
}
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
$results = mysqli_num_rows($result);
if($results){
echo '<div class="alert alert-danger">That email is already registered. Do you want to log in?</div>';
exit;
}
$activationKey = bin2hex(openssl_random_pseudo_bytes(16));
$sql = "INSERT INTO users ('username', 'email', 'password', 'activation') VALUES ('$username', '$email', '$password', '$activationKey')";
$result = mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">There was an error inserting the user details in the database!</div>';
exit;
}
$message = "Please click on this link to activate your account:\n\n";
$message .= "http://studenttest.host20.uk/activate.php?email=" . urlencode($email) . "&key=$activationKey";
if(mail($email, 'Confirm your Registration', $message, 'From:'.'msyed0230#gmail.com')){
echo "<div class='alert alert-success'>Thank you for registration! Confirmation email has been sent to $email. Please click on the activation link to activate your account.</div>";
}
?>
Here again is the JS code block I'm working with within a broad goal of making a proper sign-up form:
$("#signupform").submit(function(event){
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signup.php",
type: "POST",
data: datatopost,
success: function(data){
if(data){
$("#signupmessage").html(data);
}
},
error: function(){
$("#signupmessage").html("<div class='alert alert-danger'>There was an error with the Ajax call. Please try again later.</div>");
}
});
});
For some reason, I keep getting the AJAX error instead of the typical error messages I set up for username entry, password entry, etc. It is linked to the correct files (put in the script tag in my main index.php file) and with everything else.
What could be going on?
You might have an error in your signup.php page so it would be better if you put the whole code so as to find the issue and to fix it.
I've made a little example with almost the same code as yours and it works fine :
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" >
<div id="signupmessage"></div>
<form id="signupform" action="" method="POST">
<input type="text" name="firstname" placeholder="Enter your first name" /><br /><br />
<input type="text" name="lastname" placeholder="Enter your last name" /><br /><br />
<input type="submit" value="submit">
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type='text/javascript'>
$("#signupform").submit(function(event){
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signup.php",
type: "POST",
data: datatopost,
success: function(data){
$("#signupmessage").html(data);
},
error: function(data){
$("#signupmessage").html(data);
}
});
});
</script>
--------- signup.php -----------
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname."<br />";
echo $lastname;
}
else{
echo "<div class='alert alert-danger'>There was an error with the Ajax call. Please try again later.</div>";
}
?>

success message for form not working properly

I am working on a form located in the notify button here
I am testing the form now and I get every submission in my email, but on the frontend my success message is showing on the screen.
I would like for this form to work exactly like the contact form on the site where the success message pops up in a placeholder.. or at the bottom of the form
the html and js for the form are below. I have a feeling like I messed up on the class and/or id somewhere. I got all of this code online and have been editing it to make it do what I need it to do LOL! now I am stuck
HTML
<form action="php/newsletter-process.php" id="newsletter-form" method="post">
<input type="text" class="form-control form-control-custom" tabindex="-1"
id="text-field-nl" name="text-field-nl">
<!-- Input Name -->
<div class="nl-form-group" id="name-field">
<label for="form-name" class="sr-only">Name</label>
<input type="text" class="form-control form-control-light"
id="form-name" name="form-name" placeholder="Name">
</div>
<!-- /End Input Name -->
<!-- Input Email -->
<div class="nl-form-group" id="email-field">
<label for="form-email" class="sr-only">Email</label>
<input type="email" class="form-control form-control-light"
id="form-email" name="form-email" placeholder="Email">
</div>
<!-- /End Input Email -->
<!--Check Interest-->
<div class="nl-form-group">
<p>Which are you more interested in?</p>
<input type="checkbox" id="workbook" name="interest-type[]" value="Digital Workbook"/> Digital Workbook<br/>
<input type="checkbox" id="vclass" name="interest-type[]" value="Virtual Class Session"/>Virtual Class Session
</div>
<!-- /End Input Group -->
<!-- Submit Button -->
<div class="btn-row">
<div class="form-group">
<button type="submit" class="btn btn-light" role="button">
Send Message
</button>
</div>
</div>
<!-- /End Submit Button -->
<!-- Message Alert -->
<!--div id="message-newsletter" class="message-wrapper text-white message">
<span><i class="icon icon-sm icon-arrows-slim-right-dashed"></i><label
class="message-text" for="email"></label></span>
</div-->
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text"></span>
</div>
<!-- /End Message Alert -->
</form>
<!-- /End Newsletter Form -->
JS
/*
--------------------------------
Ajax Contact Form
--------------------------------
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
+ A Simple Ajax Contact Form developed in PHP with HTML5 Form validation.
+ Has a fallback in jQuery for browsers that do not support HTML5 form validation.
+ version 1.0.1
+ Copyright 2014 Pedro Rogerio
+ Licensed under the MIT license
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
*/
(function ($, window, document, undefined) {
'use strict';
var form = $('#newsletter-form'),
messageContainer = $('#message-newsletter'),
messageText = $('#message-newsletter .message-text');
form.submit(function (e) {
// remove the error class
form.find('.nl-form-group').removeClass('error');
messageContainer.removeClass('error');
var errorAll = '';
// get the form data
var formData = {
'name': $('input[name="form-name"]').val(),
'email': $('input[name="form-email"]').val(),
'textfield': $('input[name="text-field"]').val()
};
// process the form
$.ajax({
type: 'POST',
url: 'php/newsletter-process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('error');
errorAll = data.errors.name;
}
if (data.errors.email) {
$('#email-field').addClass('error');
errorAll = errorAll + ' ' + data.errors.email;
}
messageContainer.addClass('error');
messageText.html(errorAll);
} else {
// display success message
messageText.html(data.confirmation);
$('#newsletter-form .form-control').each(function () {
$(this).fadeIn().val($(this).attr('placeholder'));
});
}
});
messageContainer.slideDown('slow', 'swing');
setTimeout(function () {
messageContainer.slideUp('slow', 'swing');
}, 10000);
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
PHP
<?php
$subjectPrefix = 'App It Out Notify';
$emailTo = 'taking this out';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['form-name']));
$email = stripslashes(trim($_POST['form-email']));
$spam = $_POST['textfield'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
Change your button type to "button" to not reload the page.
<button type="button" class="btn btn-light" role="button">
Send Message
</button>
Use the Ajax 'success' and 'error' properties to handle the request success/errors
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Use the success/error function to push your success message into the HTML
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text" id="messageText"></span>
</div>
JS
document.getElementById('messageText').innerHTML = <success or error message>
Your code is a little bit messed up, what you can do is:
Step one
Serialize your form data, change your formData variable to:
var formData = $("form#newsletter-form").serialize();
also change the sent data and the url in your ajax:
$.ajax({
type: 'POST',
url: 'index.php' /*Now, we are requesting the index page instead of the php page.*/,
data: {'submission': formData},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Step two
Instead of writing a messed up php code you can create a functions like this:
<?php
class classname{
public function funcName($formdata,$errors,$data){
$get = explode('&', $formdata); // explode with and
foreach ( $get as $key => $value) {
$valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] = substr( $value, strpos( $value, '=' ) + 1 ) ;
}
// access your query param
$name = stripslashes(trim($valn['name']));
$email = stripslashes(trim($valn['email']));
$spam = $valn['spam'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
}
?>
Now, we need to request the function from the index.php. so, add this php code to your index page
<?php
if (isset($_POST['submission'])) {
header('Content-Type: application/json; charset=utf-8');
$subjectPrefix = 'App It Out Notify';//I don't know if you need this in your php file if so you can add it.
$emailTo = 'taking this out';//I don't know if you need this in your php file if so you can add it.
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
require_once('yourphppage.php');
$conform = new classname;
$search->funcName($_POST['data'],$errors,$data);
die();
}
?>

send form data to admin email in codeIgniter

I am newer for codeigniter. I have an one contact form with fields of stream, name, email, contact. But I have an problem with form data are not send to admin email. When i tried to submit the data on contact form page source will alert but i have given other alert data.
I have tried following code,
$('#interiorid').submit(function (e) {
e.preventDefault();
var interiorstream = $('#interiorstream').val();
var interiorname = $('#interiorname').val();
var interiormobile = $('#interiormobile').val();
var interioremail = $('#interioremail').val();
var mobileVarify = /[0-9]/.test(interiormobile);
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var dataString = 'interiorstream =' + interiorstream + '&interiorname =' + interiorname + '&interiormobile =' + interiormobile + '&interioremail =' + interioremail;
alert(interiorstream);
if (interiorstream == "0") {
alert('Please select Stream');
}
else {
if (interiorname.length > 2) {
if (mobileVarify == true && interiormobile.length == 10) {
if (regex.test(interioremail) == true) {
$.ajax({
url: 'interior_email',
type: 'post',
data: dataString,
success: function (msg, status) {
alert(status);
alert(msg);
$("#interiorid")[0].reset();
window.location.href = "/contact/thank-you";
}
});
}
else {
alert('Invalid Email');
}
}
else {
alert('Invalid Number');
}
}
else {
alert('Please enter name');
}
}
});
<!--- View ---->
<form id="interiorid">
<div class="form-div">
<select value="" id="interiorstream" >
<option value="0">Select a Stream</option>
<option value="Interior Designing">Interior Designing</option>
<option value="Fashion Designing">Fashion Designing</option>
</select>
</div>
<div class="form-div">
<input type="text" placeholder="Name" id="interiorname">
</div>
<div class="form-div">
<input type="text" placeholder="Phone" id="interiormobile">
</div>
<div class="form-div">
<input type="text" placeholder="Email" id="interioremail">
</div>
<div class="form-div">
<input type="submit" value="submit">
</div>
</form>
<!----Controller ---->
<?php
class Home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
$this->load->helper(array('url'));
}
function index() {
$this->load->view('templates/header');
$this->load->view('home');
$this->load->view('templates/footer');
$this->load->helper('form');
$this->load->view('interior/interior-intro');
}
function interior_email()
{
if (!isset($_POST['e-mail'])){
//redirect if no parameter e-mail
redirect(base_url());
}else{
$interiorstream = $this->input->post('interiorstream');
$interiorname = $this->input->post('interiorname');
$interiorphone = $this->input->post('interiorphone');
$interioremail = $this->input->post('interioremail');
$message = 'Hello Admin, This mail received from Interior design page contact form.<br/><br/>
Stream:' . $interiorstream . '<br/><br/>
Name :' . $interiorname . '<br/><br/>
Contact :' . $interiorphone . '<br><br>
Email :' . $interioremail;
$headers1 = "MIME-Version: 1.0\r\n";
$headers1 .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers1 .= "To:";
$headers1 .= "example.com <info#example.com>";
$headers1 .= "\r\n";
$headers1 .= 'From: INIFD : info#example.com' . "\r\n";
$headers1 .= "\r\n";
$subject = "Enquiry From example.com Web";
$email = 'admin#example.com';
if (mail($email, $subject, $message, $headers1)) {
echo 'mail has been sent';
} else {
echo 'mail sending failed';
}
}
}
}
?>
wrong popup like this:
So please help me.
If you are running on a localhost, it is near impossible to send emails. You can check this is if you really want to send Check this post out or try PHPMailer

PHP email issue with $Error message

On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}

Ajax doesn't send data to PHP file

I wrote this script which doesn't send the data from the AJAX to the PHP file. I debugged it with logging the data that's in the form before it ran through the AJAX function. It gave me this data:
Form: name=jim&email=info%40test.com
However, I get an empty alert and I receive an empty e-mail.
HTML
<form name="form" id="form" class="form" method="post">
<input type="text" class="text border" name="name" id="name" placeholder="Name" />
<input type="text" class="text" name="email" id="email" placeholder="E-mail" />
<input type="submit" class="button" value="Submit" />
</form>
JS
jQuery(function(){
jQuery('#form').submit(function(event){
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "includes/post.php",
data: jQuery('#form').serialize(),
success: function(data){
jQuery("#form").addClass("inactive");
jQuery("#message").addClass("active");
alert(data);
}
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$to = "test#hidden.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> '.$name.' <br/>
<strong>E-mail: </strong> '.$email.' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: '.$name.', '.$email;
$headers .= "From: ".$name." ".$$email."\r\n";
$headers .= "X-Mailer: PHP's mail() Function\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
?>
Try the below code,
Update your PHP with the below,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
echo $name;// this will see in your response
$to = "test#gmail.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> ' . $name . ' <br/>
<strong>E-mail: </strong> ' . $email . ' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: ' . $name . ', ' . $email;
$headers = "From: " . $name . " " . $email . "\r\n";
$headers.= "X-Mailer: PHP's mail() Function\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
Nothing is being returned from your php, and you need some form of server side validation, here is a complete code you can use:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'your#yourdomain.com'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
// Check name
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
You should write echo statement after mail() function. The string written in echo statement will display in alert.
for example : echo "Mail sent successfully";

Categories