I have problem with my form on my webpage. I am trying to use ajax and json to send the form values to php server, but I can't make properly json object.
My JS code
function sendJsonOpenPopout () {
$('.submitBtn').click(function(e){
e.preventDefault();
var subject = $('.subject').val();
var email = $('.email').val();
var message = $('.message').val();
var dataObject = {
subject: subject,
email: email,
message: message
}
$.ajax({
type: 'POST',
url: '../../kontakt.php',
contentType: "application/json",
dataType: 'json',
data: dataObject,
success: function(data){
alert('Items added');
},
error: function(){
console.log('You have fail');
}
//success: function(){
//var createdDiv = '<div class="divToBeCentered"><p class="dataText">Wiadomość została wysłana pomyślnie.\brDziękuję za kontakt.</p></div>';
//$('body').append(createdDiv);
//}
});
});
My PHP code
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$subject = $response[0];
$from = $response[1];
$message = $response[2];
$to = "lubycha#gmail.com";
$subject = $_POST['subject'];
$from = $_POST['email'];
$message = $_POST['message'];
$headers = "Content-Type: text/html; charset=UTF-8";
mail($to,$subject,$message,$headers);
?>
I know there is similar question already asked, but the answers didn't help me.
Thanks for helping.
I was able to get the json object and parse it on php side. Some variable might be named different, partly because some of it is pre-written code. Here are the steps I took.
Folder Structure
js/script.js
php/get_data.php
index.html
Index.html
a basic form.
<div id="feedback_panel" class="panel panel-default">
<form id="feedbackform" name="feedbackform" method="post">
<div class="form-group" id="email_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="email">E-mail:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="email#example.com" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="subject_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="subject">Subject:</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required>
<span class="help-block"> </span>
</div>
<div class="form-group" id="description_wrapper" data-toggle="popover" data-container="body" data-placement="right">
<label class="control-label" for="message">message:</label>
<textarea type="text" class="form-control" id="message" name="message" placeholder="message." required></textarea>
<span class="help-block"> </span>
</div>
<button type="submit" id="feedback_submit" class="btn btn-success">Submit</button>
</form>
</div>
script.js
upon submit, gather data and set it to an object and send to php via ajax.
$(function() {
// process the form
$('#feedbackform').submit(function(event) {
// get the form data - obj that will POSTED to get_data.php
var formData = {
'email' : $('#email').val(),
'subject' : $('#subject').val(),
'message' : $('#message').val()
};
// process the forum
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'php/get_data.php', // the url where we want to POST
data : formData, // our data object
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
if ( ! data.success) {
console.log(data);
} else {
console.log(data);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
get_data.php
receives the data from script.js, do some validations, and then send and an e-mail.
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
$email;
$subject;
$message;
//check to see if the data exist, else write an error message,
function check_data(){
$user_inputs = array();
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
return false;
}else{
$email = $_POST['email'];
array_push($user_inputs,$email);
}
if (empty($_POST['subject'])){
$errors['subject'] = 'subject is required.';
return false;
}else{
$subject = $_POST['subject'];
array_push($user_inputs,$subject);
}
if (empty($_POST['message'])){
$errors['message'] = 'message is required.';
return false;
}else{
$message = $_POST['message'];
array_push($user_inputs,$message);
}
return $user_inputs;
}
//getting array of data from check_data
$verify_data = check_data();
// 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['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
} else {
// show a message of success and provide a true success variable
$data['success'] = $verify_data;
$data['message'] = 'Success!';
//if everything is good, sent an email.
if($verify_data != false){
send_email($verify_data);
}
}
function send_email($info_data){
// person who it going
$to = 'Email, Some <some_email#mailinator.com>';
//subject of the email
$subject = $info_data[1];
$result = str_replace(' ', ' ', $info_data[2]);
$result = nl2br($result);
$result = wordwrap($result, 70, "\r\n");
//body of the email.
$message = "<html><body>";
$message .= "<p style = 'width: 400px;'>" . $result . "</p>";
$message .= "<br/>";
$message .= "</body></html>";
$headers = "From: Email, Some <some_email#mailinator.com>" . "\r\n" . 'Reply-To: '. $info_data[0] . "\r\n" ."X-Mailer: PHP/" . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
//sent mail: check to see if it was sent.
if(mail($to, $subject, $message, $headers)){
$data["went"] = "went";
$data['message'] = 'Success!';
}else{
$data["went"] = "didn't go";
$data['message'] = 'Sorry!';
}
// echo the log
echo json_encode($data);
}
?>
lot to cover, let me know if you any questions. I'll be happy to answer.
Related
Project structure is as follows
C:\xampp\htdocs\myProject\Documentation
C:\xampp\htdocs\myProject\HTML\css
C:\xampp\htdocs\myProject\HTML\images
C:\xampp\htdocs\myProject\HTML\js
C:\xampp\htdocs\myProject\HTML\videos
C:\xampp\htdocs\myProject\HTML\404.html
C:\xampp\htdocs\myProject\HTML\contact.php
C:\xampp\htdocs\myProject\HTML\index.html
C:\xampp\htdocs\myProject\PSD
I have a contact form in index.html that is controlled by a javascript file. This code stops default form submit, performs error checks and then uses ajax to make a post request to contact.php. The javascript code runs, it detects the php (see the alert in the code below just after the axjax funtion call. The value of d is the php script in the alert, but none of the debug lines in the php code get called and it never returns 'success'.
Here is the form
<form class="form-horizontal" id="phpcontactform">
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Full Name" name="name" id="name">
</div>
<div class="control-group">
<input class="input-block-level" type="email" placeholder="Email ID" name="email" id="email">
</div>
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Mobile Number" name="mobile" id="mobile">
</div>
<div class="control-group">
<textarea class="input-block-level" rows="10" name="message" placeholder="Your Message" id="message"></textarea>
</div>
<div class="control-group">
<p>
<input class="btn btn-danger btn-large" type="submit" value="Send Message">
</p>
<span class="loading"></span> </div>
</form>
here is the javascript
// JavaScript Document
$(document).ready(function() {
$("#phpcontactform").submit(function(e) {
e.preventDefault();
var name = $("#name");
var email = $("#email");
var mobile = $("#mobile");
var msg = $("#message");
var flag = false;
if (name.val() == "") {
name.closest(".control-group").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".control-group").removeClass("error").addClass("success");
} if (email.val() == "") {
email.closest(".control-group").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".control-group").removeClass("error").addClass("success");
} if (msg.val() == "") {
msg.closest(".control-group").addClass("error");
msg.focus();
flag = false;
return false;
} else {
msg.closest(".control-group").removeClass("error").addClass("success");
flag = true;
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&mobile=" + mobile.val() + "&msg=" + msg.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "http://localhost/myProject/HTML/contact.php",
cache: false,
success: function (d) {
alert("d: "+d);
$(".control-group").removeClass("success");
if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="green">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="red">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").click(function () {
$(".control-group").removeClass("success").removeClass("error");
});
})
And finally here is the php
<?php
echo "<script>console.log('Debug Objects:' );</script>";
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$msg = $_REQUEST["msg"];
echo "<script>";
echo "alert('this also works');";
echo "</script>";
$to = "myemail#gmail.com";
if (isset($email) && isset($name) && isset($msg)) {
$subject = $name."sent you a message via Raaga";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: ".$name."<br/> Email: ".$email ."<br/> Mobile: ".$mobile." <br/>Message: ".$msg;
echo "<script>alert('this maybe works');</script>";
$mail = mail($to, $subject, $msg, $headers);
if($mail)
{
echo 'success';
}
else
{
echo "<script>alert('name:'+$name);</script>";
echo 'failed';
}
}
echo "<script>alert('this finally works');</script>";
?>
I tried moving contact.php to the htdocs root but that didnt work. Have turned off all antivirus and firewalls but that didnt work either. Am at a loss. Thought php was supposed to work out of the box with xampp?
Okay so thanks to ADyson for the help. The issue was not that php isn't running, its that the mail server was not properly configured.
I'm trying to send an E-Mail via HTML-Contactform.
Therefore I created this html:
<form id="contact_form" action="sendMail.php" method="post">
<input id="firstname" name="firstname" type="text" placeholder="Vorname" value="Firstname">
<input id="lastname" name="lastname" type="text" placeholder="Nachname" value="Lastname">
<input id="mail" name="mail" type="text" placeholder="E-Mail" value="firstname.lastname#web.de">
<textarea id="msg" name="msg" placeholder="Ihre Nachricht..." >Hallo</textarea>
<p id="error_print" class="hidden"></p>
<input id="contact_submit" type="submit" title="Senden">
</form>
I am checking the inputs via jQuery and sending it via Ajax to the PHP-File and print my errors to html.
$('#contact_submit').click(function(){
var that = $('#contact_form');
var first_name = $('#firstname').val();
var last_name = $('#lastname').val();
var mail = $('#mail').val();
var msg = $('msg').val();
if(first_name == "" || last_name == "" || mail == "" || msg == "")
{
$('#error_print').removeClass("hidden");
$('#error_print').text("Bitte füllen Sie alle Felder aus");
}
else
{
if( !isValidEmailAddress(mail) )
{
$('#error_print').removeClass("hidden");
$('#error_print').text("Keine korrekte Mail");
}
else
{
if( !$('#error_print').hasClass( "hidden" ) )
{
$('#error_print').addClass("hidden");
}
var url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value)
{
var name = $(this).attr('name')
value = $(this).val();
data[name] = value;
});
//console.log(data);
$.ajax({
url: url,
type: method,
data: data,
success: function(response)
{
$('#error_print').removeClass("hidden");
$('#error_print').text("Mail wurde versendet");
},
error: function(error)
{
$('#error_print').removeClass("hidden");
$('#error_print').text("Fehler - Bitte erneut versuchen");
}
});
}
}
return false;
});
In my PHP I am sending the mail like this:
<?php
if(isset($_POST['firstname'], $_POST['lastname'], $_POST['mail'], $_POST['msg']))
{
$mail = htmlentities($_POST['mail'], ENT_QUOTES);
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
$msg = htmlentities($_POST['msg'], ENT_QUOTES);
$empfaenger = "empf#mydomain.de";
$betreff = "Kontaktaufname";
$from = "From: $fistname $lastname <$mail>";
$text = $msg;
//print_r($_POST);
mail($empfaenger, $betreff, $text, $from)
}?>
I do not know if this is the best way to do it. For that I read a lo about injection in mails. But I am not sure if my script is safe enough.
to send the mail you can try this below
<?php
ini_set("SMTP", "smtp.your_internet_service_provider.com");
ini_set("smtp_port", 25 );
ini_set("sendmail_from", "your_mail#example.com");
ini_set("auth_username", "your_mail#example.com");
ini_set("auth_password", "pwd_of_your_mail");
// For the fields $sender / $copy / $receiver, comma separated if there are multiple addresses
$sender = 'your_mail#example.com';
$receiver = 'receiver_mail#example.com';
$object = 'test msg';
$headers = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // the Content-type head for the HTML format
$headers .= 'Reply-To: '.$sender."\n"; // Mail reply
$headers .= 'From: "name_of_sender"<'.$sender.'>'."\n";
$headers .= 'Delivered-to: '.$receiver."\n";
$message = 'Hello from Aotoki !';
if (mail($receiver, $object, $message, $headers)) // Send message
{
echo 'Your message has been sent ';
}
else // error
{
echo "Your message could not be sent";
}
?>
i have this code on server 1
$("#send-mail").click(function () {
var name = $('input#name').val(); // get the value of the input field
var error = false;
if (name == "" || name == " ") {
$('#err-name').show(500);
$('#err-name').delay(4000);
$('#err-name').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var emailCompare = /^([a-z0-9_.-]+)#([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#email').val().toLowerCase(); // get the value of the input field
if (email == "" || email == " " || !emailCompare.test(email)) {
$('#err-email').show(500);
$('#err-email').delay(4000);
$('#err-email').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var comment = $('textarea#comment').val(); // get the value of the input field
if (comment == "" || comment == " ") {
$('#err-comment').show(500);
$('#err-comment').delay(4000);
$('#err-comment').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
if (error == false) {
var dataString = $('#contact-form').serialize(); // Collect data from form
$.ajax({
url: $('#contact-form').attr('action'),
type: "POST",
data: dataString,
timeout: 6000,
error: function (request, error) {
},
success: function (response) {
response = $.parseJSON(response);
if (response.success) {
$('#successSend').show();
$("#name").val('');
$("#email").val('');
$("#comment").val('');
} else {
$('#errorSend').show();
}
}
});
return false;
}
return false; // stops user browser being directed to the php file
});
then i have this other code on server 2
<?php
include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="****#hotmail.com"; //"yourmail#yoursite.com";
//from email adress
$emailFrom ="contact#yoursite.com"; //"contact#yoursite.com";
//email subject
$emailSubject = "contacto teklife";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers = 'From: TEKLIFE <jsparrow#blackpearl.com>' . PHP_EOL .
$headers .= "Reply-to: <$email>".
'X-Mailer: PHP/' . phpversion();
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
and this is the code of the contact form on server 1
<div id="successSend" class="alert alert-success invisible">
<strong>Well done!</strong>Your message has been sent.</div>
<div id="errorSend" class="alert alert-error invisible">There was an error.</div>
<form id="contact-form" method="post" action="http://guara.webposicionamientoweb.com.mx/pluton/php/mail.php">
<div class="control-group">
<div class="controls">
<input class="span12" type="text" id="name" name="name" placeholder="* Your name..." />
<div class="error left-align" id="err-name">Please enter name.</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<input class="span12" type="email" name="email" id="email" placeholder="* Your email..." />
<div class="error left-align" id="err-email">Please enter valid email adress.</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<textarea class="span12" name="comment" id="comment" placeholder="* Comments..."></textarea>
<div class="error left-align" id="err-comment">Please enter your comment.</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button id="send-mail" class="message-btn">Send message</button>
</div>
</div>
</form>
as you seen i send the post datas to other server,, if i click send on the contact form nothing happens...but the email is send ok... so i need the response so when i click send... the contact form fields are cleared... and the text appears ...message has been sent..
im complete newbee on this codes .. so some help are welcome¡¡
I ran your code through a jsfiddle.
And I got this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://guara.webposicionamientoweb.com.mx/pluton/php/mail.php. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
In your server code, try adding:
header("Access-Control-Allow-Origin: *");
or replace * with your HTML's domain. This should allow the request to pass through.
The form on my website is a simple contact form.
I would like the form to show a "success & failed" message on the same page when the form is sent/failed without reloading the page. I understand that I should use Ajax to do this but I can't get it to work because my knowledge about it is very little.
Here is the code I'm working with.
Html (single page design):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">
<label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>
<input name="name" type="text" id="name" value="" />
<label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>
<input name="email" type="text" id="email" value="" />
<label for="phonetag">Telefon</label>
<input name="phone" type="text" id="phone" value="" />
<label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>
<textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>
<label class="placeholder"> </label>
<button class="submit" name="submit">Skicka</button>
</form>
<script>
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {alert(res);
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
</script>
Php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info#mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply#mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
Your Ajax call is not working properly. Try this
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
Also as you can see i have used $('#contactus').serialize() this way you dont need to pass the form elements one by one instead serialize() will pass the whole form elements to your php page
Than in your php file echo successful if everything went well else echo error if the response is an error than show the error div
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info#mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply#mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
Change your PHP script like this:
<?php
if( isset( $_POST['submit'] )){ //checking if form was submitted
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent="Meddelande: \n\n $message";
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$mailheader = "Från: $name \n Email: $email \n Telefon: $phone \r\n";
$mailsent = mail($recipient, $subject, $formcontent, $mailheader);
if($mailsent) echo "Success"; //success if mail was sent
else echo "Ett fel uppstod!";
}
?>
Below your mail() function, simply do echo "successful";
2020 Edit
In REST API response should be always accompanied by the correct HTTP status code, with 200+ telling client that request ended up correctly processed or was otherwise good, 400+ telling client there was an error in request, and 500+ that there was a problem with the server itself. Do not use statuses inside responses, it is unnecessary duplication of the existing feature:
http_response_code(200);
echo json_encode(['message' => 'Email was sent']);
exit;
Then you can handle request and response with jQuery(assuming that you still use jQuery):
$.ajax({
url: url,
data: data,
dataType: 'json'
})
.then(function (data, textStatus, jqXHR) {
// Your 200+ responses will land here
})
.fail(function (jqXHR, textStatus, errorThrown) {
// Your 400+ responses will be caught by this handler
});
;
If you need specific status, you can get it from jqXHR parameter using jqXHR.status field.
Original answer
You can use dataType: 'json' in your ajax call.
Then you'll be able to pass status code as response key:
// form response array, consider it was success
$response = array( 'success'=> 'ok', 'message' => 'Email was sent');
echo json_encode($response);
In js then you can check data.success === 'ok' to know what's your status.
In your php script you could try this
if(mail($recipient, $subject, $formcontent, $mailheaders))
{
echo("Mail Sent Successfully"); // or echo(successful) in your case
}else{
echo("Mail Not Sent"); // or die("Ett fel uppstod!");
}
i am using correct code, still the ajax request is not sending the email content-- Can anyone have a look and suggest me what i can do better to get an email
Here is the form :
<form method="post" action="process.php">
<div class="element">
<label>Name</label>
<input type="text" name="name" class="text" />
</div>
<div class="element">
<label>Email</label>
<input type="text" name="email" class="text" />
</div>
<div class="element">
<label>Phone </label>
<input type="text" name="website" class="text" />
</div>
<div class="element">
<label>Comment</label>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
Here is the ajax request: --
<script type="text/javascript">
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website=' +
website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('enabled','false');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
and process.php as
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$website = ($_GET['website']) ?$_GET['website'] : $_POST['website'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail / no errors found
if (!$errors) {
//recipient
$to = 'info#abc.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Comment from ' . $name;
$message = '
<!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></head>
<body>
<table>
<tr><td>Name</td><td>' . $name . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Phone</td><td>' . $website . '</td></tr>
<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
echo 'Thank you! We have received your message.';
//This one for ajax
//1 means success, 0 means failed
} else {
echo '1';
}
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
Any help in the end ? Thankyou
Please browse process.php?name=jone&email=john#example.com&website=www.blabla.com&comment=blablabla to know if the problem is in the server side script.