Why does my PHP contact form not sendin the messages - php

Okay so i got this form in my website and when i test it and try to send an email message it says that the message has been sent but i dong get it to my email...
here are the codes:
contact.php:
<?php
function ValidateEmail($email)
{
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){1,255}'. # domain & possibly subdomains
'.'. # period
"([a-z]+){2,10}/i"; # domain extension
if($email == '') {
return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}
return empty($eregi) ? true : false;
}
include 'config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
$name = stripslashes($_POST['name']);
$email = $_POST['email'];
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
if(!$name)
{
$error .= '<p>Please enter your name.</p>';
}
if(!$email)
{
$error .= '<p>Please enter an e-mail address.</p>';
}
if($email && !ValidateEmail($email))
{
$error .= '<p>Please enter a valid e-mail address.</p>';
}
if(!$subject || strlen($subject) < 2)
{
$error .= "<p>Please enter the subject.</p>";
}
if(!$message || strlen($message) < 2)
{
$error .= "<p>Please enter your message.</p>";
}
if(!$error)
{
$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 id="notification">'.$error.'</div>';
}
}
?>
config.php:
<?php
// Change this to your email account
define("WEBMASTER_EMAIL", 'my mail address');
?>
form.js:
$(document).ready(function(){
$("#contactForm").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
result = '<div id="notification"><p>Your message has been sent. Thank you!</p></div>';
$('#contactForm').each (function(){
this.reset();
});
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
Thanks!!

Change var str = $(this).serialize(); to data: $("#contactForm").serialize(),

Related

Contact form PHP / HTML / JS - Phone not printing

I've been trying to figure out why my phone string is the only one not being printed in the received email from the contact form.
I have the following:
HTML:
<input
id="phone"
type="text"
name="phone"
placeholder="Telefone"
/>
PHP:
include_once (dirname(dirname(__FILE__)) . '/config.php');
$response = null;
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case "SendMessage": {
if (isset($_POST["email"]) && !empty($_POST["email"])) {
$message = $_POST["message"];
$message .= "<br/><br/>";
$message .= "phone:".$_POST["phone"];
$response = (SendEmail($message, $_POST["subject"], $_POST["name"], $_POST["email"], $email)) ? 'Mensagem Enviada!!' : "Sending Message Failed";
} else {
$response = "Sending Message Failed";
}
}
break;
default: {
$response = "Invalid action is set! Action is: " . $action;
}
}
}
JS:
function SendMail() {
$('.contact-form [type="submit"]').on('click', function () {
var emailVal = $('#contact-email').val();
if (isValidEmailAddress(emailVal)) {
var params = {
'action': 'SendMessage',
'name': $('#name').val(),
'email': $('#contact-email').val(),
'phone': $('#phone').val(),
'subject': $('#subject').val(),
'message': $('#message').val()
};
As i said, everything else is being received on our email, but the phone string.
What am i doing wrong?

error in ajax response if condition error

I want to show error ie. Email already exists in database. If not show Thank you message.
I'm using ajax and jquery for this. Here is my code:
Ajax jquery:
<script type="text/javascript" >
$(function() {
var val_holder;
$("#subscribe").click(function() {
val_holder = 0;
var subscribe_mail = jQuery.trim($("#subscribe_mail").val()); // email field
var email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(subscribe_mail == "") {
$(".error_message").html("This field is empty.");
val_holder = 1;
}
if(subscribe_mail != "") {
if(!email_regex.test(subscribe_mail)){ // if invalid email
$(".error_message").html("Your email is invalid.");
val_holder = 1;
}
}
if(val_holder == 1) {
return false;
}
val_holder = 0;
var dataString = '&subscribe_mail=' + subscribe_mail;
$.ajax({
type: "POST",
url: "ajax_subscribe.php",
data: dataString,
datatype: "json",
success: function(response) {
console.log(response);
if(response!= '')
{
$('.error_message').html(subscribe_mail + ' is already Exists.');
return true;
} else {
$('.error_message').html('Thanks For subscription!');
return false;
}
}
});
$("#subscribe_form")[0].reset();
return false;
});
});
And php file code is:
<?php error_reporting('E_ALL ^ E_NOTICE'); include('config.php');if($_POST) { $subscribe_mail = $_POST['subscribe_mail'];
$date = date('Y-m-d');
$q = mysql_query("select * from signups where signup_email_address='".$subscribe_mail."' ") or die(mysql_error());
$n = mysql_fetch_row($q);
if( $n>0 )
{
echo 'Already Exists';
}
else
{
$insert = mysql_query("insert into signups(signup_email_address,signup_date) values('$subscribe_mail','$date')") or die(mysql_error());
$from = 'sunshine.kapoor270#gmail.com';
$to = $subscribe_mail;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "From: " . $from . "\r\n"; // Sender's E-mail
$headers .= "Reply-to: " . $from . "\r\n";
$headers .= "Return-Path: $from\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$subject = "Thanks for Subscription";
$message = "Subscription email id : ".$subscribe_mail." ";
$sentmail = mail($to,$subject,$message,$headers);
$sentmail = mail($from,$subject,$message,$headers);
} } ?>
Only
if(response!= ''){$('.error_message').html(subscribe_mail + ' is already Exists.'); return true; }
this condition is working. its not going to else part if response is blank.
It depends on what you send back in your response when the user does not exist in database.
You can change the condition to:
if (!$.trim(response)){......
if the response is null or empty.
You should maybe delete your final ?> in your PHP-files because you can omit this. Those and the lines after the closing PHP-Tag are responsible for additional empty-chars/enters which make calinaadi´s answer a good one.
And you should check your includes for the same behaviour.
I would never check on nothing or empty strings and thatwhy reverse your if:
if(str.trim(response) == 'Already Exists') {
$('.error_message').html('Thanks For subscription!');
return false;
} elseif(str.trim(response) == 'New User') {
return true;
} else {
$('.error_message').html(subscribe_mail + ' is some strange unknown Stringoutput.');
return false;
}

Php ajax just want to display error message only form submit

After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});

Why is my php email script sending an email to my spam not in my inbox

Here is my php code below. When I click "send email" button it works fine. But it doesn't appear to my Inbox. It was routed to Spam folder:
<?php
function sendmail(){
$message = $_POST['message'];
$email = $_POST['email'];
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$to = 'mpylla#gmail.com';
$subject = 'From :'.$email;
$message1 = 'From: '.$name."\nEmail: ".$email."\nMessage: ".$message;
mail($to, $subject, $message1);
}
sendmail();
?>
and this ajax script is in my HTML code:
$("#submit").click(function(e) {
var name = $("#name").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var message = $("#message").text();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(email)) {
alert('Ju lutem shkruan nje e-mail valide');
return false;
}
if (email.length == 0) {
alert("Email duhet te shenohet");
return false;
}
if (name.length == 0) {
alert("Emri duhet te shenohet");
return false;
}
if (lastname.length == 0) {
alert("Mbiemri duhet te shenohet");
return false;
}
if (message.length == 5) {
alert("Mesazhi duhet te shenohet");
return false;
} else {
$.ajax({
type: "POST",
url: "mail.php",
data: $("#myform").serialize(),
success: function(response) {
$("#sukses").fadeIn('slow');
setTimeout(function() {
$("#sukses").fadeOut('slow');
document.getElementById('myform').reset();
}, 100);
clearInterval();
}
});
}
e.preventDefault();
e.stopPropagation();
});
This is usually down to the content of the email itself and the type of mailbox you are sending the email to.
Each have various spam filters in place to restrict malicious emails. Take a look at this for some tips to help you.

Manually sending a post in PHP

I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));

Categories