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

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>

Related

jQuery Code Inside PHP File Being Displayed While Using AJAX

Whilst trying to use AJAX for validation on my website, it is completely displaying to the user with exception of the PHP variables, the jquery code I am using for styling my inputs. I am trying to change the styles of my inputs accordingly and provide and error message, which is successful, however, the javascript code is also being displayed
index.php
<html>
<head>
<link rel="stylesheet" href="css/template.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery/template.js"></script>
<script type="text/javascript" src="jquery/index.js"></script>
</head>
<body onload="startUp();">
<!-- Banner Image -->
<div id="banner"><img id="bannerImage" src="abcdefd.com.jpg" alt=""></div>
<!-- Body Wrapper -->
<div id="wrapper">
<!-- Content -->
<div id="content">
<!-- <h2 id="title">Log In</h2> -->
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<input class="click" type="submit" name="submit" id="submit" value="Log in">
</form>
<p id="err"></p>
</div>
</div>
</body>
</html>
index.js
$(document).ready(function(){
$("#loginForm").submit(function(event){
event.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
var submit = $("#submit").val();
$("#err").load("config/config.index.php",{
email: email,
password: password,
submit:submit
});
});
});
config.index.php
<?php
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = $_POST['password'];
$errEmptyAll = false;
$errEmptyEmail = false;
$errEmptyPassword = false;
$errEmail = false;
if(empty($email) && empty($password)){
echo 'Please enter an email and password.';
$errEmptyAll = true;
} else if(empty($email)){
echo 'Please enter an email.';
$errEmptyEmail = true;
} else if(empty($password)){
echo 'Please enter a password.';
$errEmptyPassword = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo 'Please enter a valid email.';
$errEmail = true;
}
}
?>
<script>
var errEmptyAll = "<?php echo $errEmptyAll; ?>";
var errEmptyEmail = "<?php echo $errEmptyEmail; ?>";
var errEmptyPassword = "<?php echo $errEmptyPassword; ?>";
var errEmail = "<?php echo $errEmail; ?>";
if(errEmptyAll == true){
$("#email, #password").addClass("inputErr");
}
if(errEmptyEmail == true){
$("#email").addClass("inputErr");
}
if(errEmptyPassword == true){
$("#password").addClass("inputErr");
}
if(errEmail == true){
$("#email").addClass("inputErr");
}
</script>
The config PHP file should not have any JS at all.
Don't use .load(). Use $.ajax to send POST data and listen for server responses.
Build a json_encode response on PHP which will be returned to the browser via AJAX. Read the response data (from PHP) in JavaScript jQuery via the :success property or in the .done() method of $.ajax
index.html
<form id="loginForm" method="post" action="config/config.index.php">
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit" name="submit">Log in</button>
</form>
<p id="err"></p>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script srrc="index.js"></script>
index.js
jQuery(($) => { // DOM ready and $ alias in scope
const $err = $("#err");
$("#loginForm").on("submit", function (ev) {
ev.preventDefault(); // prevent browser submit
$(this).find(`[name]`).removeClass("inputErr");
$.ajax({
type: "POST",
dataType: "JSON",
url: this.action, // from form action value
data: $(this).serialize(),
}).done((res) => {
// res is the JSON Response from PHP
console.log(res); // Do with this whatever you want. i.e:
if (res.errors.length) {
$err.text(res.errors.join(", "));
res.fields.forEach(field => {
$(`[name="${field}"]`).addClass("inputErr");
});
} else {
// SUCCESS!!!
}
});
});
});
config/config.index.php
<?php
$response = (object)[
"status" => "error",
"errors" => [],
"fields" => [], // IDs of fields with error
];
if (
$_SERVER["REQUEST_METHOD"] === "POST" &&
isset($_POST["email"]) &&
isset($_POST["password"])
) {
$email = $_POST["email"];
$password = $_POST["password"];
$passwordEmpty = empty($password);
$emailEmpty = empty($email);
$emailInvalid = !filter_var($email, FILTER_VALIDATE_EMAIL);
if ($passwordEmpty) :
$response->errors[] = "Invalid Password";
$response->fields[] = "password";
endif;
if ($emailEmpty) :
$response->errors[] = "Empty Email";
$response->fields[] = "email";
elseif ($emailInvalid) :
$response->errors[] = "Invalid Email";
$response->fields[] = "email";
endif;
if (empty($response->errors)) :
$response->status = "success";
endif;
}
echo json_encode($response);
exit;

Submision via AJAX call not working

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.

Ajax & PHP email with JSON return

