Submision via AJAX call not working - php

I'm trying to submit an eMail via AJAX, but for some reason, nothing is working. I have counter and counter checked that the files (<script src="mail.js"></script>, jquery and url: "sendmail.php") are well mapped.
The page reloads, and nothing is submitted. I do not want any page reloads in the first place, the reason I am using AJAX.
What am I doing wrong? Thank you all in advance.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="mail.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<!-- Content -->
<div class="container">
<div class="row">
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="" method="post">
<input type="text" name="tasktitle" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
</div>
</div>
</body>
</html>
mail.js
$(document).ready(function(){
$('.btn').click(function(e){
var current_time = 123;
var tasktitle = $("input#tasktitle").val();
var dataString = 'current_time='+ current_time + '&tasktitle=' + tasktitle;
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
$('.title').html("");
$('.success-message').html("✓ Logged!")
.hide()
.fadeIn(1500, function() {
$('success-message').append("");
});
}
});
return false;
});
});
sendmail.php
I have already created the directory ccts for the file to be written into.
<?php
$tasktitle = $_POST['tasktitle'];
setlocale(LC_TIME, "fi_FI");
date_default_timezone_set("Europe/Helsinki");
$date = strftime("%Y-%m-%d-%A");
$timesaved = strftime("%H:%M:%S");
$elapsedtime = $_POST['current_time'];
$file = "ccts/".$date.".txt";
$cont = 'time submitted: '.$timesaved.' - time elapsed: '.$elapsedtime.' - Email Address http://onvill.com/ : '.$tasktitle.''. "n";
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'Contact.#site.com';
$subscriber_email = ($_POST['tasktitle']);
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$f = fopen ($file, 'w');
fwrite($f, $cont);
fclose($f);
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
}
}
?>
UPDATE
I get the error:
Uncaught ReferenceError: $ is not defined(anonymous function) # mail.js:1

HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="mail.js"></script>
</head>
<body>
<!-- Content -->
<div class="container">
<div class="row">
<div class="span12 subscribe">
<h3>Subscribe to our newsletter</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" action="" method="post">
<input type="text" name="tasktitle" placeholder="Enter your email...">
<button type="submit" class="btn">Subscribe</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
</div>
</div>
</body>
</html>
in mail.js
$(document).ready(function(){
$('.btn').click(function(e){
var current_time = 123;
var tasktitle = $("input#tasktitle").val();
var dataString = 'current_time='+ current_time + '&tasktitle=' + tasktitle;
$.ajax({
type: "POST",
url: "sendmail.php",
data: $("form.form-inline").serialize(),
dataType:'json',
success: function(data) {
if(data.type=="success")
{
$('.title').html("");
$('.success-message').html("✓ Logged!")
.hide()
.fadeIn(1500, function() {
$('success-message').append("");
});
}
else
{
alert(data.message);
}
}
});
return false;
});
});
in PHP file
<?php
$response=array();
if(!empty($_POST))
{
$tasktitle = $_POST['tasktitle'];
setlocale(LC_TIME, "fi_FI");
date_default_timezone_set("Europe/Helsinki");
$date = strftime("%Y-%m-%d-%A");
$timesaved = strftime("%H:%M:%S");
$elapsedtime = $_POST['current_time'];
$file = "ccts/".$date.".txt";
$cont = 'time submitted: '.$timesaved.' - time elapsed: '.$elapsedtime.' - Email Address http://onvill.com/ : '.$tasktitle.''. "n";
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'Contact.#site.com';
$subscriber_email = ($_POST['tasktitle']);
if(!isEmail($subscriber_email)) {
$response['type'] = 'error';
$response['message'] = 'Insert a valid email address!';
}
else {
$f = fopen ($file, 'w');
fwrite($f, $cont);
fclose($f);
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
$response['type'] = 'success';
$response['message'] = 'Mail sent successfully!';
}
}
else
{
$response['type'] = 'error';
$response['message'] = 'Invalid post request';
}
ob_clean();
echo json_encode($response);

just import jquery cdn before your mail.js
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="mail.js"></script>
jquery must be loaded before calling it.

This is because the sequence:
<script src="mail.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
your mail.js is on top and jquery after that. But in mail.js you are using $, and $ is not available there. Change the sequence and try again.

Related

Attaching an uploaded file as an attachment In PHPmailer and Jquery

