Just another silly question from the beginner. I have this function:
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
date = $('#date').val(),
message = $('#message').val(),
data_html,
success = $('#success');
if(name == "")
$('#name').val('Please enter your name.');
if(phone == "")
$('#phone').val('Please enter your phone number.');
if(date == "")
$('#date').val('Please enter a date and time.');
if(email == ""){
$('#email').val('Your email is required.');
}else if(reg.test(email) == false){
$('#email').val('Invalid Email Address.');
}
if(message == "")
$('#message').val('Message is required.');
if(message != "" && name != "" && reg.test(email) != false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&phone="+ phone + "&date="+ date;
//alert(data_html);
$.ajax({
type: 'POST',
url: '../contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#date').val('');
$('#message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>NOT</strong> sent! Please try again later. </div>') ;
}
}
});
}
return false;
});
});
And I have created this PHP which may be wrong so please do not judge me... I am still learning :) I am a total beginner to this so please do not give me a hard time :)
<?php
$to = 'dvvsfb1#gmail.com';
$subject = 'Request a Booking';
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Name',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email address',
'val' => $_POST['email']
),
2 => array(
'text' => 'Phone',
'val' => $_POST['phone']
),
3 => array(
'text' => 'Date & Time',
'val' => $_POST['date']
),
4 => array(
'text' => 'Message',
'val' => $_POST['message']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
ini_set("SMTP","aspmx.l.google.com");
$headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=utf-8\r\n";
$headers .= "From: \"" . $name . "\" \r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$message = utf8_decode($message);
mail($to, $subject, $message, $headers);
?>
I am keep getting error message that message is not sent. It doesn't connect with my PHP i think. Any advice?
You are not "answering" anything from your PHP file. Try replacing your "mail()" call with this:
if (mail($to, $subject, $message, $headers)) {
echo 'sent';
} else {
echo 'not sent';
}
In the ajax success callback, you are checking for
if (msg == 'sent')
where msg is the response response of the ajax request.
But in your php file, you are not sending any response. Try,
$status = mail($to, $subject, $message, $headers);
echo $status ? 'sent' : 'failed';
And in the Ajax success callback,
if($.trim(msg) == 'sent') {
//some code
}
Related
I have a contact form with the following ajax and php code:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("mybtn").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "t", _("t").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "mail.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("my_form").innerHTML = '<h2>Thanks '+_("n").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
PHP code of mail.php:
<?php
if( isset($_POST['n']) && isset($_POST['e']) && isset($_POST['t']) && isset($_POST['m']) ){
$n = $_POST['n']; // HINT: use preg_replace() to filter the data
$e = $_POST['e'];
$t = $_POST['t'];
$m = nl2br($_POST['m']);
$to = "myemail#mydomain.com";
$from = $e;
$subject = 'Contact Form Message';
$message = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <br><b>Telephone:</b> '.$t.' <p>'.$m.'</p>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}
?>
It was working fine but I just now checked and when I click on Submit button, the PHP code is printed out. It does not send the email to my mailbox containing all the information. is there anything wrong with this code? Or can I be doing this is a simpler way?
I do not have much background in PHP or Ajax.
Here is textboxes I am trying to send with email.
Please help me with the code.The textboxes are dynamic
HTML
Flavor<input class="textbox" type='text' id="fl" name="flav[]" value=""/></label></br>
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_btn").click(function() {
var str = new Array();
$("input[name='flav[]']").each(function(){
str.push($(this).val());
});
alert(str);
var proceed = true;
if(str==""){
$('input[name=flav]').css('border-color', 'red');
proceed = false;
}
if(proceed)
{
//data to be sent to server
post_data={'userData':str};
$.post('mail.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('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input").keyup(function() {
$("#contact_form input").css('border-color', '');
$("#result").slideUp();
});
});
</script>
PHP
<?php
if($_POST)
{
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);
}
if(!isset($_POST["userData"]))
{
}
foreach($_POST as $key=> $value)
{
$message .= $key .":".$value."<br>";
}
$headers = "From: " . $user_Email . "\r\n";
$headers .= "Reply-To: ". $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, $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);
}
}
?>
Kindly help me with this.
How can I recieve all the values entered via message?
I have edited the code
Looks like you will get text with 'Array' in it, to fix it change
foreach($_POST as $key=> $value)
{
$message .= $key .":".$value."<br>";
}
to
foreach($_POST[userData] as $key=> $value)
{
$message .= $key .":".$value."<br>";
}
(This will only work one level down in your array) or replace it with:
$message = print_r($_POST, true);
from Store print_r result into a variable as a string or text to show the full depth of the array
I want to go directly to my problem: My application shows data from an mysql database and the user can select those items and save them into an javascript list. After he has selected his items we want that he write his name in an inputfield and with the click on an button the "javascript-list" (contains only strings) should be send to our mailForm.php via post & ajax.
The problem is that our mailForm.php works perfectly fine (trying to access via Java and sending Post data) but we are not able to post the data via ajax and javascript (have a look:)
mailForm.php
<?
if ($_POST) {
$message = "";
while (list ($key, $val) = each ($_POST)) {
if ($key == "mailAn") {
$mymail = $val;
} elseif ($key == "subject") {
$subject = $val;
} elseif ($key == "mailVon") {
$email = $val;
} elseif ($key == "message") {
$message = $val;
}
}
//array_walk ($_POST, "GetValues");
if (mail($mymail,$subject,$message,"From: $email")) {
header ("");
} else {
header ("Location: form_notok.htm");
//echo "Fehler beim Senden des Formulars!";
}
}
?>
As you can see wie have 4 keys (mailAn, subject, mailVon, message).. Any idea how this goes via js/jquery? (getting the Strings (javascriptlist) as message and the name (from inputfield) into mailVon)
Javascript:
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val(); //Inputfield with Name
var email = $("#email").val(); // Inputfield with email
var text = $("#text").val(); //should be list
var dataString = 'mailVon=' + name + '&mailAn=' + email + '&message=' + text;
$.ajax({
type: "POST",
url: "./mailForm.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
return false;
});
EDIT:
I now added the subject post param:
var dataString = 'mailVon=' + name + '&subject' + 'Test via javascript' + '&mailAn=' + email + '&message=' + text;
I still get an success message but no mail...
I would setup some echos and debug it with firebug.
if (isset($_POST['mailAn'])){
echo "Phase 1";
foreach($_POST as $key => $value)
{
switch ($key){
case "mailAn":
$mymail = $value;
echo "Phase 2";
break;
}
}
}else{
echo "FAILED";
}
I would add headers to the mail function.
`
<?
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: ' . $to . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$headers .= 'Cc: ' . "\r\n";
$headers .= 'Bcc: ' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
`
The code above works perfectly fine - problem was the settings of the test host we used. Using our business webspace it will work. Good Look.
MailForm.php
<?
if ($_POST) {
$message = "";
while (list ($key, $val) = each ($_POST)) {
if ($key == "mailAn") {
$mymail = $val;
} elseif ($key == "subject") {
$subject = $val;
} elseif ($key == "mailVon") {
$email = $val;
} elseif ($key == "message") {
$message = $val;
}
}
//array_walk ($_POST, "GetValues");
if (mail($mymail,$subject,$message,"From: $email")) {
header ("");
} else {
header ("Location: form_notok.htm");
//echo "Fehler beim Senden des Formulars!";
}
}
?>
JavaScript with fixed mail & javascript-list as dataString:
// Contact Form
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = 'your#email.com';
var message = '';
for (var i = 0; i < musicList.length; i++) {
message += musicList[i];
if(i < (musicList.lenght-1)){
message += ', ';
}
}
var dataString = 'mailVon=' + name + '&subject=' + 'Betreff: Music' + '&mailAn=' + email + '&message=' + message;
$.ajax({
type: "POST",
url: "./mailForm.php",
data: dataString,
success: function(data) {
if(data.status == 'success')
$('.success').fadeIn(1000);
else if(data.status == 'error')
$('.error').fadeIn(1000);
}
});
return false;
});
Hope it will help someone else too
-Domi
I'm using ajax contact form:
jQuery(document).ready(function () {
// Comment or uncomment the result you want.
// Currently, shake on error is enabled.
// When a field is left blank, jQuery will shake the form
/* Begin config */
// var shake = "Yes";
var shake = "No";
/* End config */
$('#message').hide();
// Add validation parts
$('#contact input[type=text], #contact input[type=number], #contact input[type=email], #contact input[type=url], #contact input[type=tel], #contact select, #contact textarea').each(function () {
$(this).after('<mark class="validate"></mark>');
});
// Validate as you type
$('#email').focusout(function () {
if (!$(this).val() || !isEmail($(this).val())) $(this).addClass('error').parent().find('mark').removeClass('valid').addClass('error');
else $(this).removeClass('error').parent().find('mark').removeClass('error').addClass('valid');
});
$('#submits').click(function () {
$("#message").slideUp(200, function () {
$('#message').hide();
// Kick in Validation
$('#email').triggerHandler("focusout");
if ($('#contact mark.error').size() > 0) {
if (shake == "Yes") {
$('#contact').effect('shake', {
times: 2
}, 75, function () {
$('#contact input.error:first, #contact textarea.error:first').focus();
});
} else $('#contact input.error:first, #contact textarea.error:first').focus();
return false;
}
});
});
$('#contactform').submit(function () {
if ($('#contact mark.error').size() > 0) {
if (shake == "Yes") {
$('#contact').effect('shake', {
times: 2
}, 75);
}
return false;
}
var action = $(this).attr('action');
$('#submits')
.after('<img src="/system/cms/themes/default/views/partials/assets/ajax-loader.gif" class="loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
website: $('#website').val(),
kvk: $('#kvk').val(),
sending: $('#sending').val(),
webwinkel: $('#webwinkel').val(),
pakketten: $('#pakketten').val(),
},
function (data) {
$('#message').html(data);
$('#message').slideDown();
$('#contactform img.loader').fadeOut('slow', function () {
$(this).remove()
});
$('#contactform #submits').attr('disabled', '');
if (data.match('success') != null) $('#contactform').slideUp('slow');
});
return false;
});
function isEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
function isNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
In some way it is not sending the email if i exclude this script the email script does work?
Ive tried everything but i can't get it to work , i think its strange because im using this script on more places and there its working :(...
anyone idea's ?
* Update Mail script *
<?php if (!isset($_SESSION)) session_start();
if(!$_POST) exit();
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$website = $_POST['website'];
$kvk = $_POST['kvk'];
$sending = $_POST['sending'];
$webwinkel = $_POST['webwinkel'];
$pakketten = $_POST['pakketten'];
$error = '';
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
$address = "email#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'Nieuwe Aanmelding';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "Er is een nieuwe aanmelding binnen gekomen:\n\n" . PHP_EOL . PHP_EOL;
$e_name = "Name: $name \n\n";
$e_email = "Email: $email \n\n";
$e_phone = "Tel: $phone \n\n";
$e_kvk = "KVK: $kvk \n\n";
$e_website = "Website: $website \n\n";
$e_sending = "Verzending nu: $sending \n\n";
$e_winkel= "Webwinkel: $webwinkel \n\n";
$e_pakketten= "Paketten per maand: $pakketten \n \n";
$msg = wordwrap($e_body . $e_name . $e_email . $e_website . $e_phone . $e_kvk . $e_sending . $e_winkel . $e_pakketten,70);
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<div class='span12'>";
echo "<div class='span4'></div>";
echo "<div class='span6'>";
echo "<div id='success_page'>";
echo "<h1 style='color:white'>Uw aanmelding is verzonden.</h1>";
echo "<p style='color:white'>Bedankt <strong>$name</strong>, U wordt zo spoedig mogelijk geholpen.</p>";
echo "</div>";
echo "</div>";
} else {
echo 'ERROR!';
}
}
?>
Resolved
Guys,
Thanks for the quick response.
This is the new jquery ive just downloaded and its working now.
$('#contactform').submit(function(){
if ($('#contact mark.error').size()>0) {
if(shake == "Yes") {
$('#contact').effect('shake', { times:2 }, 75);
}
return false;
}
var action = $(this).attr('action');
$('#submit')
.after('<img src="assets/img/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, $('#contactform').serialize(),
function(data){
$('#message').html( data );
$('#message').slideDown();
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#contactform #submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
return false;
});
There's so much wrong on so many levels, please first take a look at www.phptherightway.com.
After that, try and figure out if the form is being sent to the server (via the POST request method). If it's not, I'm guessing the form is returning false on the submit event, and that'll be the reason it's not working most likely.
I'm using jQuery's AJAX function to send a message from a contact form -
$('form button').click(function () {
$("input").removeClass("error");
$("textarea").removeClass("error");
var name = $("#name").val();
if (name == "" || name == "Name" || name == "Namn") {
$("#name").addClass("error");
$("#name").focus();
return false;
}
var email = $("#email").val();
if (email == "" || email == "Email" || email == "Epost") {
$("#email").addClass('error');
$("#email").focus();
return false;
}
var message = $("#message").val();
if (message == "") {
$("#message").addClass('error');
$("#message").focus();
return false;
}
// Non-verifying fields
var phone = $("input#phone").val();
// Gather data
var post = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// Disable form
var limit = document.forms[0].elements.length;
for (i = 0; i < limit; i++) {
document.forms[0].elements[i].disabled = true;
}
// Send data
$.ajax({
type: "POST",
url: "form_handler.php",
data: post,
success: function () {
$('div.contact form').animate({
opacity: 0.25
}, function () {
$('div.contact div.confirm').fadeIn(200);
});
},
error: function () {
$('div.contact form').animate({
opacity: 0.25
}, function () {
$('div.contact div.deny').fadeIn(200);
});
}
});
return false;
});
I know this is not the safest method considering I reveal the Mail file in my JS code but nevertheless I want this to work before I decide to try anything else. In my contact form I have the above fields (name, email, phone and message) and in "form_handler.php" the settings look like this -
<?php
header('Content-type: text/html; charset=UTF-8');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "staffan.estberg#gmail.com";
$subject = "Meddelande från x.se";
$body = "------------------------------------------------------------------------------------------------------------------------\n\n";
$body .= "Meddelande från $name:\n\n";
$body .= "$message\n\n";
$body .= "Avsändarens epost: $email\n";
$body .= "Avsändarens telefonnummer: $phone\n\n";
$body .= "------------------------------------------------------------------------------------------------------------------------";
$headers = "From: $email";
mail($to,$subject,$body,$headers);
?>
When I combine the scripts I manage to generate a message though it doesn't contain any form data. Have I missed out on something?
I think you'll actually want to pass a JSON array as the data parameter instead of the GET-style string.
Something like:
post = { 'name' : name, ... }