I've tested my site's mailing with a different script - just to make sure it wasn't the host, and it's working fine.
I'm not sure why my code isn't working. I've included all my contact forums code except the html. It seems to not be loading the php, as it doesn't show any error messages when I put in an invalid email etc. - it just refreshes the page it seems.
Help is much appreciated, thanks everyone.
<!-- Contact Form Js -->
<script type="text/javascript">
// contact form js
jQuery(document).ready(function($) {
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "inc/contact-process.php",
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
setTimeout("location.reload(true);",7000);
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
});
</script>
<!-- End Contact -->
PHP - 'contact-processes'
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include dirname(dirname(__FILE__)).'/config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
if(!$error)
{
ini_set("sendmail_from", WEBMASTER_EMAIL); // for windows server
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
PHP - 'functions'
<?php
function ValidateEmail($value)
{
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($value == '') {
return false;
} else {
$string = preg_replace($regex, '', $value);
}
return empty($string) ? true : false;
}
?>
PHP - 'config'
<?php
define("WEBMASTER_EMAIL", 'snip#myemail.com');
?>
Related
I'm working on a contact website, where I want to have contact form. I want it to send data to e-mail and I want it to be checked by Google's recaptcha v3.
This is my second try. In the past, I've done it successfully without recaptcha. Now, I used this (https://codeforgeek.com/google-recaptcha-v3-tutorial/) tutorial, with following result:
script below the form
// when form is submit
$('#myform').submit(function() {
// we stoped it
event.preventDefault();
var mail = $('#email').val();
var comment = $("#sprava").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('__SITE-KEY__', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#myform').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{mail: mail, comment: comment, token: token}, function(result) {
if(result.success) {
alert('Thanks for message')
} else {
alert('An error occured')
}
});
});;
});
});
</script>
the names of html form fields are "email", "vyber", "sprava"
form.php
<?php
$mail;$comment;$captcha;
$mail = filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
$captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
}
function email_sending(){
$webmaster_email = "bla#bla.com";
$sender_email= "blabla#bla.com" ;
$email_address = $_REQUEST['email'] ;
$selection = $_REQUEST['vyber'] ;
$message = $_REQUEST['sprava'];
$msg =
"E-mail: " . $email_address . "\r\n" .
"I'm interested in " . $selection . "\r\n" .
"Message: " . $message ;
mail( "$webmaster_email", "You have mail", $msg, $header);
}
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
email_sending();
} else {
echo json_encode(array('success' => 'false'));
}
?>
The problem isn't within recaptcha part, but then I recieve e-mail, where data is missing. (it shows only variable names, not actual values). I might think it's because of naming in script, as I'm not sure what to write in declaration of variables. I'd be glad to receive any input about this problem.
I managed to solve this problem by changing server-side code like below, thanks to this Recaptcha tutorial.
// Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '__SECRET-KEY___';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->success == true) {
// Verified - send email
} else {
// Not verified - show form error
}
}
I want to make the form hide and a thank you message appear instead of it after the form is successfully submitted. I've done the below code but I cannot manage to get any action performed after the form is submitted .. it's like the 'if' function is ignored.
Below is my code:
JQuery:
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (! data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert("An internal error has occured");
}
});
//Stop form default action
event.preventDefault();
Php:
<?php
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
$data['success'] = true;
$data['message'] = 'Form Submitted';
}
echo json_encode($data);
Any help would be greatly appreciated. Thanks.
First error I spotted on your code :
'message' : $("#msg").val(), that is your last item in your array therefore no need for the ',' javascript expect more items after','
You need to check all you js errors in the console, they are there.
then the second error I saw,
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
show and hide does not exist in jquery they have show(); and hide(); then here : if (! data.success == true) {}
This is how your code should look :
<script type="text/javascript">
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val()
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (!data.success) {
$('section#contact form#contactform').hide();
$('section#contact div.thxform').show();
//check which field was wrong and show the user
if(data.errors.name){
$('section#contact div.thxform').append(data.errors.name);
}
if(data.errors.email){
$('section#contact div.thxform').append(data.errors.email);
}
if(data.errors.subject){
$('section#contact div.thxform').append(data.errors.subject);
}
if(data.errors.message){
$('section#contact div.thxform').append(data.errors.message);
}
}else{
$('#successDIV').append(data.message);
}
}),
.fail(function(data){
//debugging puporses, all your php errors will be printed in the console
console.log(data);
});
//Stop form default action
event.preventDefault();
</script>
You need to tell the browser what to expect. So add the header function before your echo
header('Content-Type: application/json'); // this line here
echo json_encode($data);
UPDATE
Also your event.preventDefault(); comes last which should be the first thing you call after $('form#contactform').submit(function(event) { since you want to prevent stuff before the ajax call.
Also you PHP is echoing stuff in either case of the mail functions return value. So the json response is messed up, thus your ajax will not get proper data back.
UPDATE 2
I have the strong feeling that your PHP script is throwing errors of some sort. The mail function could be throwing a 530 error for example. So best you disable error displaying in your PHP script.
General advice for debugging this sort of stuff is web developer browser extensions to view request/response information.
Try this refactored code please:
ini_set('display_errors',0); // disable error displaying. Rather view in logs
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['errors'] = $errors; // only necessary to set errors
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
$data['success'] = 'Your message has been sent!'; // store to $data instead of echo out
} else {
$data['errors'] = 'Something went wrong, go back and try again!'; // store to $data instead of echo out
}
}
header('Content-Type: application/json');
echo json_encode($data);
And your javascript snippet in the done function of the ajax call:
<script type="text/javascript">
$('#contactform').submit(function(event) {
event.preventDefault(); // note this one has to be at the beginning of your submit function since you do not want to submit
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (data.success) { // success either exists or not
alert("Success! Form should hide now...");
$('#contactform').hide(); // an id is (should always) be unique. So you dont need this "section#contact form#contactform". It does not make sense. Also hide and show are functions and need brackets at the end
$('div.thxform').show();
} else { // then its an error
alert("An internal error has occured");
}
});
});
</script>
And the HTML i used to test this:
<form method="post" id="contactform">
Name <input type="text" name="name" value="test"><br>
Email <input type="text" name="email" value="test#localhost.com" ><br>
Subject <input type="text" name="subject" value="subject" ><br>
Message <textarea name="message" ></textarea><br>
<input type="submit">
</form>
Its because of 2 tiny mistakes:
[js code] Replace if (! data.success == true) with if (data.success == true).
[php code] add header('Content-Type: application/json'); before echoing $data
I guess the problem is here
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
because you echo a string and then a json object. Therefore when you treat data response on Javascript, it's not a json object.
Then I would do as follow in PHP
if (#mail($to, $subject, $body, $from)) {
$data['success'] = true;
$data['message'] = 'Form Submitted';
} else {
$data['success'] = false;
$data['message'] = 'Internal error';
}
echo json_encode($data);
and in Javascript
.done(function(data) {
if (typeof data !== 'object') {
alert('Expected data as object - '+typeof data+' received');
return;
}
data = jQuery.parseJSON(data);
//Errors and validation messages
if (data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert(data.message);
}
});
Note that the # operator before mail function will not generate error messages to avoid sending a string on Javascript.
Can anybody help me with this? I am not highly proficient in coding but know enough to get by. The issue is that the form can be filled out but in the telephone number field it won't accept spaces and 2) when it is filled out properly it does not return a value of "submitted".
Any help is greatly appreciated.....
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
var href = location.href.replace(/dark\/|video\/|slider\/|contact\.html/g,'');
$.ajax({
type: "POST",
url: href + "contact_form/contact_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
$(this).addClass('success').find('span:eq(1)').html('success');
} else {
$(this).addClass('error').find('span:eq(1)').html('error');
}
}
});
return false;
});
and the PHP code
<?php
include dirname(dirname(__FILE__)).'/mail.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post){
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$message = stripslashes($_POST['message']);
$mail = mail(CONTACT_FORM, $phone, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail){
echo 'OK';
}
}
?>
your data is the wrong syntax you need to define it and then put the key in it i.e.
data: {str: str},
http://api.jquery.com/jQuery.ajax/
I am using the jQuery Form Post plugin from malsup, with the following code:
//Post a form
function PostForm(FormID, Target) {
var $t = Math.round(new Date().getTime() / 1000);
try{
var options = {
target: Target,
beforeSubmit: function () {
jQuery(Target).html('<div id="frmLoadingImageWrapper"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>');
jQuery(Target).slideDown('slow');
},
success: function (html) {
setTimeout(function () {
jQuery(Target).html(html);
jQuery(FormID)[0].reset();
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
}, 100);
},
error: function(e){
var $html = e.responseText;
jQuery(Target).html($html);
jQuery(Target).slideDown('fast');
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
setTimeout(function() {
jQuery(Target).slideUp('fast');
}, 3500);
}
};
jQuery(FormID).ajaxSubmit(options);
}catch(err){
alert(err.message);
}
}
When I submit my form to /inc/mail.php the actuall PHP code shows in my Target instead of getting processed.
How can I fix this issue? All other PHP scripts work as they should, including other ajax pulled php scripts.
Here is the mailer code, it's using PHP SMTP
<?
require("/inc/class.phpmailer.php");
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('m/d/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['secAnswer'];
$valid = true;
if(!is_string($email) || !(strlen($email)>0) || !ValidateEmail($email)){
$valid = false;
}
if(!is_string($name) || !(strlen($name)>0) || !ValidateText($name)){
$valid = false;
}
if(!is_string($message) || !(strlen($message)>0) || !ValidateText($message)){
$valid = false;
}
if(!CheckCAPTCHA($captcha)){
$valid = false;
}
sleep(1.5);
if($valid){
$mail = new PHPMailer();
$mail->IsMail(); // send via SMTP
$mail->From = $email; // SMTP username again
$mail->AddAddress("kevin#pirnie.us"); // Your Adress
$mail->Subject = "New mail your site!";
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Body = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Phone: </strong> {$phone} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
if(!$mail->Send())
{
echo "Mail Not Sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Mail Sent";
}else{
echo "Mail Not Sent. Please make sure all fields are filled out correctly.";
}
function ValidateEmail($str){
$atIndex = strrpos($str, "#");
if (is_bool($atIndex) && !$atIndex){
return false;
}else{
if (filter_var($str, FILTER_VALIDATE_EMAIL)) {
$domain = substr($str, $atIndex + 1);
return (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"));
}else{
return false;
}
}
}
function ValidateText($str){
return (bool)preg_match("/^[a-zA-Z0-9 _-]+$/", $str);
}
function CheckCAPTCHA($str){
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/captcha.class.php');
$csc = new ResponsiveCaptcha();
if($csc->checkAnswer($str)){
return TRUE;
}else{
return FALSE;
}
}
Make sure that your server supports the short PHP open tag <?
If not : change the short_open_tag value in your php.ini file
or use <?php
Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.