File attachments fails - php

Hi I am trying to send a mail with phpmailer lib, with option to attach multiple files.
But my mailer script doesnt send mails.
I have used a similar script to send mails successfully. But it fails when I try with attachments. I followed the PHPmailer example.
(I am using recaptcha 3 with this form.)
If possible, kindly take a look and let me know what I might be doing wrong.
Thanks a lot in advance.
The html file
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Multiple File Upload</title>
</head>
<body>
<form method="post" id="contact-form" enctype="multipart/form-data" action="testmailer.php">
<input name="fname" placeholder="Your name" title="Your name" type="text" /></div>
Select one or more files:
<input name="userfile[]" type="file" multiple="multiple">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
<input type="submit" id="submit-button" value="Send Files">
<div id="alertm"></div>
</form>
<script>
$('#contact-form').submit(function(event) {
event.preventDefault();
$('#alertm').text('Processing...').fadeIn(0);
grecaptcha.ready(function () {
grecaptcha.execute('xxxrecaptcha3-site_keyxxx', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
// Make the Ajax call here
$.ajax({
url: 'testmailer.php',
type: 'post',
data: $('#contact-form').serialize(),
dataType: 'json',
success: function( _response ){
// The Ajax request is a success. _response is a JSON object
var error = _response.error;
var success = _response.success;
if(error != "") {
// In case of error, display it to user
$('#alertm').html(error);
}
else {
// In case of success, display it to user and remove the submit button
$('#alertm').html(success);
$('#submit-button').remove();
}
},
error: function(jqXhr, json, errorThrown){
// In case of Ajax error too, display the result
var error = jqXhr.responseText;
$('#alertm').html(error);
}
});
});
});
});
</script>
</body>
</html>
The mail sending script
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/PHPMailer/src/PHPMailer.php';
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer();
if(isset($_POST['fname'])){
$name=$_POST['fname'];
}
function isValid() {
if($_POST['name'] != "") {
return true;
} else {
return false;
}
}
$email_to = "email#domain.com";
$mail->setFrom('no-reply#somedomain.com', 'SomeDomain Mailer');
$mail->Subject = 'File Attachment';
$body = "Name - $name\n";
$mail->Body = $body;
if (array_key_exists('userfile', $_FILES)) {
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to attach file ' . $filename;
}
} else {
$body .= 'Failed to move file to ' . $uploadfile;
}
}
$mail->IsHTML(true);
$error_output = '';
$success_output = '';
if(isValid()) {
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '***recaptcha3-secret_key***';
$recaptcha_response = $_POST['recaptcha_response'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'contact') {
$mail->send();
$success_output = "Your message sent successfully";
} else {
$error_output = "Something went wrong. Please try again later";
}
} else {
$error_output = "Please fill all the required fields";
}
$output = array(
'error' => $error_output,
'success' => $success_output
);
// Output needs to be in JSON format
echo json_encode($output);
}
?>

Related

PHP PDO insert into mysql table via AJAX with JSON response