I have a simple contact form. I got the invalid email and fill all the fields error messages correctly, but I don't get the success message. Hence it's sending the email twice without giving any returning success messages (I just click once, I'm sure about that).
The JS part:
<script language="javascript" type="text/javascript" >
$(function(){
$("#ContactForm").submit(function(){
$("#submitf").value='Sending...';
$.post("send.php", $("#ContactForm").serialize(),
function(data){
if(data.frm_check == 'error'){
$("#message_post").html("<div class='errorMessage'>Error: " + data.msg + "!</div>");
document.ContactForm.submitf.value='Send Again >>';
document.ContactForm.submitf.disabled=false;
} else if(data.frm_check == 'done') {
$("#message_post").html("<div class='successMessage'>Thanks, " + data.msg + "!</div>");
}
}, "json");
return false;
});
});
</script>
The PHP part:
$return_arr = array();
$email = $_POST["email"];
$message= $_POST["message"];
$name= xss_protect(sacarXss($_POST["name"]));
if(!empty($email) && !empty($name) && !empty($message)) {
if(isValidEmail($email)){
$return_arr["frm_check"] = 'done';
$return_arr["msg"] = "Success";
send_mail($email, $name, $message);
}
else{
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Invalid email";
}
} else {
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Fill all the fields.";
}
echo json_encode($return_arr); ?>
The HTML part:
<form method="post" id="ContactForm">
<div class="element">
<input type="text" name="name" class="text" placeholder="name" /><br />
<input type="text" name="email" placeholder="email" class="text" /><br />
<textarea name="message" class="textarea" rows="3" placeholder="message"></textarea><br />
<input type="submit" name="submitf" id="submitf" value="send!"/>
</div>
<div id='message_post'></div>
</form>
I think the form is sent twice to the php script: via the javascript and the submit button of the form. If you change the type of the submit button from 'submit' to 'button', the form will be sent only once.
You must parse the JSON response, so the javascript function becomes:
<script language="javascript" type="text/javascript" >
$(function(){
$("#ContactForm").submit(function(){
$("#submitf").value='Sending...';
$.post("send.php", $("#ContactForm").serialize(),
function(data){
data = jQuery.parseJSON(data);
if(data['frm_check'] == 'error'){
$("#message_post").html("<div class='errorMessage'>Error: " + data['msg'] + "!</div>");
document.ContactForm.submitf.value='Send Again >>';
document.ContactForm.submitf.disabled=false;
} else if(data['frm_check'] == 'done') {
$("#message_post").html("<div class='successMessage'>Thanks, " + data['msg'] + "!</div>");
}
}, "json");
return false;
});
});
</script>

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);
}
}
});

How to add AJAX Submit to PHP validation and return message?

I've been working my way up on validating a form and got the JS and PHP validation to work but I am still having a hard time adding ajax(with or without JQUERY) to submit to the php file and return a success message.
My form with CSS and JS validation:
<html>
<head>
<style type="text/css">
#nameerror {
color:red;
}
#emailerror{
color:red;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
var email = document.forms['form']['email'].value;
var atpos = email.indexOf('#');
var dotpos = email.lastIndexOf('.');
var name = document.forms['form']['name'].value;
if (name == null || name == ""){
document.getElementById('nameerror').innerHTML="Please enter your name";
return false;
} else if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
document.getElementById('emailerror').innerHTML="Please enter a valid email";
return false;
} else {
}
}
</script>
</head>
<body>
<div>Sign Up</div>
<form name="form" action="form_validation.php" id="form" onsubmit="return Validate();" method = 'post'>
<label>Name:</label><br/>
<input id='name' type="text" name='name' /><br/>
<span id="nameerror"></span><br/>
<label>Email:</label><br/>
<input type='text' name='email' id = 'email'/> <br/>
<span id= "emailerror"></span><br/>
<label>Comments:</label><br/>
<textarea name='comments' id ='comments'></textarea><br/>
<span id="comerror"></span>
<input type="submit" name="submit" value="Submit"/>
<span id="success" style="display:none">Your message has been sent successfully.</span>
</form>
</body>
</html>
And this is form_validation.php:
<?php
if(isset($_POST['submit'])){
if($_POST['name']){
$name = $_POST['name'];
}
if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
echo "Name can only contain letters.";
return false;
} else {
echo "Name accepted";
}
if($_POST['email']){
$email = $_POST['email'];
}
$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if(!preg_match($pattern, $email)){
echo "Please enter a valid email address.";
return false;
} else {
echo "Email Valid";
}
if($_POST['comments']){
$comments = $_POST['comments'];
}
if (strlen($comments) > 100){
echo "please enter less than 100 characters.";
return false;
}
}
?>
thanks for the help!
$('form').on('submit',function() {
$.ajax({
url: 'form_validation.php',
data: $(this).serialize(),
type: 'POST'
}).done(function(data){
// you can append a success message to your document here
});
});

Categories