I have created a web form where people can enter registration information and upload an image to our server. I can get their name, email and message but I can't figure out how to get the uploaded file. I'd like to have the page not reload so that's why I'm using JQuery. It mostly works but I can't get the uploaded file to be recognized in the POST data or the FILES data. The form and processor page are located in the same directory and the image get placed in a subfolder called uploads. Here is what I have so far which does not work for attaching image. I believe the problem is in the JavaScript file where I define the var photoFile = $('#submitForm #photoFile').val(); What is the correct way to declare the uploaded file?
Here's the HTML form:
form action="../inc/sendPhotoEmail.php" name="submitForm" id="submitForm" method="post"
enctype="multipart/form-data">
<label for="submitName">Name <span class="required">*</span></label>
<input name="submitName" type="text" id="submitName" size="35" value="" />
<label for="submitEmail">Email <span class="required">*</span></label>
<input name="submitEmail" type="text" id="submitEmail" size="35" value="" />
<label for="submitMessage">Tell us what you want fixed <span class="required">*</span></label>
<textarea name="submitMessage" id="submitMessage" rows="10" cols="50" ></textarea>
<label for="attach_photo">Attach Your Photo<span class="required"/>*</span></label>
<input type="file" name="photoFile" id="photoFile" accept="image/*"/>
<button class="submit" name="submitFormSubmit" value="Submit">Submit</button>
<span id="image-loader"><img src="images/loader.gif" alt="" /></span>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>
The javascript:
jQuery(document).ready(function() {
$('form#submitForm button.submit').click(function() {
$('#image-loader').fadeIn();
var submitName = $('#submitForm #submitName').val();
var submitEmail = $('#submitForm #submitEmail').val();
var submitMessage = $('#submitForm #submitMessage').val();
var photoFile = $('#submitForm #photoFile').val();
var data = 'submitName=' + submitName + '&submitEmail=' + submitEmail +
'&submitMessage=' + submitMessage + $photoFile='+ photoFile;
$.ajax({
type: "POST",
url: "inc/sendPhotoEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#submitForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
And the PHP file:
<?php
require_once('class.phpmailer.php');
$ourEmail = "repair#myemail.net";
$target_dir = "../uploads/";
if($_POST) {
$name = trim(stripslashes($_POST['submitName']));
$email = trim(stripslashes($_POST['submitEmail']));
$emailMessage = trim(stripslashes($_POST['submitMessage']));
$image_attachment = $_POST["photoFile"]; // <---- this doesn't print anything
$targetFile = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "targetFile = ". $targetFile . "<br/>"; // <-- this only prionts the subdirectory
move_uploaded_file($_FILES["photoFile"]["tmp_name"],$target_dir.$_FILES["photoFile"]["name"]);
echo "Uploaded File :".$_FILES["photoFile"]["name"]. "<br/>";
$target_file = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "target_file = ". $target_file . "<br/>";
$mail = new PHPMailer(); //Create a new PHPMailer instance
$mail->isSendmail(); // Set PHPMailer to use the sendmail transport
// Set Message
$mail->setFrom($email, $name); //Set who the message is to be sent from
$mail->addReplyTo("replyto#example.com", "First Last"); //Set an alternative reply-to address
$mail->addAddress($ourEmail, "Figley T. Whitesides"); //Set who the message is to be sent to
$mail->Subject = "Repair Form Submission"; //Set the subject line
$mail->WordWrap = 80;
$mail->msgHTML($emailMessage); //Create message bodies and embed images
$mail->addAttachment($target_file); //Attach an image file
if (!$error) {
//send the message, check for errors
if (!$mail->send()) {
$mail->ErrorInfo;
} else {
$response = "Photo sent!";
} // end if - no validation error
}
else{
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
$response .= (isset($error['attachment'])) ? $error['attachment'] . "<br />" : null;
echo $response;
} // end if - there was a validation error
}
?>
});
You can't upload data and files with one form using ajax, but try this code,
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});

Contact form don't send well

I have a problem when sending data to the contact form. Data is sent to e-mail only if you click many times, but if you tab to move to the button and press enter data is sent immediately. But still fall into the spam.
HTML
<div id="f1" class="contact_wrapper">
<form>
<div id="r2"></div>
<input type="text" name='rname' id="names" class="name" placeholder="Ваше имя">
<input type="email" name='email' id="eml" class="email" placeholder="Ваше Email">
<input type="text" name='subject' id="phon" class="contact_number" placeholder="Контактный телефон">
<textarea name="message" id="masage" cols="30" rows="10"></textarea>
<input name="" id="button" type="button" value="Отправить" class="submit" onclick="mail2('Радиус-01 Оформить заявку - последняя форма','names','eml','phon','masage','f1','r2')">
</form>
</div>
AJAX
<script>
function mail2(subject,names,eml,phon,masage,f,rr){
var names = document.getElementById(names).value;
var eml = document.getElementById(eml).value;
var phon = document.getElementById(phon).value;
var masage = document.getElementById(masage).value;
var frt = document.getElementById('generator_konr').value;
var params = {subject:subject,names:names,eml:eml, phon:phon,masage:masage,kon:frt};
$.ajax({
type: "POST",
url: "mail2.php",
data: params,
success: function(data){
$('#ertretgfdg').html(data).fadeIn("slow");
}
});
}
</script>
mail2.php
<?
### Referals script start
$debug=0;
function writelog($s) {
global $lf,$debug;
if ($debug)
fputs($lf,"$s\n");
}
if ($debug)
$lf=#fopen(dirname(__FILE__).'/'.'debug.log','a');
$t=date('Y-m-d H:i:s');
$utm='нет';
$term='нет';
$ip=$_SERVER['REMOTE_ADDR'];
$utmdata='';
writelog("Session started (zakaz.php) at '$t', IP='$ip'");
writelog("REQUEST: ".print_r($_REQUEST,true));
if (isset($_COOKIE['utmdata'])) {
writelog("Found saved cookie UTMdata");
$utmdataexp=explode('&',$_COOKIE['utmdata']);
if (count($utmdataexp)>=2 && !empty($utmdataexp[0]) && !empty($utmdataexp[1])) {
$t=$utmdataexp[0];
$utm=$utmdataexp[1];
$term=isset($utmdataexp[2]) ? $utmdataexp[2] : 'нет';
$utmdata=$t.'&'.$utm.'&'.$term;
}
}
writelog("UTMdata is '$utmdata'");
### Referals script end
$phon = $_POST['phon'];
$names = $_POST['names'];
$subject = $_POST['subject'];
$kon = $_POST['kon'];
$eml = $_POST['eml'];
$masage = $_POST['masage'];
if ($names=='' or $names=='Введите ваше имя') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите свое имя");</script>';
exit;
}
if ($phon=='' or $phon=='Ваш телефон' or $phon=='Введите номер телефона') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите номер телефона");</script>';
exit;
}
if ($eml=='' or $eml=='Ваш email' or $eml=='Введите ваш email') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваш email");</script>';
exit;
}
if ($masage=='' or $masage=='Ваше сообщение' or $masage=='Введите ваше сообщение') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваше сообщение");</script>';
exit;
}
$er=null;
if ($subject=='Выбран конкретный генератор') {
$ert='Генератор: '.$kon.'<br/>';
}
$body ='
По вопросу: '.$subject.'<br/>
'.$ert.'
Имя: '.$names.'<br/>
Телефон: '.$phon.'<br/>
Мыло: '.$eml.'<br/>
Сообщение: '.$masage.'<br/>
Рекламная площадка:</b> '.$utm.'<br />
Ключевое слово: '.$term.'<br />
';
$email='myemail#gmail.com';
$headers = "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: <".$em.">\r\n";
if (mail($email, $subject_t, $body, $headers)) {
echo '<script>$().toastmessage(\'showSuccessToast\', "Сообщение успешно отправлено");</script>
<script>$(".header .sform").delay( 2000 ).slideToggle();</script>';
exit;
} else {
echo '<script>$().toastmessage(\'showErrorToast\', "Ошибка, повторите попытку");</script>';
exit;
}
?>
<!--