I have a contact form in my index page that should have the email and message of visitor which will be stored in mysql table after send button is clicked , I've created a jquery button click function which has the ajax call and ajax request goes to a page called contact I don't know why it's not working did I missed up ! now This is my project structure:
index.php
connect.php (Database Connection)
js (folder) => ajax.js (The jquery file inside the "js" folder)
ajax (folder) => contact.php (The php file inside the ajax folder)
My html:
<div id="index-contact-form">
<form>
<div>
<input type="email" id="con-email" required>
<label>Email</label>
</div>
<div>
<textarea id="con-msg" required></textarea>
<label>Message</label>
</div>
<div>
<button id="con-send-btn" class="btn index-contact-form-btn">Send</button>
<p id="con-error"></p>
</div>
</form>
</div>
This is my ajax.js file code:
$(document).ready(function(){
$("#con-send-btn").click(function(e){
e.prvenetDefault();
// Get Vister Entered Data
var contactEmail = $("#con-email").val().trim();
var contactMsg = $("#con-msg").val().trim();
// Call AJAX Method And Specify Its Parameters
$.ajax({
url: "../ajax/contact.php",
type: "POST",
data: {email:contactEmail,message:contactMsg},
dataType:"json",
success: function(data){
$("#index-contact-form").empty();
$("#index-contact-form").append(data.success);
},
error: function(data){
$("#con-error").text(data.fail);
}
});
});
});
This is my contact.php file code:
<?php
ini_set( 'error_reporting', E_ALL );
ini_set( 'display_errors', true );
include("../connect.php");
if(isset($_POST['email']) && isset($_POST['message']))
{
// Get Data From POST Request
$email = $_POST['email'];
$message = $_POST['message'];
// Declare Variables For Maintain The Results
$success = '';
$fail = '';
// Validate The Form
$formErrors=array(); // Empty Array Defined For Containing Error Messages Of Empty Inputs
if(isset($email))
{
$filteredEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
if(filter_var($filteredEmail , FILTER_SANITIZE_EMAIL) != true)
{
$formErrors[]='Email not valid';
}
if(strlen($filteredEmail) > 100)
{
$formErrors[]='Email should be less than 100 characters';
}
if(empty($filteredEmail))
{
$formErrors[]='You should provide email';
}
}
if(isset($message))
{
$filteredMessage = filter_var($message,FILTER_SANITIZE_STRING);
if(strlen($filteredMessage) < 10)
{
$formErrors[]='Message can't be less than 10 characters';
}
if(strlen($filteredMessage) > 255)
{
$formErrors[]='Message must be less than 255 characters';
}
if(empty($filteredMessage))
{
$formErrors[]='Message must not be empty';
}
}
// If There Is No Error Procced The Insert Operation
if(empty($formErrors))
{
// Insert User Info In Database
$stmt = $con->prepare("insert into contact (ID , email , message) values (DEFAULT , :cemail , :cmessage)");
$stmt-> execute(array(
'cemail' => $email,
'cmessage' => $message
));
$success .= "Message has been sent";
}
else
{
foreach($formErrors as $error)
{
$fail .= $error;
}
}
$data = array('success' => $success,'fail' => $fail);
echo json_encode($data);
}
?>

Limiting attachment type and file size on PHPMailer contact form

I've created a contact form, which allows for the upload of 3 files. Currently there is no limitation to the file size and file type.
I would like to be able to do the following:
Limit the file type to "png,gif,jpg,jpeg,bmp"
Limit the file size to 5mb
I'm currently using PHPMailer to send the contact form via SMTP.
My contact_mail.php contents:
<?php
require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = FALSE;
$mail->Port = 25;
$mail->Host = "###HIDDEN###";
$mail->Mailer = "smtp";
$mail->SetFrom($_POST["userEmail"], $_POST["userName"]);
$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
$mail->AddAddress("###HIDDEN###");
$mail->Subject = $_POST["subject"];
$mail->WordWrap = 80;
$mail->Body='Name: '.$_POST['userName'].'<br />
Telephone: '.$_POST['telephone'].'<br />
Nationality: '.$_POST['nationality'].'<br />
Age: '.$_POST['age'].'<br />
Height: '.$_POST['height'].'<br/>
Favourites: '.$_POST['age'].'<br />
Bio: '.$_POST['content'];
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile'] ['tmp_name'],$_FILES['attachmentFile']['name']);
$mail->AddAttachment($_FILES['attachmentFile2']['tmp_name'],$_FILES['attachmentFile2']['name']);
$mail->AddAttachment($_FILES['attachmentFile3']['tmp_name'],$_FILES['attachmentFile3']['name']);
}
$mail->IsHTML(true);
if(!$mail->Send()) {
echo "<p class='error'>Problem in Sending Mail.</p>";
} else {
echo "<p class='success'>Contact Mail Sent.</p>";
}
?>
Form content:
<div class="col-xs-12 col-sm-4 labelPanel">
<label>Portfolio Images</label><br/>
<input type="file" name="attachmentFile" id="attachmentFile" class="inputField">
<input type="file" name="attachmentFile2" id="attachmentFile" class="inputField">
<input type="file" name="attachmentFile3" id="attachmentFile" class="inputField">
</div>
PHP code & validation:
<script type="text/javascript">
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$('#loader-icon').show();
var valid;
valid = validateContact();
if(valid) {
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
$('#loader-icon').hide();
},
error: function(){}
});
}
}));
function validateContact() {
var valid = true;
$(".inputField").css('background-color','');
$(".info").html('');
if(!$("#userName").val()) {
$("#userName-info").html("(required)");
$("#userName").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#telephone").val()) {
$("#telephone-info").html("(required)");
$("#telephone").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#nationality").val()) {
$("#nationality-info").html("(required)");
$("#nationality").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#age").val()) {
$("#age-info").html("(required)");
$("#age").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#height").val()) {
$("#height-info").html("(required)");
$("#height").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#favourites").val()) {
$("#favourites-info").html("(required)");
$("#favourites").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#userEmail").val()) {
$("#userEmail-info").html("(required)");
$("#userEmail").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#userEmail").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#userEmail-info").html("(invalid)");
$("#userEmail").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#subject").val()) {
$("#subject-info").html("(required)");
$("#subject").css('background-color','#FFFFDF');
valid = false;
}
if(!$("#content").val()) {
$("#content-info").html("(required)");
$("#content").css('background-color','#FFFFDF');
valid = false;
}
return valid;
}
});
</script>
I'm quite new to PHP so I've followed a tutorial online to create the contact form as it is - unfortunately when it comes to validation on image upload, I'm a bit stuck.

