How can I use reCAPTCHA with my form contact? - javascript

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.

Related

How to Redirect PHP form with Javascript depending on echo

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\">";
}
?>

Troubleshooting AJAX form submission

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! :)

How to include ordered products in email using php

I have a online shop that collects data and displays the product and price on the page. The customer then needs complete the form and mail delivery address to me. Everything is working fine, but i would like to include the product that have been ordered in the email that comes to me.
My view_cart.php looks like this
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="paypal-express-checkout/process.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
$ShippinCost = 150.00;
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal + $ShippinCost);
if ($subtotal > 1200) { $total = $subtotal;
}
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
echo 'Order Number:';
$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
echo $unique = $today . $rand;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '</form>';
}else{
echo 'Your Cart is empty';
}
?>
Then I have a simple HTML form that collects the info and sends it with ajax. This looks like this
<?php
error_reporting(-1);
ini_set('display_errors', 'on');
ini_set("SMTP", 'smtp.xxxxxxx');
ini_set("smtp_port", "25");
ini_set('sendmail_from','noreply#domain.com');
if($_POST)
{
$to_email = "sean#domain.co.za";"CC: info#domain.co.za "; //Recipient email, Replace with own email here
$from_email = "noreply#YOUR-DOMAIN.com"; //From email address (eg: no-reply#YOUR-DOMAIN.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);
$country_code = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT);
$phone_number = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_name)<4){ // 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(!filter_var($country_code, FILTER_VALIDATE_INT)){ //check for valid numbers in country code field
$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in country code'));
die($output);
}
if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
die($output);
}
if(strlen($subject)<3){ //check emtpy subject
$output = json_encode(array('type'=>'error', 'text' => 'Subject is required'));
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 : (".$country_code.") ". $phone_number ;
### Attachment Preparation ###
$file_attached = false;
if(isset($_FILES['file_attach'])) //check uploaded file
{
//get file details we need
$file_tmp_name = $_FILES['file_attach']['tmp_name'];
$file_name = $_FILES['file_attach']['name'];
$file_size = $_FILES['file_attach']['size'];
$file_type = $_FILES['file_attach']['type'];
$file_error = $_FILES['file_attach']['error'];
//exit script and output error if we encounter any
if($file_error>0)
{
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder" );
$output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
die($output);
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
//now we know we have the file for attachment, set $file_attached to true
$file_attached = true;
}
if($file_attached) //continue if we have the file
{
# Mail headers should work with most clients
$headers = "MIME-Version: 1.0\r\n";
$headers = "X-Mailer: PHP/" . phpversion()."\r\n";
$headers .= "From: ".$from_email."\r\n";
$headers .= "Subject: ".$subject."\r\n";
$headers .= "Reply-To: ".$user_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=".md5('boundary2')."\r\n\r\n";
$headers .= "--".md5('boundary2')."\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
$headers .= $message_body."\r\n\r\n";
$headers .= $obj."\r\n\r\n";
$headers .= $product_code."\r\n\r\n";
$headers .= $cart_itm."\r\n\r\n";
$headers .= $total."\r\n\r\n";
$headers .= "--".md5('boundary2')."--\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: ".$file_type."; ";
$headers .= "name=\"".$file_name."\"\r\n";
$headers .= "Content-Transfer-Encoding:base64\r\n";
$headers .= "Content-Disposition:attachment; ";
$headers .= "filename=\"".$file_name."\"\r\n";
$headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
$headers .= $encoded_content."\r\n";
$headers .= "--".md5('boundary1')."--";
}else{
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\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{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
die($output);
}
}
?>
I have searched the site but cant find my solution. Please can someone point me in the right direction

not getting and passing values in jquery from from form checkbox to $_POST

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

Can't send Email using PhP

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

Categories

Resources