PHP/Ajax contact form clear input fields only if success

I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!
Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});

AJAX with PHP self-submitting form and validation

I've been learning PHP via the book "PHP Solutions" by David Powers, which has a contact form with basic validation/error handling and input sanitization I would like to use without refreshing the page.
I'm testing this locally with XAMPP, and using the php form itself works perfectly: error messages display correctly, and if the form is successfully submitted, a thank you page is displayed and the form is delivered as an email to my test email address.
Now I need the form to submit and display error messages with AJAX. I've read many posts on accomplishing this, but I've been unsuccessful in implementing this. I've tried both the jQuery $.ajax and $.post methods - if the fields are all filled, the success message displays, but the message is not sent.
My guess is that javascript and php arrays are structured differently, but don't know how to reconcile this. I'm not even sure what the php processing scripts are getting/sending, if anything. How can I get this form to submit without refreshing the page, but still using the php scripts for server-side validation?
To simplify, I've stripped everything else from my page (and put all files in the same folder), except for the form: php, html, and the jQuery/AJAX I can't figure out.
Hope this makes sense. My 4 files:
mySite.js (the jQuery/AJAX I'm having trouble with...):
mySite = {
jsFormSubmission : function() {
$("#feedback").submit(function(event){
event.preventDefault();
var errorMsg = "<p class=\"errorBox\">Please fix the item(s) indicated.</p>";
var successMsg = "<p class=\"messageBox\">Thanks for the submission, your message has been sent.</p>";
var myObject = {
name : $("#name").val(),
email : $("#email").val(),
comments : $("#comments").val()
};
var ajaxData = JSON.stringify(myObject);
$.ajax({
type: 'POST',
url: 'form.php',
data: ajaxData,
success: function(data){
$(".formResult").html(successMsg);
},
error: function(http) {
$(".formResult").html(errorMsg);
alert(http.responseText);
}
});
});
}
};
The form (contact.php):
<?php include("form.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src=" mySite.js"></script>
<script type="text/javascript">
$(document).ready(function() {
mySite.jsFormSubmission();
});
</script>
</head>
<body>
<div id="contact">
<p class="formResult"></p>
<?php $errorForm = (($_POST && $suspect) || ($_POST && isset($errors['mailfail'])));
$errorTag = $missing || $errors;
if ($errorForm || $errorTag) { ?>
<p class="errorBox">
<?php } ?>
<?php if ($errorForm) { ?>
Sorry, your message could not be sent. Please try again later.
<?php } elseif ($errorTag) { ?>
Please fix the item(s) indicated.
<?php } ?>
<?php if ($errorForm || $errorTag) { ?>
</p>
<?php } ?>
<form id="feedback" method="post" action="">
<div class="tag">
<label id="lblName" for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your name</span>
<?php } ?>
</label>
<input name="name" id="name" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblEmail" for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span style="color:red; font-weight:bold;">Invalid email address</span>
<?php } ?>
</label>
<input name="email" id="email" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblComments" for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your message</span>
<?php } ?>
</label>
<textarea name="comments" id="comments" cols="60" rows="8"><?php
if ($missing || $errors) {
echo htmlentities($comments, ENT_COMPAT, 'UTF-8');
} ?></textarea>
</div>
<p>
<input name="send" id="send" type="submit" value="Send message">
</p>
</form>
</div>
</body>
</html>
form.php (included at top of contact.php):
<?php
$name = '';
$email = '';
$comments = '';
$required = '';
$errors = array();
$missing = array();
// check if the form has been submitted
if (isset($_POST['send'])) {
//email processing script
$to = 'johntest2#localhost';
$subject = 'Website contact form';
//list expected fields
$expected = array('name', 'email', 'comments');
// set required fields
$required = array('name', 'email', 'comments');
$headers = "From: Website Contact Test<johntest1#localhost>\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
require('processmail.php');
if ($mailSent) {
header("Location: thankYou.php#main");
$messageConfirm = true;
exit;
}
}
?>
processmail.php (validation scripts - included in form.php):
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
// function to check for suspect phrases
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
}
// validate the user's email
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) {
// initialize the $message variable
$message = '';
foreach($expected as $item) {
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item).": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
There's a few ways that you can get the error to display from the PHP side. You can throw an exception, which I wouldn't recommend, or use a header:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
In your AJAX call, use the jQuery error callback:
$.ajax({
url: //url,
data: //data,
success: function (data) { //show success },
error: function () { //display code here }
});
You can also return the error in the body of the error message from the PHP side, and strip that from the body in your error callback.
PHP:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo 'Your error message';
JavaScript:
error: function(http) {
// show http.responseText;
}
Also, for your form submission, pack your data into a object, and then serialize it. So:
var myObject = {
property1 : 'string',
property2 : [ 'array' ]
};
var ajaxData = JSON.stringify(myObject);

JQuery Form remains static - page doesn't validate on the fly

I'm having some problems with my contact form using jquery.
I've used this same code several times before but this time I've changed divs and classes
to have meaningful names.
Everything works, it's just that when you press submit, you are physically taken to send.php instead of the data being placed in the placeholder div.
It's driving me mad so I was wondering if another few pairs of eyes could spot something?
Thanks,
Martin
All JS includes in the head of the page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.anchor.js" type="text/javascript"></script>
<script src="js/jquery.fancybox-1.2.6.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.highlight').hover(function(){
$(this).children().addClass('datahighlight');
},function(){
$(this).children().removeClass('datahighlight');
});
});
</script>
<script type="text/javascript">
window.addEvent('domready', function(){
$('contactform').addEvent('submit', function(e) {
new Event(e).stop();
var log = $('form_results').empty().addClass('ajax-loading');
this.send({
update: log,
onComplete: function() {
log.removeClass('ajax-loading');
}
});
});
});
</script>
Contact section:
<h2 class="contact">Contact Us</h2>
<p> Some text</p>
<div id="log">
<div id="form_results">
<!-- SPANNER -->
</div>
</div>
<form method="post" id="contactform" action="send.php">
<p><label for="name">Name</label></p>
<input type="text" id=name name=name placeholder="First and last name" tabindex="1" />
<p><label for="email">Email</label></p>
<input type="text" id=email name=email placeholder="example#domain.com" tabindex="2" />
<p><label for="comment">Your Message</label></p>
<textarea name="comment" id=comment name=comment placeholder="Comments" tabindex="4"></textarea>
<input name="submit" type="submit" id="submit" tabindex="5" value="Send Message" />
</form>
</section>
Send.php:
<?php
function alpha_numeric($str)
{
return ( ! preg_match("/^([-a-z0-9])+$/i", $str)) ? FALSE : TRUE;
}
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if ($_POST['name']=='' || strlen($_POST['name'])<3)
{
$errors[] = 'Please include your name, it helps when contacting you! [needs to be more than 3 characters]';
}
if (valid_email($_POST['email'])==FALSE)
{
$errors[] = 'At least put a real e-mail address!';
}
if ($_POST['comment']=='' || strlen($_POST['comment'])<3)
{
$errors[] = 'Please write something, otherwise it\'s pointless contacting us!';
}
if(is_array($errors))
{
echo '<div id="error-margin">';
echo '<p class="error"><b>Can\'t send it for the following reasons:</b></p><br />';
while (list($key,$value) = each($errors))
{
echo '<span class="error">'.$value.'</span><br /><br />';
}
echo'</div>';
}
else {
// do something here----store to db, send email
echo'<div id="success">';
echo '<p><b>It worked!</b></p>';
echo '<span>Thanks for contacting us! We\'ll be in touch soon</span>';
echo'</div>';
$name = stripslashes($_POST['name']); //sender's name
$email = stripslashes($_POST['email']); //sender's email
// The subject
$subject = "Message from 4playtheband.co.uk "; //The default subject. Will appear by default in all messages.
$msg = "From : $name \r\n"; // add sender's name to the message
$msg .= "e-mail : $email \r\n\n"; // add sender's email to the message
$msg .= "---Message--- \r\n\n\t".stripslashes($_POST['comment'])."\r\n\n"; // the message itself
// Extras:
// Display user information such as Ip address and browsers information...
$msg .= "---User information--- \r\n\n"; //Title
$msg .= "User IP Address: ".$_SERVER["REMOTE_ADDR"]."\r\n"; //Sender's IP
$msg .= "Browser: ".$_SERVER["HTTP_USER_AGENT"]."\r\n"; //User agent
$msg .= "Page User Came From: ".$_SERVER["HTTP_REFERER"]; //Referrer
// Send!
(mail('someone', $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"));
}
?>
DEMO & SOURCE: https://so.lucafilosofi.com/jquery-form-remains-static-page-doesnt-validate-on-the-fly/
you are using jquery, so there is no need to use window.addEvent('domready', function(){
you js code should look like this:
$('#contactform').submit(function() {
var query = $(this).serialize();
$('#form_results').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "send.php",
data: query,
success: function(data) {
$('#form_results').removeClass('ajax-loading').html(data).fadeIn(500);
}
});
return false;
});
window.addEvent('domready',... is from MooTool. Since you use Jquery you may have to add
<script language="javascript" type="text/javascript">
jQuery.noConflict();
</script>
before. Oh and it seems that FancyUpload only work with MooTool, don't forget to include that.
i typically use preventDefault() like so
<script type="text/javascript">
window.addEvent('domready', function(){
$('contactform').addEvent('submit', function(e) {
e.preventDefault();
var log = $('form_results').empty().addClass('ajax-loading');
this.send({
update: log,
onComplete: function() {
log.removeClass('ajax-loading');
}
});
});
});
</script>

Categories