AngularJS PHP contact cannot read property name

Basically I have a contact form made with angularJS and PHP. and thats hosted on 000webhost. When I'm sending a mail the mail goes through but it also gives me an error. I think thats the reason it doesnt display MessageSuccess or MessageError messages.
TypeError: Cannot read property 'name' of undefined
at app.js:119
at angular.min.js:81
at angular.min.js:112
at m.$get.m.$eval (angular.min.js:126)
at m.$get.m.$digest (angular.min.js:123)
at m.$get.m.$apply (angular.min.js:127)
at l (angular.min.js:81)
at P (angular.min.js:85)
at XMLHttpRequest.H.onload (angular.min.js:86)
the HTML:
<div id="websiteApp" class="contactRow" style="display: none;">
<form ng-submit="submitForm()" ng-controller="FormController" novalidate class="contactForm" name="form" ng-hide="loaded">
<input class="input" type="text" name="name" placeholder="SINU NIMI" ng-model="formData.name" ng-class="{'error' : errorName}">
<input class="input2" type="email" name="email" placeholder="SINU E-MAIL" ng-model="formData.email" ng-class="{'error' : errorEmail}">
<textarea name="message" ng-class="{'error' : errorTextarea}" placeholder="KIRJUTA MEILE" ng-model="formData.message" rows="5"></textarea>
<input class="saada" type="submit" value="SAADA!" name="submit">
<div ng-class="{'submissionMessage' : submission}" ng-bind="submissionMessage"></div>
</form>
</div>
App.js
var app = angular.module('kaidoweb', ['ngRoute', 'ngAnimate']).
config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'pages/index.html',
activetab: 'index',
controller: HomeCtrl
}).
otherwise({ redirectTo: '/' });
}]).run(['$rootScope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.part = $route.current.activetab;
});
}]);
/*app.config(['$locationProvider', function($location) {
$location.hashPrefix('!');
}]);*/
//Contact form
app.controller('FormController',function($scope, $http) {
// creating a blank object to hold our form information.
//$scope will allow this to pass between controller and view
$scope.formData = {};
// submission message doesn't show when page loads
$scope.submission = false;
// Updated code thanks to Yotam
var param = function(data) {
var returnString = '';
for (d in data){
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
// Remove last ampersand and return
return returnString.slice( 0, returnString.length - 1 );
};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = data.messageError;
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.submissionMessage = data.messageSuccess;
$scope.formData = {}; // form fields are emptied with this line
$scope.submission = true; //shows the success message
}
});
};
});
and the PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
$data['messageError'] = 'Vaata üle punased alad!';
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['messageSuccess'] = 'Tänan, et kirjutasid. Võtan ühendust nii pea kui saan.';
// CHANGE THE TWO LINES BELOW
$email_to = "email.to#khk.ee";
$email_subject = "KaidoWeb kiri";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['message']; // required
$email_message = "Form details below.nn";
$email_message .= "Name: ".$name."n";
$email_message .= "Email: ".$email_from."n";
$email_message .= "Message: ".$message."n";
$headers = 'From: '.$email_from."rn".
'Reply-To: '.$email_from."rn" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
}
// return all our data to an AJAX call
echo json_encode($data);
Also another thing is I also host this site on GoDaddy when trying to send a mail there it says: POST http://www.kaidoweb.com/process.php 403 (Forbidden).
I would be immensely grateful if someone could give me some sort of solution here and if you need to see something more just ask.
This is how your PHP is setting the errors object it is returning to your Angular App:
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
As you can see, in each case it is setting a different key inside of the errors array. In your Angular code you don't account for this, you just assume that all of the keys will be set:
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
You can fix this either in your PHP or in your Angular App. In PHP, you could use an integer array rather than an associative array:
if (empty($_POST['name']))
$errors[] = 'Name is required.';
if (empty($_POST['email']))
$errors[] = 'Email is required.';
if (empty($_POST['message']))
$errors[] = 'Message is required.';
Then in Angular just set the scope variable and modify the view with how it's displayed:
$scope.errors = data.errors;
<ul><li data-ng-repeat="error in errors">{{ error }}</li></ul>
Alternatively, in Angular just check if the keys are set before attempting to access them:
if(data.errors.hasOwnProperty('name') {
$scope.errorName = data.errors.name;
}
Update
I'm talking about this section of your angular code, specifically the case in the success callback where data.success is falsey:
$scope.submitForm = function() {
$http({
method : 'POST',
// ...
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errors = data.errors;
$scope.submission = true; //shows the error message
} else {
// ...
}
});
};
Since you're probably binding to e.g. {{ errorName }} in your view template, wherever that is, that will also have to be updated with what I have above if you switch your $error array to return with numerical indices.

