I'm scratching my head with this one at the moment - if any of you could help that'd be amazing. I have a site which uses AJAX to submit a contact form after a simple validation. All goes well, and the site acts as if the email has sent, but I'm not receiving any emails (yep I've triple checked, it's the right email address).
Here's what I'm working with:
HTML / PHP
<script type="text/javascript" language="javascript" src="js/contact.js"></script>
...
<section id="contact">
<span class="contact_results"></span>
<div class="form">
<input type="text" name="name" id="contactname" required value="<? echo $user_name ?>" placeholder="Your Name:" autocomplete="off">
<input type="email" name="email" id="email" required value="<? echo $email ?>" placeholder="Your E-Mail Address:" autocomplete="off">
<input type="phone" name="phone" id="phone" value="<? echo $phone ?>" placeholder="Your Telephone Number:" autocomplete="off">
<textarea name="message" id="message" required placeholder="Your Message:"><? echo $message ?></textarea>
<button type="submit" name="submit" id="contactbutton">Submit Form</button>
</div>
</section>
Contact.js
$(function() {
$("#contact button").click(function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact input[required=true], #contact textarea[required=true]").each(function(){
$(this).css('border-color','#EEE');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','#FC0'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','#FC0'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'user_phone' : $('input[name=phone]').val(),
'msg' : $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('contact_sendform.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<span class="error">'+response.text+'</span>';
}else{
output = '<span class="success">'+response.text+'</span>';
//reset values in all input fields
$("#contact input[required=true], #contact textarea[required=true]").val('');
$(".form").fadeOut(400); //hide form after success
}
$("#contact .contact_results").hide().html(output).slideDown(400);
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact input[required=true], #contact textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
contact_sendform.php
<?php
if($_POST)
{
$to_email = "xxxxxxxx#hotmail.com";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$user_phone = filter_var($_POST["user_phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_name)<3){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$user_name."\r\nEmail : ".$user_email."\r\nPhone Number : ". $user_phone ;
// Set Subject
$subject = "Ian! You've got a new message from ".$user_name;
//proceed with PHP email.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$user_email."\r\n".
'Reply-To: '.$user_email."\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$userArray = explode(' ', trim($user_name));
$output = json_encode(array('type'=>'message', 'text' => 'Thanks for getting in touch, '.$userArray[0] .'!'));
die($output);
}
}
?>
As I said - when the form is submitted with the correct data, it displays the confirmation message which only fires when $sendMail works - so I'm at a loss as to what's going wrong. Any insight or help would be majorly appreciated - thanks! :)
Related
When I press button Submit on form, reCAPTCHA will allow.
My form can send message without check I'm not a robot.
I don't know if it's about include ajax.
How can I use reCAPTCHA with my form contact?
Thank you very much for your time and assistance in this matter.
This my HTML code.
<form class="callus" onSubmit="return false">
<div id="result"></div>
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<textarea name="message" id="message"></textarea>
<div class="g-recaptcha" data-sitekey="XXXXX"></div>
<button id="submit_btn">Submit</button>
</form>
This is my Javascript.
jQuery(document).ready(function($){
$("#submit_btn").click(function() {
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
var post_data, output;
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_subject==""){
proceed = false;
}
if(user_message==""){
proceed = false;
}
if(proceed) {
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
$.post('email.php', post_data, function(response){
if(response.type == 'error') {
output = '<div class="alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert-success">'+response.text+'</div>';
$('.callus input').val('');
$('.callus textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
$(".callus input, .callus textarea").keyup(function() {
$("#result").slideUp();
});
});
email.php
<?php
if($_POST) {
$to_Email = 'demo#localhost.com';
$subject = 'New Contact Inquiry';
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
if(strlen($user_Name)<3) {
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) {
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail) {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
You have to validate captcha code at server side . Once you checked captcha it will give you captcha code.
var captchaCode = this.grecaptcha.getResponse();
Re-Captcaha provide callback functions like
<div class="g-recaptcha" id="headerCaptcha" data-callback="recaptchaCallbackHeader" data-expired-callback="recaptchaExpiryHeader" data-sitekey="xxx"></div>
You have to post this capthca code to backednd for validation inside recaptchaCallbackHeader. (refer below links for detail code)
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
Inresponse of this API you will get .
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are not a robot #$%K out</h2>';
} else {
echo '<h2>Thanks for posting comment.</h2>';
}
Remember recaptcha provide two types of keys.
Private key which is used on server side for validation of captcha code.
Site-key which is used to render captcha on clint side.
See how reCaptcah works
And Here to validate using PHP.
I'm looking for a way to redirect after submit depending on the echo
and i used the following code:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$body = 'name: ' .$name."\r\n";
$body = 'email: ' .$email."\r\n";
$body = 'message: ' .$message."\r\n";
$go = mail($to, $subject, $body, "From:<$email>");
if ($go) {
echo "Success";
}
else {
echo "error";
}
?>
<form action="index9.html" method="post" name="redirect" ></form>
<script> document.forms['redirect'].submit()</script>
but i have now two problems:
i am always getting "success" echo. even the client sending empty details.
i want to redirect to an error page with Javascript (if/else) and i don't now how.
BTW i am new in this field so:
I will appreciate your advise/help and be thankful.
You don't need javascript to achive this you can use pure php.
You can use error checking if a field is empty in the form as follows
validate.php
if(isset($_POST['submit'])){
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (isset( $nameErr) || isset($emailErr){
// you have a error
}
else {
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
....
This will check if "email" field is empty if it is it will promp a error "Email is required"
And then in your html you add the error
<form class="form-horizontal" action="validate.php" method="post">
<label for="email">Email: </label>
<input type="text" class="form-control input-sm" name="email">
<span class="error">* <br><?php echo $emailErr;?></span>
<input class="btn btn-info btn-lg" type="submit" name="submit" value="Submit">
</form>
Hope that helps
You seem to be on the right path, before throwing the arguments into the the mailer I would say you can do more sanity checking to make sure all values are entered, this way you avoid trying to send emails that you know will fail, so you fail early and notify the user, you may also see the error message the mail function returns in case of failure to make it easy to rectify any other issues by using the erorr_get_last() method.
echo error_get_last()['message'];
Note: php mail does not verify the headers given, so you have to be 100% sure it's clean and there are no possibilities for the user to inject their own headers, so make sure you sanitize that too.
Then to do redirecting you can just directly replace the echo "success" and echo "error" calls with your javascript part.
So the script would finally look like this:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$missingFieldCount = 0;
if(!isset($_POST['name'])) {
echo "Error: Name requried";
$missingFieldCount++;
}
if(!isset($_POST['email'])) {
echo "Error: Email required";
$missingFieldCount++;
}
if(!isset($_POST['message'])) {
echo "Error: message required";
$missingFieldCount++;
}
if($missingFieldcount > 0) {
echo "Please fill in the missing $missingFieldcount fields, then submit again";
} else {
$body = 'name: ' .$name."\r\n";
$body .= 'email: ' .$email."\r\n"; // Using .= to append instead of replace
$body .= 'message: ' .$message."\r\n";
$headers = "From:<$email>"; //Make sure $email is actually just an email address and not injected headers
$success = mail($to, $subject, $body, $headears);
if ($success) {
$redirectPage = "successPage.html"
} else {
$redirectPage = "errorPage.html"
echo "An error occured:";
//Don't show this to the user, but log it to file instead
//this is here only for demonstration
echo error_get_last()['message'];
}
echo "<form action="$redirectPage" method="post" name="redirect" ></form>";
echo "<script> document.forms['redirect'].submit()</script>";
}
}
?>
Tnq Guys for your answers.
finally i manged a perfect PHP form from all the information i get in this issue. no need Javascript to redirect TO 2 different pages:
1. Thank you page.
2. error page.
and the code is like this:
<?php
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$to = "mymail#gmail.com";
$subject = " New Client order ";
$errors = 0;
$body ="";
$body .="Name: ";
$body .=$name;
$body .="\n";
$body .="Email: ";
$body .=$email;
$body .="\n";
$body .="Message: ";
$body .=$message;
$body .="\n";
if(isset($_POST['submit'])) { // Checking null values in message.
$name = $_POST["name"]; // Sender Name
$email = $_POST["email"]; // Sender's email ID
$message = $_POST["message"]; // Sender's Message
if (empty($_POST["name"])){
$nameError = "Name is required";
$errors = 1;
}
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if (empty($_POST["message"])){
$messageError = "Message is required";
$errors = 1;
}
}
if($errors == 0){
$successMessage = mail($to, $subject, $body, "From: <$email>");
}
else {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.html\">";
}
if ($successMessage){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks.html\">";
}
?>
I have a comment system in which user comments and through ajax it validates the data and sent to .php page. The problem is it receives the status=1 but does not apply the else if Ajax code. I am stuck here. Any suggestions or help will be highly regarded.
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_comment").click(function() {
var proceed = true;
$(" #comment_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed)
post_data = {
'user_email' : $('input[name=email]').val(),
'pid' : $('input[name=productid]').val(),
'msg' : $('textarea[name=comment]').val()
};
$.post('comments.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}
else if(response.status && response.type != 'error')
{
output = '<div class="success">'+response.text+'</div>';
$(response.html).hide().insertBefore('#comment_form').slideDown();
$(" #comment_form textarea[required=true]").val('');
$("#comment_form #comment_body").slideUp();
}
$("#comment_form #comment_results").hide().html(output).slideDown();
}, 'json');
});
//reset previously set border colors and hide all message on .keyup()
$("#comment_form input[required=true], #comment_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Form
<?php
include "comment.php";
$comments = array();
$result = mysqli_query($con,"SELECT * FROM comments where product_id='$id' ORDER BY dt LIMIT 5");
while($row = mysqli_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<?php
}
}
?>
<div class="form-style" id="comment_form">
<div id="comment_results"></div>
<div id="comment_body">
<input type="hidden" name="email" id="email" value="<?php echo $email?>">
<input type="hidden" name="productid" id="productid" value="<?php echo $pid?>" />
<label for="field5"><span>Comment: <span class="required">*</span></span>
<textarea name="comment" id="comment" class="textarea-field" required="true"></textarea>
</label>
<label>
<span> </span><input type="submit" id="submit_comment" value="Submit"">
</label>
</div>
</div>
comment.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
$this->data = $row;
}
public function markup()
{ $d = &$this->data;
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
return '
<div class="comment">
<div class="name">'.$d['email'].'</div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
}
?>
comments.php
<?php
include("db/db.php");
include "comment.php";
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_email"], FILTER_SANITIZE_STRING);
$pid = filter_var($_POST["pid"], FILTER_VALIDATE_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$arr = array();
//additional php validation
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
mysqli_query($con,"INSERT INTO comments(email,body,product_id) values('$user_name','$message','$pid')");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$res=mysqli_query($con,$query);
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
if(!$res)
{
$output = json_encode(array('type'=>'error', 'text' => 'Cannot recieve your comment.'));
die($output);
}else{
$output= json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your review','status'=>1,'html'=>$insertedComment->markup()));
echo $output;
die($output);
}
}
?>
I have several checkboxes with identical names and using square brackets so to get array
<label>
<input type="checkbox" value="Tlocrt objekta" name="dokument[]" > Tlocrt objekta </input>
</label>
<label>
<input type="checkbox" value="Građevinska dozvola" name="dokument[]" > Građevinska dozvola </input>
</label>
<label>
<input type="checkbox" value="Glavni projekt" name="dokument[]" > Glavni projekt </input>
</label>
<label>
<input type="checkbox" value="Izvedbeni projekt" name="dokument[]" > Izvedbeni projekt </input>
</label>
<label>
<input type="checkbox" value="Elaborat legalizacije" name="dokument[]" > Elaborat legalizacije </input>
</label>
<label>
<input type="checkbox" value="Elaborat etažiranja" name="dokument[]" > Elaborat etažiranja </input>
</label>
<label>
<input type="checkbox" value="Projekt preuređenja" name="dokument[]" > Projekt preuređenja </input>
</label>
<label>
<input type="checkbox" value="Završno izvješće nadzornog inženjera" name="dokument[]" > Završno izvješće nadzornog inženjera </input>
I am trying to get values from checkboxes with this
var user_Docs = $("input:checkbox[name='dokument[]']:checked");
and pass them on to PHP with this
//data to be sent to server
post_data = {'name':user_Name, 'email':user_Email, 'telefon':user_Phone, 'objekt':user_Objekt, 'kvadratura':user_Kvadratura, 'god_izgradnje':user_Izgradnja, 'kat_cestica':user_Cestica, 'kat_opcina':user_Opcina, 'namjena':user_Namjena, 'napomena':user_Napomena, 'dokument[]':user_Docs};
This is my Javascript
$(document).ready(function() {
$("#submit_btn").click(function() {
//get input field values
var user_Name = $('input[name=name]').val();
var user_Email = $('input[name=email]').val();
var user_Phone = $('input[name=telefon]').val();
var user_Objekt = $('input[name=objekt]').val();
var user_Kvadratura = $('input[name=kvadratura]').val();
var user_Izgradnja = $('input[name=god_izgradnje]').val();
var user_Cestica = $('input[name=kat_cestica]').val();
var user_Opcina = $('input[name=kat_opcina]').val();
var user_Namjena = $('input[name=namjena]').val();
var user_Napomena = $('textarea[name=napomena]').val();
var user_Docs = $("input:checkbox[name='dokument[]']:checked");
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if(user_Name==""){
$('input[name=name]').css('border-color','red');
proceed = false;
}
if(user_Email==""){
$('input[name=email]').css('border-color','red');
proceed = false;
}
if(user_Phone=="") {
$('input[name=telefon]').css('border-color','red');
proceed = false;
}
if(user_Objekt=="") {
$('input[name=objekt]').css('border-color','red');
proceed = false;
}
if(user_Kvadratura=="") {
$('input[name=kvadratura]').css('border-color','red');
proceed = false;
}
if(user_Izgradnja=="") {
$('input[name=god_izgradnje]').css('border-color','red');
proceed = false;
}
if(user_Cestica=="") {
$('input[name=kat_cestica]').css('border-color','red');
proceed = false;
}
if(user_Opcina=="") {
$('input[name=kat_opcina]').css('border-color','red');
proceed = false;
}
if(user_Namjena=="") {
$('input[name=namjena]').css('border-color','red');
proceed = false;
}
/* if(user_Napomena=="") {
$('texarea[name=napomena]').css('border-color','red');
proceed = false;
} */
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'name':user_Name, 'email':user_Email, 'telefon':user_Phone, 'objekt':user_Objekt, 'kvadratura':user_Kvadratura, 'god_izgradnje':user_Izgradnja, 'kat_cestica':user_Cestica, 'kat_opcina':user_Opcina, 'namjena':user_Namjena, 'napomena':user_Napomena, 'dokument[]':user_Docs};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function() {
$("#contact_form input, #contact_form textarea").css('border-color','');
$("#result").slideUp();
});
});
this is my PHP
<?php
if($_POST)
{
$to_Email = "bla#bla.com"; //Replace with recipient email address
$subject = 'Poruka'; //Subject line for emails
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
$user_Docs = '';
if(isset($_POST['dokument']) && is_array($_POST['dokument']) && count($_POST['dokument']) > 0){
$user_Docs = implode('|', $_POST['dokument']);
}
//check $_POST vars are set, exit if any missing
//if(!isset($_POST["name"]) || !isset($_POST["email"]) || !isset($_POST["telefon"]) || !isset($_POST["objekt"]))
//{
//$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
//die($output);
//}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$user_Phone = filter_var($_POST["telefon"], FILTER_SANITIZE_STRING);
$user_Objekt = filter_var($_POST["objekt"], FILTER_SANITIZE_STRING);
$user_Kvadratura = filter_var($_POST["kvadratura"], FILTER_SANITIZE_STRING);
$user_Izgradnja = filter_var($_POST["god_izgradnje"], FILTER_SANITIZE_STRING);
$user_Cestica = filter_var($_POST["kat_cestica"], FILTER_SANITIZE_STRING);
$user_Opcina = filter_var($_POST["kat_opcina"], FILTER_SANITIZE_STRING);
$user_Namjena = filter_var($_POST["namjena"], FILTER_SANITIZE_STRING);
$user_Napomena = filter_var($_POST["napomena"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(!is_numeric($user_Phone)) //check entered data is numbers
{
$output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
die($output);
}
if(strlen($user_Objekt)<3) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short objekt! Please enter something.'));
die($output);
}
if(!is_numeric($user_Kvadratura)<0) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short kvadratura! Please enter something.'));
die($output);
}
if(!is_numeric($user_Izgradnja)<0) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short izgradnja! Please enter something.'));
die($output);
}
if(strlen($user_Cestica)<0) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short cestica! Please enter something.'));
die($output);
}
if(strlen($user_Opcina)<0) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short opcina! Please enter something.'));
die($output);
}
if(strlen($user_Namjena)<0) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short namjena! Please enter something.'));
die($output);
}
/* if(strlen($user_Napomena)<0) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short napomena! Please enter something.'));
die($output);
} */
// Construct email body
$body_message = 'Od: ' . $user_Name . "\r\n";
$body_message .= 'E-mail: ' . $user_Email . "\r\n";
$body_message .= 'Telefon: ' . $user_Phone . "\r\n";
$body_message .= 'Novi ili postojeći objekt: ' . $user_Objekt . "\r\n";
$body_message .= 'Kvadratni metri: ' . $user_Kvadratura . "\r\n";
$body_message .= 'Godina izgradnje: ' . $user_Izgradnja . "\r\n";
$body_message .= 'Kat. čestica: ' . $user_Cestica . "\r\n";
$body_message .= 'Kat. općina: ' . $user_Opcina . "\r\n";
$body_message .= 'Namjena: ' . $user_Namjena . "\r\n";
$body_message .= 'Napomena: ' . $user_Napomena . "\r\n";
$body_message .= 'Dodatni dokumenti: ' . $user_Docs . "\r\n";
$body_message .= 'Dodatni dokumenti: ' . $dokument . "\r\n";
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to_Email, $subject, $body_message .' -'.$user_Name, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
die($output);
}
}
?>
My form is working, but I am not getting the values from checkboxes in my email.
To be more precise i am trying to gather data from form and send an email containig same data. All data is in the email but the values of checkboxes are not displaying. Somehow i am not getting them. Can someone give me a hand with this, please?
I think you're looking into an AJAX form submission. Read examples like this one: Submitting HTML form using Jquery AJAX
Or it looks like there is no action for your form to be submitting anywhere. To pass it into $_POST, you need to have the tag say something like
That output.php is where $_POST will be filled.
serialize the form instead of manually creating the array to be passed.
http://jsfiddle.net/44H7b/
$("#form").submit(function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
the answer was serializing [link]http://api.jquery.com/serialize/
which means replacing this part of code
//data to be sent to server
post_data = {'name':user_Name, 'email':user_Email, 'telefon':user_Phone, 'objekt':user_Objekt, 'kvadratura':user_Kvadratura, 'god_izgradnje':user_Izgradnja, 'kat_cestica':user_Cestica, 'kat_opcina':user_Opcina, 'namjena':user_Namjena, 'napomena':user_Napomena, 'dokument[]':user_Docs};
with this one
post_data = $('form#yourForm').serialize();
well not exactly as is. I changed the ID and put my own Form ID
I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)
<?php
/*
* Contact Form Class
*/
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'sgg3590#rit.edu'; // 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(){
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>';
}
else
{
$this->response_status = 0;
$this->response_html = '<p>Sending failed</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();
?>
here is how I am calling it
BRUSHED.contactForm = function(){
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
$.ajax({
type: "POST",
url: "_include/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
}
And here is my form
<form id="contact-form" class="contact-form" action="#">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
</p>
<p class="contact-submit">
<a id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="response">
</div>
</form>
The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail)
I followed this code from a website and I Don't really understand whats wrong here.. :(
First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test#test.org but From: localhost.
Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:
<?php
try {
$to = 'user#test.org';
$subject = 'Mail Test';
$message = <<<TEXT
Mail request received
TEXT;
$message = str_replace("\n.", "\n..", $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Test Org. <webmaster#test.org>' . "\r\n" .
'Reply-To: webmaster#test.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
printf("Mail sent to " + $to);
} catch (Exception $e) {
printf("Error occured: " + $e);
}
?>
If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent#test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.
Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.
Thanks