[I suspect the issue at hand has to do with how the php array gets passed to jQuery, if that isn't the case I apologize for the misleading title]
The contact form below is working -- except when I submit the forms' data, sometimes one field always keeps its red border indicating missing input, even when it actually has data.
To elaborate: I have a working php-only solution but on submit it causes a page-reload which I would like to avoid. After some research, it seems I need php/jQuery/ajax to perform these things asynchronously and to stay on the same site.
Desired behaviour:
So there are three required input fields called name, email and message, if any one is left out, it should receive a red border and no email gets sent.
Actual behaviour:
If for example only name and message are filled out and submitted, the empty email field is colored red.
But if a (valid) email is provided, the second submit action does not remove the red border around the email field.
I know that javascript and friends is a client-side language, and PHP gets processed server-side. Once the form is submitted, the .ajax function takes the serialized form values, uses 'POST' to stuff it into the php script and waits for the server to call us back inside .done()
This is where I'm lost - how is the php array to be used in jQuery?
E.g. no matter what, this line is never reached:
console.log("All fields filled and valid");
index.html:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />
<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>
<style>
.input-error
{
border: 2px solid red;
}
</style>
<script>
$(document).ready(function() // Wait until website (DOM) is completely loaded
{
/* Page top */
$('#pagetop').click(function()
{
console.log(this);
$('body, html').animate({scrollTop: '0px'}, 600);
return false;
});
});
</script>
</head>
<body>
<!-- action is left blank as process.php is called from verify.js -->
<form action="" method="POST" id="contactForm">
<label for="company">Company</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
<br><br>
<label for="name">Name *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
<br><br>
<label for="email">Email *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
<br><br>
<label for="message">Message *</label>
<br>
<textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
<br><br>
<input type="submit" id="submit" name="submit" value="Send">
<br><br>
</form>
</body>
verify.js
$(document).ready(function()
{
// process the form
$('#contactForm').submit(function(event)
{
//$('#name, #email, #message').removeClass('input-error');
// process the form
$.ajax(
{
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : $('#contactForm').serialize(),
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data)
{
// log data to the console so we can see
console.log(data);
if (data.errors.name)
{
console.log("Name missing");
$('#name').addClass('input-error');
}
else
{
$('#name').removeClass('input-error');
}
// handle errors for email
if (data.errors.email)
{
console.log("Email missing or invalid");
$('#email').addClass('input-error');
}
else
{
$('#email').removeClass('input-error');
}
// handle errors for message
if (data.errors.message)
{
console.log("Message missing");
$('#message').addClass('input-error');
}
else
{
$('#message').removeClass('input-error');
}
if(data.input_valid == true)
{
console.log("All fields filled and valid");
alert('success');
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
process.php
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// Sanitize input variables
$company = test_input($_POST['company']);
$name = test_input($_POST['user_name']);
$email = test_input($_POST['user_email']);
$message = test_input($_POST['user_message']);
// Validate the variables
// If any of these variables don't exist, add an error to our $errors array
if (empty($name))
$errors['name'] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
$errors['email'] = 'Valid Email is required.';
if (empty($message))
$errors['message'] = 'Message is required.';
$from = '--- Contact Form ---';
$to = 'some#mail.com';
$subject = 'Message from Contact Form';
$body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
if(mail($to, $subject, $body, $from))
{
$data['message'] = 'Thank you for your message!';
$data['mail_sent'] = true;
}
else
{
$data['message'] = 'Message could not be sent - please try again later.';
$data['mail_sent'] = false;
}
}
// return all our data to an AJAX call
echo json_encode($data);
// Convert special characters to html entities to prevent XSS attacks
// Also remove white-space and backslashes
function test_input($val)
{
$val = trim($val);
$val = stripslashes($val);
$val = htmlspecialchars($val);
return $val;
}
?>
It looks like if all validations pass in your php script, then data['errors'] is never defined. This might cause an error to be thrown (that you can see in the browser console) in the javascript when you write:
if (data.errors.name)
data.errors will evaluate to undefined in javascript, and when you try to access a property of undefined like data.errors.name, it will throw an error and stop the script.
To fix this, you probably just need to define errors in your php script, (though I'm not 100% sure the JSON methods won't leave out an empty array...). Try doing this in your php script:
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
$data['errors'] = $errors; // even though it is empty
// etc
EDIT:
I don't know if it will work with your jquery version but just in case it doesn't, place this code in your header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I used the below code and it worked. Sent the email without having to change the PHP code:
$(document).ready(function() {
$('#contactForm').submit(function(event) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#contactForm').serialize(),
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if(data.input_valid == true) {
console.log("All fields filled and valid");
// If the function is a success remove error classes from all fields
// you can either place the below code above the alert so that it happens
// before you get the success message, or after.
$('#name').removeClass('input-error');
$('#email').removeClass('input-error');
$('#message').removeClass('input-error');
alert('success');
} else {
if (data.errors.name) {
console.log("Name missing");
$('#name').addClass('input-error');
} else {
$('#name').removeClass('input-error');
}
if (data.errors.email) {
console.log("Email missing or invalid");
$('#email').addClass('input-error');
} else {
$('#email').removeClass('input-error');
}
if (data.errors.message) {
console.log("Message missing");
$('#message').addClass('input-error');
} else {
$('#message').removeClass('input-error');
}
}
});
event.preventDefault();
});
});
Related
sorry that I start this topic. I know that there were a lot of topics in this matter. But still I can not deal with it, because I need the success / failure messages to be displayed as below:
<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="save-test-form" value="Save">
</form>
/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$_SESSION['success_msg'] = 'All is well.';
}else{
$_SESSION['error_msg'] = 'Enter the email.';
}
}else{
$_SESSION['error_msg'] = 'Enter the name.';
}
}
?>
And jquery?
My point is to submit this form without reloading the page (because it's in the modal window) and I have to display success / failure messages in the form (also without reloading the page). I do not know how to do it.
I will be grateful for the help and explanation of how to do it step by step.
Your PHP script is executed on page reload, so when using Ajax you must manually show messages from server:
// PHP
$response = [];
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$response['success'] = 'All is well.';
}else{
$response['error_msg'] = 'Enter the email.';
}
}else{
$response['error_msg'] = 'Enter the name.';
}
echo json_encode($response); // Format array as json and output it
die(); // No other output, just JSON
}
// jQuery
$.ajax({
url: '',
method: 'POST',
dataType: 'json',
data: {},
success: function (response) {
if (typeof response.success !== 'undefined') {
$('#responseMessage').text(response.success);
} else {
$('#responseMessage').text(response.error_msg);
}
}
})
I have a problem with an apparently simple form for a mailing list subscription.
The HTML5 form contains 3 fields:
text input for e-mail address: <input type="email" name="email"
radio button control with 2 choices:
<input type="radio" value="subscribe" name="radio"
<input type="radio" value="unsubscribe" name="radio"
text input for a CAPTCHA check: <input type="text" name="captchavalue"
<form id="contact" name="contact" method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="check" value="01">
<small>*tutti i campi sono obbligatori</small>
<label for="email" id="emailabel">E-mail:<span class="err topp">INDIRIZZO NON VALIDO</span></label>
<input type="email" name="email" id="email" class="textemail">
<label for="subscr" id="subscrlabel">Scelta:<span class="err topp">devi selezionare una scelta</span></label>
<p><input type="radio" name="radio" id="radio" value="subscribe" checked>Iscrizione</p>
<p><input type="radio" name="radio" id="radio" value="unsubscribe">Cancellazione</p>
<img src="captcha.php" id="captchaimg">
<label for="captcha" id="captchalabel">Copiare il codice di verifica<span class="err capter">CAPTCHA ERRATO</span></label>
<input type="text" name="captchavalue" id="captchavalue" class="textcaptcha">
<section id="subber">
Invia richiesta
</section>
</form>
</div>
We have a list of domains which are allowed to ask for subscription contained in an external file .dat, some line in PHP to dynamically create a regular expression to check the email address (just in case of subscription, otherwise any valid email address is allowed)
<?php
$domains = file("domains.dat");
$domcount = count($domains);
for ($i=0; $i < $domcount; $i++) {
$regex .= "(".trim($domains[$i]).")|";
}
$regex = str_replace(".", "\.", $regex);
$regex = "/^([a-zA-Z\.-_0-9]*#(".substr($regex, 0, strlen($regex)-1).")$)/i";
?>
function checkValidCNRAddress(emailAddress) {
var pattern = new RegExp(<? echo $regex ?>);
return pattern.test(emailAddress);
};
function checkValidEmailAddress(emailAdd) {
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][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAdd);
};
var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
// statement below is for DEBUG purposes only -- to show the
// value of the radio button (subscription status) in ALL CASES
document.write(usubscr); //DEBUG
//check that a radio button option is checked (default: "subscribe" is checked )
if(!usubscr) {
$("#subscrlabel").children(".err").fadeIn('slow');
}
else if(usubscr) {
// we have *something* selected in the radio button for subscription
$("#subscrlabel").children(".err").fadeOut('slow');
// next, check for validate email addresses using regular expressions
//check on dynamic regex
if (usubscr == "subscribe") {
if(!checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
}
} //else check at least for a valid email address
else if (usubscr == "unsubscribe"){
if(!checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
}
}
}
Then it checks whether the captcha it's OK or not (it sends data to a PHP page captcha_check) and then submits to sendmail.php (which is in charge to send the subscribe/unsubscribe request to our mailserver)
// captcha check
$.ajax(
{
type: 'POST',
url: 'captcha_check.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "false") {
mailsendstatus = false;
$("#captchalabel").children(".err").fadeIn('slow');
}
else if(data == "true"){
$("#captchalabel").children(".err").fadeOut('slow');
if((checkValidCNRAddress(uemail))||(checkValidEmailAddress(uemail))) {
// in this case it's alright
// TRUE
mailsendstatus = true;
$("#subber").html('<img src="img/load.gif" alt="loading...">');
$.ajax(
{
type: 'POST',
url: 'sendmail.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "yes") {
$("#contactwrapper").slideUp(650, function(){
$(this).before("<p>La tua richiesta รจ stata inviata, grazie.</p>");
});
}
}
}
); //
} //
} //
} //
} //
);
return mailsendstatus;
}
$(document).ready(function(){
$("#contact").submit(function() { return false; });
$("#submitlink").bind("click", function(e){
var usercaptvalue = $("#captchavalue").val();
var emailvalue = $("#email").val();
var subscrvalue = $("#radio").val();
//sends values to sendmail.php
var postchecks = userSendMailStatus(emailvalue, subscrvalue, usercaptvalue);
});
});
</script>
</body>
Can anybody explain this to me:
- when the script verifies the email address, the value of the radio button given is always "subscribe", in any case, even if I check for unsubscription
- but if I type an email address which domain is contained in domains.dat and check the button for unsubscription, the value passed to sendmail.php is "unsubscribe" (as I can see when I receive the e-mail message)
Hope it's clear enough...thank you in advance for your precious help!
Your problem is that you're NOT actually making any AJAX request to sendmail.php AT ALL unless the email is valid and ONLY when the email is valid.
You see, all your validations in JavaScript to check for valid email addresses, are ONLY then:
fading your errors IN => $("#subscrlabel").children(".err").fadeIn('slow');
or
fading your errors OUT => $("#subscrlabel").children(".err").fadOut('slow');
but, this is occurring on the page only
When you actually submit, it fails the AJAX request if the email is invalid, BUT, it is still submitting the form normally and therefore it resets to the default subscribe input state of "checked"
What you need to do is include your .ajax(...) statement/call inside of your validation, not below it, after you've closed the function:
var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
//verify radio button (it's checked by default in our case)
if(!usubscr) {
$("#subscrlabel").children(".err").fadeIn('slow');
}
else {
$("#subscrlabel").children(".err").fadeOut('slow');
//check on dynamic regex
if (usubscr == "subscribe") {
if(!checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
mailsendstatus = true;
}
} //else check at least for a valid email address
else if (usubscr == "unsubscribe"){
if(!checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
mailsendstatus = true;
}
}
}
if (mailsendstatus = true;) {
...
//make your AJAX request here
...
}
}
I'm trying to use recaptcha with PHP and AJAX and I'm stuck. For some reason whenever I try to take something out of $_POST I get an error message.
I'm running PHP 4.4.
<?php
require_once('includes/recaptchalib.php');
define("PRIV_KEY", "yesthereisakeyhere");
$name = $_POST['name']; // This line comes back as undefined index
$email = $_POST['email']; //This line comes back as undefined index
if(in_array('', array($name, $email))) {
//one (or more) of the required fields is empty
$result = "field_error";
} else {
$resp = recaptcha_check_answer (PRIV_KEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); // 2 more undefined index errors here.
if (!$resp->is_valid) {
//Captcha was entered incorrectly
$result = "captcha_error";
} else {
//Captcha was entered correctly
$result = "success";
//mail function goes in here.
}
}
echo $result;
?>
This is my HTML for reference:
<?php
require_once('includes/recaptchalib.php');
define("PUB_KEY", "yesthereisakeyhere");
?>
<form class="form" method="post">
<label>Name *</label>
<input type="text" name="name" class="required" />
<label>Email *</label>
<input type="text" name="email" class="required" />
<?php echo recaptcha_get_html(PUB_KEY); ?>
<input type="submit" value="GET A QUOTE" />
</form>
Here is a my AJAX call for reference:
$("#locator-quote input[type=submit]").click(function() {
$(".message").removeClass("success").removeClass("error").addClass("loader").html("Sending message").fadeIn("slow");
$.ajax({
type: "POST",
url: "ajax.php",
data: $(this).serialize(),
dataType: 'text',
success: function(msg){
$('body').prepend('<h1>' + msg + '</h1>') /// This line is for testing
switch(msg) {
case "field_error": // one or more fields is/are empty
$(".message").removeClass("loader").addClass("error");
$(".message").html("Please fill in all the required fields.");
break;
case "captcha_error": // captcha wasn't typed correctly
$(".message").removeClass("loader").addClass("error");
$(".message").html("Please type the words correctly and try again!");
break;
case "success": // all good
$(".message").removeClass("loader").addClass("success");
$(".message").html("Your message has been sent. You'll soon hear from us!");
break;
default: // Hmm. The default case. You never know.
alert("Something is wrong. Please try again.");
}
}
});
Recaptcha.reload();
return false;
});
The problem is you are trying to serialize the button and not the form.
You are listening to the $("#locator-quote input[type=submit]").click event, so this will be the button.
You need to serialize the form.
$(this).closest('form').serialize()
Or, instead bind to the form's .submit event.
$('.form').submit(function(){
var data = $(this).serialize();
return false;
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
This is the HTML with form:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="css/index.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.10.2.min.js" charset="utf-8"></script>
<script type="text/javascript" src="js/login.js" charset="utf-8"></script>
<script src="../htdocs/SpryAssets_index/SpryMenuBar.js" type="text/javascript"></script>
<link href="../htdocs/SpryAssets_index/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="includes/css/index.css" />
</head>
<body>
<div class="container">
<?php
include ('includes/header.html')
?>
<br /><br />
<h1>Login</h1>
<p id="results"></p>
<form action="login_ajax.php" method="post" id="login">
<p id="emailP">Email Address: <input type="text" name="email" id="email" /><span class="errorMessage" id="emailError">Please enter your email address!</span></p>
<p id="passwordP">Password: <input type="password" name="password" id="password" /><span class="errorMessage" id="passwordError">Please enter your password!</span></p>
<p><input type="submit" name="submit" value="Login!" /></p>
</form>
<div class="footer">
<?php
include ('includes/footer.html')
?>
</div>
</div>
</body>
</html>
This is the handler login_ajax.php:
<?php
if (isset($_POST['email'], $_POST['password'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
function check_login($dbc, $email = 'email', $pass = 'pass') {
$errors = array(); //Intialize the error array.
if (empty($email)) {
$errors[] = 'You forgot to enter your email address.';
} else {
$e = filter_var($email, FILTER_SANITIZE_EMAIL);
}
if (empty($pass)) {
$errors[] = 'You forgot to enter your password.';
} else {
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if (empty($errors)) {
$q = "SELECT first_name, last_name FROM users WHERE email='$e' AND pass=SHA1('$p')";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) {
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
echo 'CORRECT';
} else {
$errors[] = 'The email address and password entered do not match those on file.';
echo 'INCORRECT';
}
session_start();//START A SESSION HERE.
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['last_name'] = $data['last_name'];
}
}
check_login($dbc, $_POST['email'], $_POST['password']);
} else {
echo 'INVALID_EMAIL';
}
} else {
echo 'INCOMPLETE';
}
?>
This is the Javascript that handles the echo login.js:
// Script 15.10 - login.js
// This script is included by login.php.
// This script handles and validates the form submission.
// This script then makes an Ajax request of login_ajax.php.
// Do something when the document is ready:
$(function() {
// Hide all error messages:
$('.errorMessage').hide();
// Assign an event handler to the form:
$('#login').submit(function() {
// Initialize some variables:
var email, password;
// Validate the email address:
if ($('#email').val().length >= 6) {
// Get the email address:
email = $('#email').val();
// Clear an error, if one existed:
$('#emailP').removeClass('error');
// Hide the error message, if it was visible:
$('#emailError').hide();
} else { // Invalid email address!
// Add an error class:
$('#emailP').addClass('error');
// Show the error message:
$('#emailError').show();
}
// Validate the password:
if ($('#password').val().length > 0) {
password = $('#password').val();
$('#passwordP').removeClass('error');
$('#passwordError').hide();
} else {
$('#passwordP').addClass('error');
$('#passwordError').show();
}
// If appropriate, perform the Ajax request:
if (email && password) {
// Create an object for the form data:
var data = new Object();
data.email = email;
data.password = password;
// Create an object of Ajax options:
var options = new Object();
// Establish each setting:
options.data = data;
options.dataType = 'text';
options.type = 'get';
options.success = function(response) {
// Worked:
if (response == 'CORRECT') {
// Hide the form:
$('#login').hide();
// Show a message:
$('#results').removeClass('error');
$('#results').text('You are now logged in!');
} else if (response == 'INCORRECT') {
$('#results').text('The submitted credentials do not match those on file!');
$('#results').addClass('error');
} else if (response == 'INCOMPLETE') {
$('#results').text('Please provide an email address and a password!');
$('#results').addClass('error');
} else if (response == 'INVALID_EMAIL') {
$('#results').text('Please provide your email address!');
$('#results').addClass('error');
}
}; // End of success.
options.url = 'login_ajax.php';
// Perform the request:
$.ajax(options);
} // End of email && password IF.
// Return false to prevent an actual form submission:
return false;
}); // End of form submission.
}); // End of document ready.
This form is returning an INCOMPLETE from the PHP handler which the Javascript is returning as "Please provide an email address and a password!".
Heres my suggestion for you. Hopefully this makes sense and works for you. Please try to understand what is happening rather than just copy and hope it works. Your form, on submit, gets sent to the JS file. This grabs the form values, uses JSON to send them to your php file which processes everything and returns a response, either true or false. If false, the js file will display your errors on screen and add classes etc. If true you can get it to redirector do whatever you want.
HTML form...
<h1>Login</h1>
<p id="results"></p>
<form action="login_ajax.php" method="post" id="login" onsubmit="jsquicksub(this); return false;>
<p id="emailP">Email Address: <input type="text" name="email" id="email" /><span class="errorMessage" id="emailError">Please enter your email address!</span></p>
<p id="passwordP">Password: <input type="password" name="password" id="password" /><span class="errorMessage" id="passwordError">Please enter your password!</span></p>
<p><input type="submit" name="submit" value="Login!" /></p>
</form>
In your login.js
// hide the div where the error reporting gets displayed on load of the page
$(document).ready(function() {
$('#results').hide();
});
var gb_ajaxbusy = false;
function jsquicksub(po_form) {
if (gb_ajaxbusy)
return false;
gb_ajaxbusy = true;
var lo_request = {};
// go through each and every form element and assign to variable
lo_request.e = $(po_form).find('#email').val();
lo_request.p = $(po_form).find('#password').val();
$(po_form).fadeTo(200, 0.3);
$.getJSON('/login.php', lo_request, function(po_result) { // php form processing field
gb_ajaxbusy = false;
$(po_form).fadeTo(0, 1);
if (!po_result.success) {
$('#results').show();
document.getElementById('results').innerHTML = po_result.content;
// inserts errors in specified div. can use alert if wanted
// do your thing with adding classes etc if you want to
return false;
}
// replace form with thankyou message/redirect somewhere or whatever you want to do
// empty results element
$('#results').hide();
});
} // end jsquicksub()
Then in your login.php file ....
// function gets passed values after validation and returns a message to the user on screen - gets passed back to JS file which then returns stuff to the screen
function jsonreturn($pb_success, $ps_content = null) {
$lo_result = (object) array('success'=>$pb_success, 'content'=>$ps_content);
ob_clean();
echo json_encode($lo_result);
exit;
} // end jsonreturn()
// these values are recieved from the javascript function
$ps_email = isset($_GET['e'])? $_GET['e']: null;
$ps_password = isset($_GET['p'])? $_GET['p']: null;
if(empty($ps_email) OR empty($ps_password)) {
// run your check_login stuff in here
// use jsonreturn(false, 'message') for error OR when everything is fine and you have set the session, use jsonreturn(true, 'complete');
}
else {
jsonreturn(false, 'Your error message in here which gets added to the id="results" p tag');
}
There are new ways to code, faster and better ; you are programing not in a very good way, everything is mixed so it get confused.
Your php handler is testing for POSTed variables, but you've set the javascript to send by GET.
I'm having one, admittedly very minor issue with a contact form I've set up in WordPress using jQuery, jQuery form and PHP Mail to send a form-generated email.
To replace my current contact form which performs a pHp validation from within the contact form page and then sends using PHP Mail, I've designed the following simple html 5 form (which can be seen on this page: http://edge.donaldjenkins.net/contact):
<form id="contact" method="post" action="">
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" placeholder="Your Name" title="Enter your name" class="required">
<label for="email">E-mail</label>
<input type="email" name="email" placeholder="yourname#domain.com" title="Enter your e-mail address" class="required email">
<label for="phone">Phone</label>
<input type="tel" name="phone" placeholder="ex. (555) 555-5555">
<label for="website">Website</label>
<input type="url" name="url" placeholder="http://">
<label for="message">Question/Message</label>
<textarea name="message"></textarea>
<label for="checking" class="hidden">If you want to submit this form, do not enter anything in this field</label><input type="text" name="checking" class="hidden">
<input type="submit" name="submit" class="button" id="submit" value="Send Message" />
</fieldset>
I then use the jQuery validate [jquery.validate.js] and form [jquery.form.js] plugins to perform a client-end validation:
<script src="js/jquery.validate.js"></script>
<script src="js/jquery.form.js"></script>
<script>
$(function(){
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'send-message.php',
success: function() {
$('#contact').hide();
$('#instructions').hide();
$('#status').show();
$('#popular-posts').show();
$('#status').append("<p>Thanks! Your request has been sent. One will try to get back to you as soon as possible.</p>")
}
});
}
});
});
</script>
After the validation, the above script uses jQuery.form's ajaxSubmit function to submit the date to a server PHP page, send-message.php (the reason being that javascript can't send email). I use this PHP file to carry out a second, server-side validation of the data (though this is probably redundant, since because the setup relies on javascript to pass the data on to the server, one can safely assume that no one will be able to use the form without javascript enabled). It also performs a honeypot captcha check on data in a hidden input field added in the form. The email is then sent:
<?php
//invoke wp_load in order to use WordPress wp_mail plugin function instead of mail for better authentification of the sent email
require_once("/path/to/wp-load.php");
//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
$captchaError = true;
$errors .= "\n Error: Captcha field filled in";
} else {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) === '') {
$errors .= "\n Error: Name field empty";
$hasError = true;
} else {
$name = strip_tags($_POST['name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '') {
$emailError = 'You forgot to enter your email address.';
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$errors .= "\n Error: Message field empty";
$hasError = true;
} else {
$email = strip_tags($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) === '') {
$errors .= "\n Error: Message field empty";
$hasError = true;
} else {
$phone = strip_tags($_POST['phone']);
$url = strip_tags($_POST['url']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = strip_tags($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
// Send Message
$emailTo = 'me#mydomain.com';
$subject = 'Contact Form Submission from '.$name;
$body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nWebsite: $url \n\nMessage: $message";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$alert = 'Thanks! Your request has been sent. One will try to get back to you as soon as possible.';
} else {
$alert = $errors;
}
} ?>
The server keeps track of whether errors were found or whether the email was successfully sent in variable $alert.
After the pHp function completes, the script hides the form from the contact page and displays a previously hidden html element to which it appends an alert message.
The issue I can't solve is making javascript change the wording of that alert message to reflect whether the email was or not successfully sent, because I don't know how to pass the requisite pHp variable ($alert) containing a list of the error messages in the server PHP process to the script for insertion in the Contact Form page. Of course, again, this is a very theoretical concern, since for the reasons stated above, it's unlikely that an error-prone message would even have reached the PHP stage in the first place.
I've tried inserting the following code at the end of the PHP file, to no avail:
<script type="text/javascript">
alert = <?php echo $alert; ?>;
</script>
The latter attempt doesn't generate any errors in Firebug, but the variable value doesn't get passed on. Any ideas or thoughts welcome.
UPDATE: I added this workflow chart to clarify the setup for this issue:
In send-message.php, put the alert text in an IDd <div />:
<div id="statusmsg" style="display: none">
<?php echo $alert ?>
</div>
Then your Javascript on the calling page ought to look like this:
<script type="text/javascript">
$(function() {
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'send-message.php',
success: function(data) {
$('#contact').hide();
$('#instructions').hide();
$('#status').show();
$('#popular-posts').show();
// Make DOM object from result
var $DOMObj = $(data);
// Retrieve status message, if any
var $status = $('#statusmsg', $DOMObj);
// Show status message, if any
if ($status) {
$status
.css('display', '')
.appendTo('#status');
}
}
});
}
});
});
</script>
Hopefully you can see how I've used a parameter to the success callback to retrieve the HTML contents of the AJAX request response, located the statusmsg div and appended it to the relevant element on the calling page.
More optimally, send-message.php would print JSON rather than HTML, making this process a little easier. I'll leave that as an exercise for the reader.. at least in this question thread.
You want to return the success or failure of the email in response to the AJAX call.
For this sample example, you could simply return false or true. If you needed more information, return a JSON string such as...
{
"success": true,
"something": ["something", "something-else"]
}
You can easily turn an array into JSON in PHP with json_encode().