Cant get google recaptcha v2 to prevent form submission

So I can successfully get the captcha to validate, using the following code.
</p>
<?php
if(isset($_POST['g-recaptcha-response'])){
echo verify($_POST['g-recaptcha-response']);
}
function verify($response) {
$ip = $_SERVER['blank']; //server Ip
$key="secretkey"; // Secret key
//Build up the url
$url = 'https://www.google.com/recaptcha/api/siteverify';
$full_url = $url.'?secret='.$key.'&response='.$response.'&remoteip='.$ip;
//Get the response back decode the json
$data = json_decode(file_get_contents($full_url));
//Return true or false, based on users input
if(isset($data->success) && $data->success == true) {
return True;
}
return False;
}
?>
<p style="text-align: justify;">
<script type="text/javascript">
function verify(){
var serializedValues = jQuery("#infoForm").serialize();
jQuery.ajax({ type: 'POST',url:"verify.php",data: serializedValues,success:function(result){
if(result){
$('#show').html('Your Form Successfully Submitted');
$('.formwrap').hide(result);
return true;
}
}});
$('#show').html('Please Enter Valid Captcha');
return false;
}
var onloadCallback = function() {
grecaptcha.render('captcha_ele', {
'sitekey' : 'Enter Your Site Key Here', // Site key
});
};
</script>
However, when I click submit, regardless of what the captcha says, form will still submit. My email form process is as follows...
<!-- language: lang-css -->
$("#blank").submit(function() {
$.post('assets/php/email-process.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'},
function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
<?php
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
// display message that the form submission was rejected
}
else {
// accept form submission
$to = 'info#blank'; // Replace with your email
$subject = 'Message from website visitor'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
I use this which works for me. Put a js function in your form submit to validate the re-captcha:
<form action="/sign-visitors-log/" method="post" id="VisitorsLogForm" onsubmit="return validateRecaptcha();">
Then some js to stop the form submit if the user didn't tick the check box:
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("not validated");
return false;
} else {
alert("validated");
return true;
}
}
You can swap out the alerts for toast or as you are doing some elements on the page.
HTH
In a separate js file (at least: no inline call to a function), you have to check if the captcha can validate. Like so:
jquery('form').on('submit',function(e){
if(grecaptcha.getResponse() === "") {
e.preventDefault();
alert('Error: \n please validate the Captcha test');
}
});
You don't have to check if the test passive as true, you have already prevented the form to be sent with this method.
This is a simpler model that does the job
document.querySelector(".form").addEventListener("submit", (event)=>{
const response = grecaptcha.getResponse();
if (response.length === 0) {
event.preventDefault();
alert("Please verify that you are human!");
}
})
<!--reCAPTCHA v2 -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="/" method="POST" class"form">
<!--Please register as a developer and add "your_site_key" you will find it on https://www.google.com/recaptcha/admin/create-->
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</form>

