Submitting Form Details to Mail via PHP - php

I am fairly new to PHP. So, may be it is a very silly mistake I am doing. I have to send the form details to mail id. I browsed through The Internet and get the various link about the same. I got the files and changed them according to my needs. But I am facing error 500 and I am not able to understand what is the cause behind this.
My HTML is-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>app</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div id="form-messages" class="success">
</div>
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required> </textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
</body>
</html>
My mailer.php is
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "hello#example.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
My app.js file is
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Can anyone please look into this issue. I have not much and I am not able to solve this issue. Please help me?

It is giving 500 error because you have code
http_response_code(500);
in else condition and which is getting called may be because php mail() functionality is not available on localhost (or on server which you are using).
Alternatively you can use any SMTP class to send emails. Also, You can configure your gmail id with SMTP class.

may be you didn't set mail credentials see here how can you do this.
php manual

Related

How to integrate reCAPTCHA into existing php contact form?

I am trying to integrate a reCAPTCHA with my existing php contact form. Please can someone help? I have added the relevant code into the html form, I just don't know how to adapt my mailer.php code to perform the necessary backend checks and process the form data. I'm new to php and the code i have used I adapted from a site on the web. The form also uses ajax and query form validation.
<form id="form-ajax" class="form-ajax" method="post" action="mailer.php">
<input id="name" class="form-name" type="text" name="name" placeholder="Name" required>
<span class="error"></span>
<input id="email" class="form-email" type="email" name="email" placeholder="Email Address" required>
<span class="error"></span>
<textarea id="message" class="form-message" name="message" placeholder="Message..." required></textarea>
<span class="error"></span>
<div class="g-recaptcha" data-sitekey="my-site-key"></div>
<button class="form-submit" type="submit" name="submit">Send</button>
</form>
<script>
$(function() {
// Get the form
var form = $('#form-ajax');
// Get the messages div
var formMessages = $('#form-messages');
// Set up an event listener for the contact form
$(form).submit(function(event) {
// Stop the browser from submitting the form
event.preventDefault();
// Serialize the form data
var formData = $(form).serialize();
// Submit the form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text
$(formMessages).text(response);
// Clear the form
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
</script>
<?php
// Only process POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address
$recipient = "email#example.com";
// Set the email subject
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank you! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Can't explain 400 bad request error from php/ajax form

I always get an unexplained 400 error when submitting an email through my form and i cannot understand why this is.
This worked on my local server, but when i uploaded it on the live website
Here is my HTML
<form method="post" id="ajax-contact" class="clearfix" action="js/mailer.php">
<input class="sb-search-input" placeholder="I want your freebies!" type="email" id="email" name="name" >
<input class="sb-search-submit" type="submit">
<button class="formbutton" type="submit">
<span class="fa fa-check"></span>
</button>
</form>
Here is my AJAX
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#email').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Here is my PHP
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
echo "$email";
// Check that data was sent to the mailer.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "ahamdan#kindredbay.co.uk, aemmadi#kindredbay.co.uk";
// Set the email subject.
$subject = "New enquiry from $email";
// Build the email content.
$email_content .= "Email: $email\n\n";
// Build the email headers.
$email_headers = "From: $email <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Try replacing this in your form:
<input class="sb-search-input" placeholder="I want your freebies!" type="email" id="email" name="email" >

How to send confirmation email via PHP and Ajax?

I am working on a project with a simple PHP form with Ajax. The form sends email successfully but in AJAX messages it displays an error message that I have set: 'Oops! An error occured and your message could not be sent.
' could it be a server problem?
Also I want to send user a thank you (form submit confirmation) email after they submit the form on my website.
HTML Code:
<form id="ajax-contact" method="post" action="mailer.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" required name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="3" id="message" name="message"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
PHP mailer.php Code:
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "receiveremail#somewhere.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
AJAX Code:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
just change this line and check once. even i had the same issue, i solved like this,
data: formData
to
data: {"postvalues":formData},
or
data: formData to data: {name: "sample",email:"your emal",message:"hi how are you"}
If you are using first one, make necessary changes in mailer.php. Like this
$post = $_POST['postvalues'];
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
If you follow second method, you cant serialize() form, and no need to change anything in mailer.php.
To send email to user who filled the form, use this
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
mail($email, "Contact Us", "Thank you for contacting us, we will get back to you soon", $email_headers)
}

Why is the contact form not working in my site?

The contact form doesnt work
Here is the code im using in the page.
Jquery in Index.html
<!--contact form -->
<script type="text/javascript">
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
</script>
Here is the HTML Code for the Container
Contact-Form in HTML # index.html
<!--contact form -->
<div id="contact-form">
<div id="contact_form_holder">
<form action="index.php" method="post" id="contact_form">
<p>
Your Name:
<input name="name" class="field" id="name" type="text">
</p><div id="name_error" class="error"><img src="web_files/error.png"> Please enter your name</div>
<p></p>
<p>
Your Email:
</p><div><input name="email" class="field" id="email" type="text">
<div id="email_error" class="error"><img src="web_files/error.png"> OOps!! i can't get back to you in this mail id</div>
</div>
<p></p>
<p>
The Message:
</p><div>
<textarea name="message" class="field" id="message"></textarea>
<div id="message_error" class="error"><img src="web_files/error.png"> Forgot why you came here?</div></div>
<p></p>
<div id="mail_success" class="success"><img src="web_files/success.png"> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="web_files/error.png"> Sorry, don't know what happened. Try later.</div>
<p id="cf_submit_p">
<!--<input type='submit' id='send_message' value='Send it to me' class="submit"> -->
<input id="send_message" value="Send The Message" class="submit" type="submit">
</p>
</form>
</div>
</div>
<!--contact form -->
And at last here is the PHP code as
send_email.php
//we need to get our variables first
$email_to = 'mail#mail.com'<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__"); a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2) {c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s); l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
//the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
Your error is at your first line in your PHP-code:
$email_to = 'email#email.com'<script type="text/javascript">
Your string ends after the e-mail address. Correct it to
$email_to = 'email#email.com';
and you should be fine.
Also, what is the JavaScript doing inside the PHP? Remove it or make sure to either echo it, or place it outside of your PHP-tags.
1)Change the first line of your php code to
$email_to = 'some.person#example.com';
2)Remove the JavaScript from the PHP file.
If its still not working, change all the $_POST to $_GET and enter the values of the variables yourself. Then run the code and tell me the output.
EDIT :
I have found your error. You have not opened your php file correctly.
http://www.justyesh.in/send_email.php
You begin PHP with <?php and close it with ?>

Passing a variable from PHP to javascript and on to an html form

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().

Categories