Post error report by pressing a button jQuery not working

Small problem here, I need to place a button on my 404 page to ask people to submit an error.
The problem is that nothing is actually happens, I mean no mail is received and no errors are displayed, so I am confused.
My report is very basic, it collects all data of what my user did before getting 404
$site = "mySite.com";
$email = "donotreply#mySite.com";
$http_host = $_SERVER['HTTP_HOST'];
$server_name = $_SERVER['SERVER_NAME'];
$remote_ip = $_SERVER['REMOTE_ADDR'];
$request_uri = $_SERVER['REQUEST_URI'];
$cookie = $_SERVER["HTTP_COOKIE"];
$http_ref = $_SERVER['HTTP_REFERER'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$error_date = date("D M j Y g:i:s a T");
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "404 Error Report for ".$site."\n";
$message .= "Date: ".$error_date."\n";
$message .= "Requested URL: http://".$http_host.$request_uri."\n";
$message .= "Cookie: ".$cookie."\n";
$message .= "Referrer: ".$http_ref."\n";
$message .= "User Agent: ".$user_agent."\n";
$message .= "IP Address: ".$remote_ip."\n";
$message .= "Whois: http://ws.arin.net/cgi-bin/whois.pl?queryinput=".$remote_ip;
this is my form, all fields are hidden that are placed in the same file along with php code above
<form name="form" method="POST" id="report-form">
<div class="form">
<input type="hidden" name="message" value="$message">
<div class="done">
<p><strong>Thank you!</strong></p>
</div>
<div class="error">
<p><strong>Error!</strong> Sorry, something went wrong, please try again.</p>
</div>
<input type="hidden" name="visitor" value="">
<input type="hidden" name="submitted" value="submitted">
<input type="submit" name="submit" value="Submit" class="formSubmit" />
</div>
</form>
<script type="text/javascript" src="js/report_validation.js"><\/script>
here is my jQuery validation script, which I am trying to use, which is in the separate file named report_validation.js in js folder
$(document).ready ( function() {
$('.formSubmit').click(function() {
// Store values in variables
var form = $(this).closest('form');
var message = form.find('input[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'message=' + message.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "includes/report_form_mail.php",
data: data,
cache: false,
success: function (html) {
if (html == "true") {
form.find('.done').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
here is my mailing script, which is also placed in the separate file and named report_form_mail.php in my incudes folder
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// If valid, store values in variables
$site = "mySite.com";
$email = "donotreply#mySite.com";
$mes = stripslashes($_POST['message']);
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "Message: $mes";
// Send email
$sent = mail($email, $subject, $message, $headers);
if($sent) {
echo json_encode(true);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
Please help me to figure it all out
I have actually found an error myself.
The jQuery was not loaded to the page correctly so I have corrected it and my form works perfectly fine.
Thanks to all

Categories