AJAX form working in Chrome but not IE of FF - php

Hi really need some help...
First of all I know very little of jQuery / javascript, I learnt basic CSS a month back after having a website professionally built, then basic HTML, a few days ago I thought I would try my luck with jQuery but I am a total novis so if you answer please keep in mind I know almost nothing about these things - thanks!
I have been trying to make a new contact form, I have used bits of code from all over the net (so I know the code is probably very messy) anyway the resulting form seems to work fine in Chrome but in IE or FF or Safari on the submit it returns the 'Sorry, there has been a problem with this form' alert and nothing happens, I guess the PHP script is returning '1' to make this happen, but to be honest I am in over my head!
Below is the jquery....
$(function(){
//original field values
var field_values = {
//id : value
'firstname' : 'first name',
'lastname' : 'last name',
'email' : 'email address',
'phone' : 'phone number',
};
//inputfocus
$('input#lastname').inputfocus({ value: field_values['lastname'] });
$('input#firstname').inputfocus({ value: field_values['firstname'] });
$('input#email').inputfocus({ value: field_values['email'] });
$('input#phone').inputfocus({ value: field_values['phone'] });
//reset progress bar
$('#progress').css('width','0');
$('#progress_text').html('0% Complete');
//second_step
$('form').submit(function(){ return false; });
$('#submit_second').click(function(){
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#third_step').slideDown();
} else return false;
});
$('#submit_third').click(function(){
//update progress bar
$('#progress_text').html('100% Complete');
$('#progress').css('width','339px');
//prepare the fourth step
var fields = new Array(
$('#firstname').val() + ' ' + $('#lastname').val(),
$('#email').val(),
$('#phone').val(),
$('#service').val(),
$('#location').val(),
$('#mirror').val(),
$('#from').val()
);
var tr = $('#fourth_step tr');
tr.each(function(){
//alert( fields[$(this).index()] )
$(this).children('td:nth-child(2)').html(fields[$(this).index()]);
});
//slide steps
$('#third_step').slideUp();
$('#fourth_step').slideDown();
});
$('#submit_fourth').click(function(){
//Get the data from all the fields
var firstname = $('input[name=firstname]');
var email = $('input[name=email]');
var lastname = $('input[name=lastname]');
var phone = $('input[name=phone]');
//organize the data properly
var data = 'firstname=' + firstname.val() + '&email=' + email.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&service=' + $('select#service option:selected').val() + '&location=' + $('select#location option:selected').val() + '&mirror=' + $('select#mirror option:selected').val() + '&leadfrom=' + $('select#from option:selected').val();
//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
$('.summary').fadeOut('slow');
//show the success message
$('.success').fadeIn('slow');
$('#submit_fourth').attr("disabled", true);
window.location = "http://www.stackoverflow.com";
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, there has been a problem with this form. Thank you');
}
});
//cancel the submit button default behaviours
return false;
});
//back button
$('.back').click(function(){
var container = $(this).parent('div'),
previous = container.prev();
switch(previous.attr('id')) {
case 'first_step' : $('#progress_text').html('0% Complete');
$('#progress').css('width','0px');
break;
case 'second_step': $('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
break;
case 'third_step' : $('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
break;
default: break;
}
$(container).slideUp();
$(previous).slideDown();
});
});
and the HTML...
<div class="outer-formbody">
<div class="formbody">
Close
<div id="container">
<form action="#" method="post">
<!-- #second_step -->
<div id="second_step">
<h3>Book your appointment</h3>
<div class="form">
<input type="text" name="firstname" id="firstname" value="first name" />
<label for="firstname">Your First Name.<span>*</span></label><!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input type="text" name="lastname" id="lastname" value="last name" />
<label for="lastname">Your Last Name.<span>*</span></label><!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input type="text" name="email" id="email" value="email address" />
<label for="email">Your email address (not shared).<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input type="text" name="phone" id="phone" value="phone number" />
<label for="email">Your contact number (not shared).<span>*</span></label>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="submit" type="submit" name="submit_second" id="submit_second" value="" />
</div>
<!-- #third_step -->
<div id="third_step">
<h3>Book your appointment</h3>
<div class="form">
<select id="service" name="service" class="required">
<option value="">Please Select</option>
<option>Power of Attorney</option>
<option>Property Trust</option>
<option>Disabled Trust</option>
<option>Discretionary Trust</option>
<option>Other Trust</option>
<option>Protection / Insurance</option>
<option>Other Service</option>
</select>
<label for="service">Select the service you require.<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<select id="location" name="location" class="required">
<option value="">Please Select</option>
<option>Staffordshire</option>
<option>Shropshire</option>
<option>West Midlands</option>
<option>Shropshire</option>
<option>Leicestershire</option>
<option>Birmingham</option>
<option>Cheshire</option>
<option>Other</option>
</select>
<label for="location">Select your home county.<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<select id="mirror" name="mirror" class="required">
<option value="">Please Select</option>
<option>Single</option>
<option>Couple</option>
</select>
<label for="country">Single or two documents (for a couple).<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<select id="from" name="from" class="required">
<option value="">Please Select</option>
<option>NHS/School/Council</option>
<option>Friend/Family Member</option>
<option>Other Public Sector Employer</option>
<option>Private Sector Employer</option>
<option>Internet Advert</option>
<option>Google</option>
<option>Newspaper</option>
<option>NetMums</option>
<option>MumsNet</option>
<option>Other</option>
</select>
<label for="from">Where did you hear about us?<span>*</span></label>
</div><!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="back" type="button" value="" />
<input class="submit" type="submit" name="submit_third" id="submit_third" value="" />
</div>
<!-- #fourth_step -->
<div id="fourth_step">
<h3>Book your appointment</h3>
<div class="form">
<div class="success">
</br>
</br>
</br>
</br>
</br>
<h3>Booking Submitted. <span>Please Wait . . .</span></h3>
</div>
<div class="summary">
<h3>Summary</h3>
<table class="table">
<tr><td>Name</td><td></td></tr>
<tr><td>Email</td><td></td></tr>
<tr><td>Phone</td><td></td></tr>
<tr><td>Service</td><td></td></tr>
<tr><td>Location</td><td></td></tr>
<tr><td>Single/Couple</td><td></td></tr>
<tr><td>From</td><td></td></tr>
</table>
</div>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="back" type="button" value="" />
<input class="send submit" type="submit" name="submit_fourth" id="submit_fourth"value="" />
</div>
</form>
</div>
<div id="progress_bar">
<div id="progress"></div>
<div id="progress_text">0% Complete</div>
</div>
<div></div>
</div></div>
</div>
and the PHP script to process the form....
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$firstname = ($_GET['firstname']) ? $_GET['firstname'] : $_POST['firstname'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$lastname = ($_GET['lastname']) ?$_GET['lastname'] : $_POST['lastname'];
$phone = ($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$service = ($_GET['service']) ?$_GET['service'] : $_POST['service'];
$location = ($_GET['location']) ?$_GET['location'] : $_POST['location'];
$mirror = ($_GET['mirror']) ?$_GET['mirror'] : $_POST['mirror'];
$leadfrom = ($_GET['leadfrom']) ?$_GET['leadfrom'] : $_POST['leadfrom'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//if the errors array is empty, send the mail
if (!$errors) {
//recipient
$to = 'Alex <clansey2004#yahoo.co.uk>';
//sender
$from = $firstname . ' <' . $email . '>';
//subject and the html message
$subject = 'Lead from ' . $firstname;
$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>
</Br>
<table>
<tr><td>First Name</td><td>' . $firstname . '</td></tr>
<tr><td>Lastname</td><td>' . $lastname . '</td></tr>
<tr><td>Location</td><td>' . $location . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Phone</td><td>' . $phone . '</td></tr>
<tr><td>Service</td><td>' . $service . '</td></tr>
<tr><td>Mirror</td><td>' . $mirror . '</td></tr>
<tr><td>Lead From</td><td>' . $leadfrom . '</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) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} 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;
}
?>
I am sure I have made a silly mistake - any help would be greatly appreciated!!
Thanks

My guess is you need to urlescape the values with encodeURIComponent(), especially those with a slash inside.

Related

Send multiple contact form from one page via AJAX

I have 3 contact form in one page ( Header, Body, Footer ). The code works correctly if sent from one form. I want to use one AJAX request for all forms. That is, when you click on the submit button, so that the code checks if this form then send data to php. How can i do it right? I use the hasClass () method of jquery, but I have errors in the console
HTML:
Footer Form
<form id="contact-form1" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="name" placeholder="Name">
<input type="text" class="simple-input" id="email" placeholder="Email address">
<textarea class="quession-input" id="msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" class="checked-checkbox" name="myCheckboxes[]" id="box1" checked="checked" value="true" />
<label for="box1" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn submit1"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
Another Form
<form id="contact-form" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="hy_name" placeholder="Name">
<input type="text" class="simple-input" id="hy_email" placeholder="Email address">
<textarea class="quession-input" id="hy_msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" id="box3" class="checked-checkbox" checked="checked" />
<label for="box3" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn hy-submit submit2"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
jQuery:
jQuery('#submit').on('click', function(e) {
e.preventDefault();
if(e.hasClass('submit1')) {
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var msg = jQuery('#msg').val();
var subj = jQuery('#subj').val();
var data = "action=send_email&name=" + name + "&email=" + email + "&msg=" + msg + "&subj=" + subj + "&myCheckboxes=" + choice,
} elseif (e.hasClass('submit2')) {
var hy_name = jQuery('#hy_name').val();
var hy_email = jQuery('#hy_email').val();
var hy_msg = jQuery('#hy_msg').val();
var data = "action=send_email&name=" + hy_name + "&email=" + hy_email + "&msg=" + hy_msg + "&myCheckboxes=" + choice,
}
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
var chkElem = document.getElementsByName("myCheckboxes[]");
var choice ="";
for(var i=0; i< chkElem.length; i++)
{
if(chkElem[i].checked)
choice = choice + chkElem[i].value;
}
jQuery.ajax({
type: "post",
url: "/wp-admin/admin-ajax.php",
data: data;
success: function (response) {
jQuery('#contact-form input').val('');
jQuery('#contact-form textarea').val('');
jQuery('.submit').text('Done!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
PHP:
add_action('wp_ajax_nopriv_send_email', 'send_email');
add_action('wp_ajax_send_email', 'send_email');
function send_email() {
$checkbox = $_POST['myCheckboxes'];
if (isset($checkbox)) {
echo $checkbox;
}
$headers = 'Content-Type: text/html; charset="utf-8"';
$name = $_POST['name'];
$hy_name = $_POST['hy_name'];
$from = 'contact#xelon.ch';
$to = 'yaver.mammadov#gmail.com';
$email = $_POST['email'];
$hy_email = $_POST['hy_email'];
$msg = $_POST['msg'];
$hy_msg = $_POST['hy_msg'];
$subject = 'Footer form: ' . $_POST['email'];
$message .= (!empty($name)) ? '<p><strong>User Name</strong> : ' . $name .' </p>' : '';
$message .= (!empty($email)) ? '<p><strong>User Email</strong> : '. $email .'</p>' : '';
$message .= (!empty($msg)) ? '<p><strong>User Message</strong> : '.$msg .'</p>' : '';
$message .= (!empty($checkbox)) ? '<p><strong>Checkboxs</strong> : '.$checkbox .'</p>' : '';
$message .= '</body></html>';
echo mail($to, $subject, $message, $headers);
return $msg;
die();
}
You can use method serialize(), and use a class to identifique buttons submit. Using two identical ids on one page is not good practice.
If you use the class .submit per example in each button submit:
$('.submit').on('click', function(e) {
e.preventDefault();
var data = $(this).closest('form').serialize();
[...]
}

PHP $_POST value not appearing in email for PHPMailer

Greetings everyone,
I have a problem where the value for the student name and programme not appearing the email after I send the email through PHPMailer. I am using PHP PDO and I have checked that the student name and programme is under a form. Other values are appearing just fine in the email such as the image below:
I am not sure whether it is the quotation marks making problem or other things.
Below are my code for the student-appointment-form.php file:
<?php
require ("global-include-student.php");
require ('PHPMailer/PHPMailerAutoLoad.php');
require ('PHPMailer/smtp-credentials.php');
//timezone for Malaysia
date_default_timezone_set("Asia/Kuala_Lumpur");
//Condition when the submit button is clicked
if(isset($_POST["btnSubmit"])){
try
{
$appointment_date = date('Y-m-d',strtotime($_POST['appointment_date']));
//$appointment_date = date("Y-m-d H:i:s");
// Inserting the data into database
$insert_query = "INSERT INTO appointment (appointment_type, appointment_date, appointment_time, student_id, lecturer_id, field, venue, remarks, appointment_status)
VALUES ('".$_POST["appointment_type"]."',
'".$appointment_date."',
'".$_POST["appointment_time"]."',
'".$_POST["student_id"]."',
'".$_POST["lecturer_id"]."',
'".$_POST["field_id"]."',
'".$_POST["venue"]."',
'".$_POST["remarks"]."',
'".$_POST["appointment_status"]."'
)";
//PHPMailer set up
$field_name = $_POST['field_name'];
$lect_name = $_POST['lect_name'];
$lect_email = $_POST['lect_email'];
$student_name = $_POST['student_name'];
$programme = $_POST['programme'];
$output='<strong>Greetings from STULEC,</strong> <br/>
<p>There is an appointment request from ' . $student_name . ' who is in the ' . $programme . ' programme.</p>
The appointment details are such as below: <br/>
<ul>
<li>Appointment Type: '. $_POST['appointment_type'] .'</li>
<li>Appoinment Date: '. $_POST['appointment_date'] .'</li>
<li>Appointment Time: '. $_POST['appointment_time'] . '</li>
<li>Venue: '. $_POST['venue'] .' </li>
<li>Course Field: '. $_POST['field_name'] .' </li>
<li>Remarks: '. $_POST['remarks'] . '</li>
</ul>
</p>
<p>Please approve the appointment request by logging into STULEC. Thank you.';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = EMAIL; // SMTP username
$mail->Password = PASS; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('stulec#edu.my', 'STULEC'); //From sender
$mail->addAddress($lect_email, $lect_name); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'STULEC | Appointment Request from Student';
$mail->Body = $output;
$mail->CharSet = 'utf-8';
$mail->ContentType = 'text/html';
if (($db->query($insert_query)) && $mail->send())
{
echo "<script type= 'text/javascript'>alert('An appointment has been made with the lecturer. Please wait until the lecturer responds to your request.');";
echo 'window.location= "student-view-pending-appointment.php"';
echo "</script>";
}
else
{
echo "<script type= 'text/javascript'>alert('Error: The appoinment cannot be made!');";
echo 'window.location= "student-appointment-form.php"';
echo "</script>";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>STULEC | Appointment Form</title>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!--Include header-->
<?php include 'include/header.php' ?>
<!--Include sidebar-->
<?php include 'include/sidebar.php' ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1 align='center'>
<u>Appointment Form</u>
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="box box-default">
<div class="box-body">
<div class="row">
<div class="col-md-12">
<!-- form start -->
<form class="form-horizontal" action="" method="POST">
<?php
//select student details from the database
$sql = "SELECT username, name, role, department, programme, profile_pic, programme_name FROM users
LEFT JOIN programme AS programme ON programme.programme_id = users.programme
WHERE user_id = :user_id";
$stmt = $db->prepare($sql);
if ($stmt->execute(array('user_id' => $_SESSION['user_id'])))
{
while($row = $stmt->fetch())
{
//fetch the rows
$username = $row['username'];
$name = $row['name'];
$programme = $row['programme_name'];
echo "
<!--Name-->
<div class='form-group'>
<label for='Name' class='col-sm-2 control-label'>Name</label>
<div class='col-sm-10'>
<input type='text' class='form-control' name='student_name' id='student_name' value='". $row['name']."' disabled>
<input type='hidden' class='form-control' name='student_id' id='student_id' value=" . $row['username'] ." />
</div>
</div>
<!--Programme-->
<div class='form-group'>
<label for='Programme' class='col-sm-2 control-label'>Programme</label>
<div class='col-sm-10'>
<input type='text' class='form-control' name='programme' id='programme' value=" . $row['programme_name'] ." disabled>
</div>
</div>
";
}
}
?>
<!--Consultation Type-->
<div class='form-group'>
<label for='ConsultationType' class='col-sm-2 control-label'>Consultation Type</label>
<div class='col-sm-10'>
<select class='form-control' name='appointment_type'>
<option selected='selected' name='assignment_discussion' value='Assignment Discussion'>Assignment Discussion</option>
<option name='advisory_session' value='Advisory Session'>Advisory Session</option>
<option name='fyp_discuss' value='Final Year Project Discussion'>Final Year Project Discussion</option>
</select>
</div>
</div>
<!--Field name-->
<div class='form-group'>
<label for='Course' class='col-sm-2 control-label'>Course Field</label>
<div class='col-sm-10'>
<select class='form-control' name='field_id' id='field_id' required>
<option value=''>Please select a course field</option>
<?php
//Display field name
$select_field_query = "SELECT field_id, field_name FROM course_field
LEFT JOIN field_programme ON field_programme.field = course_field.field_id
LEFT JOIN users ON users.programme = field_programme.programme
LEFT JOIN programme ON programme.programme_id = field_programme.programme
WHERE field_programme.programme = :programme AND users.username = :student";
$field_statement = $db->prepare($select_field_query);
$field_statement->bindParam(':programme', $_SESSION['programme']);
$field_statement->bindParam(':student', $_SESSION['username']);
$field_statement->execute();
while ($row = $field_statement->fetch(PDO::FETCH_ASSOC))
{
echo
"<option value='" . $row['field_id'] . "'>" . $row['field_name'] . "</option>";
}
?>
</select>
</div>
</div>
<!--Hidden course field_name-->
<input type='hidden' id='field_name' name='field_name'>
<!--Lecturer name selection-->
<div class='form-group'>
<label for='Lecturer' class='col-sm-2 control-label'>Lecturer</label>
<div class='col-sm-10'>
<select class='form-control' name='lecturer_id' id='lecturer_id'>
<option>-</option>
</select>
</div>
</div>
<!--Hidden lecturer email-->
<input type='hidden' id='lect_email' name='lect_email'>
<!--Hidden lecturer name-->
<input type='hidden' id='lect_name' name='lect_name'>
<!-- Date -->
<div class='form-group'>
<label for='Date' class='col-sm-2 control-label'>Date</label>
<div class='col-sm-4'>
<div class='input-group date'>
<input type='text' class='form-control pull-right' name='appointment_date' id='datepicker' required>
<div class='input-group-addon'>
<i class='fa fa-calendar'></i>
</div>
</div><!-- /.input group -->
</div><!-- /.form group -->
</div>
<!-- Time -->
<div class='form-group'>
<label for='Time' class='col-sm-2 control-label'>Time</label>
<div class='col-sm-4'>
<div class='input-group time'>
<input type='text' class='form-control timepicker' name='appointment_time' id='timepicker' required>
<div class='input-group-addon'>
<i class='fa fa-clock-o'></i>
</div>
</div><!-- /.input group -->
</div>
</div><!-- /.form group -->
<!--Venue-->
<div class='form-group'>
<label for='Venue' class='col-sm-2 control-label'>Venue</label>
<div class='col-sm-10'>
<select class='form-control' name='venue'>
<option selected='selected' name='in_front_dpmt' value='In front of department'>In front of department</option>
<option name='library' value='Library'>Library</option>
<option name='consultation_room' value='Consultation Room'>Consultation Room</option>
</select>
</div>
</div>
<!--Remarks-->
<div class='form-group'>
<label for='Remarks' class='col-sm-2 control-label'>Remarks</label>
<div class='col-sm-10'>
<input type='text' class='form-control' name='remarks' id='remarks' placeholder='Eg: Related to the Local Area Network question' required>
</div>
</div>
<!--Hidden Appointment Status which is set as Pending when form is submitted-->
<input type="hidden" value="Pending" name="appointment_status">
<!--Submit button-->
<div class="box-footer">
<button type="submit" class="btn btn-success pull-right" name="btnSubmit" id="btnSubmit">Submit</button>
</div>
</form>
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- ./wrapper -->
<!-- Page script -->
<script>
$(function ()
{
//Change lecturer when different course field is selected
$("#field_id").change(function () {
if ($('#field_id option:selected').val() != "")
{
$.ajax({
type: 'POST',
url: 'ajax-field-lecturer.php',
data: { 'field_id' : $('#field_id option:selected').val() },
success: function(data) {
$('#lecturer_id').empty();
var lect = JSON.parse(data);
$.each(lect, function( index, lectObj )
{
if (index == 0)
{
$('#lect_email').val(lectObj.email);
$('#lect_name').val(lectObj.name);
$('#field_name').val(lectObj.field_name);
}
$('#lecturer_id').append("<option value='"+lectObj.username+"'>"+lectObj.name+"</option>");
});
},
error: function(data) {
alert(data);
}
});
}
else
{
$('#lecturer_id').empty();
}
});
//Change lecturer email when different the lecturer is selected
$("#lecturer_id").change(function () {
if ($('#lecturer_id option:selected').val() != "")
{
$.ajax({
type: 'POST',
url: 'ajax-email-lecturer.php',
data: { 'lecturer_id' : $('#lecturer_id option:selected').val() },
success: function(data) {
//alert(data);
$('#lect_email').empty();
var lect = JSON.parse(data);
$('#lect_email').val(lect[0].email);
},
error: function(data) {
alert(data);
}
});
}
else
{
$('#lect_email').empty();
}
});
//Show lecturer name
$("#lecturer_id").change(function () {
if ($('#lecturer_id option:selected').val() != "")
{
$.ajax({
type: 'POST',
url: 'ajax-name-lecturer.php',
data: { 'lecturer_id' : $('#lecturer_id option:selected').val() },
success: function(data) {
//alert(data);
$('#lect_name').empty();
var lect = JSON.parse(data);
$('#lect_name').val(lect[0].name);
},
error: function(data) {
alert(data);
}
});
}
else
{
$('#lect_name').empty();
}
});
//Show course field name
$("#field_id").change(function () {
if ($('#field_id option:selected').val() != "")
{
$.ajax({
type: 'POST',
url: 'ajax-field-name.php',
data: { 'field_id' : $('#field_id option:selected').val() },
success: function(data) {
//alert(data);
$('#field_name').empty();
var lect = JSON.parse(data);
$('#field_name').val(lect[0].field_name);
},
error: function(data) {
alert(data);
}
});
}
else
{
$('#field_name').empty();
}
});
//Date picker
$( "#datepicker" ).datepicker({
dateFormat: "yyyy-MM-dd"
});
//Timepicker
$('.timepicker').timepicker({
showInputs: false
})
})
</script>
</body>
</html>
Please guide me on how to solve this problem. Thank you.
In your form your student_name and programme fileds are disabled, and not posted.
Consider using hidden inputs to post values or change disable to readonly (not sure if it the latter works tho).

What language(s) i have to use to make a success or an error situation for PHP mail form?

I've got a PHP mail form which is already coded :
And I would like to appear a banner i coded using CSS and jQuery, if the form succeed to send a mail, or not :
I would like to know what language could I use to make it happens ? What are your advices ?
Here is my html code for the form :
<form id="my_form" enctype="multipart/form-data" method=POST action=formmail.php>
<input type="hidden" name="subject" value="formmail">
<!-- PSEUDO -->
<p>
<h3>
PSEUDO
<font class="color-red">
* :
</font>
<span class="padding1"><input type="text" class="form-control" name="pseudo" aria-required="true" aria-invalid="false"></span></p><br>
<!-- EMAIL -->
<p>
EMAIL
<font class="color-red">
* :
</font>
<span class="your-email padding1"><input type="email" class="form-control" name="email" aria-required="true" aria-invalid="false"></span></p><br>
<!-- MOTO -->
<p>
QUOTE
<font class="color-red">
* :
</font>
<span class="moto padding1"><input type="moto" class="form-control" name="moto" aria-invalid="false"></span> </p><br>
<!-- LINK OF THE GIF -->
<p>
LINK OF THE GIF
<font class="color-red">
* :
</font>
<span class="link-url padding1"><input type="link_url" class="form-control" name="link_url" aria-invalid="false"></span> </p><br>
<!-- RECAPTCHA -->
<div align="center">
<p><div class="g-recaptcha" data-sitekey="6LehFQoTAAAAAMHlOs6vgktrCdFo485AoHwmp9Cp"></div></p><br><h3>
<!-- SUBMIT -->
<p><input type="image" src="img/submitbutton.png" value="send"/><img class="ajax-loader" src="http://s584101063.onlinehome.fr/wp-content/plugins/contact-form-7/images/ajax-loader.gif" alt="Envoi en cours ..." style="visibility: hidden;"></p></div>
</div>
</form>
Here is my PHP :
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "MY_SECRET_RECAPTCHA";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
Header("Location: MY_WEBSITE");
$TO = "MY_MAIL";
$subject = "Submission";
$h = "From: " . $_POST['email'];
$pseudo = $_POST['pseudo'];
$email = $_POST['email'];
$link_url = $_POST['link_url'];
$moto = $_POST['moto'];
$HTTP_POST_VARS = $_POST;
$message = "Pseudo : " . $pseudo . "\n\n " . "Email : " . $email . " \n\n" . "Text : " . $moto . "\n\n " . "URL du GIF : " . $link_url;
mail($TO, $subject, $message, $h);
}
else
{
$result
}
}
?>
VERY basic idea:
$test=mail($TO, $subject, $message, $h);
if($test){
echo 'EmAIL WORK';
}else{
echo 'EmAIL Fail';
}
EDIT : The Dagon's answer works very well, but my question was not clear, here is what I found to do what I wanted :
Thanks Dagon, but it was not really what I expected to do,
I found how to do it, it works :)
<?php
if(isset($_GET['id']) AND $_GET['id']==2) {
echo '<script type="text/javascript">';
echo '
$("#success-bar").css("display", "inline");
$("#success-bar").addClass("animated bounceInDown")
$("#success-bar").one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",
function(){
$("#success-bar").removeClass("animated bounceInDown")
$( "#close2" ).click(function() {
$("#success-bar").addClass("animated bounceInUp")
$("#success-bar").hide()
$("#success-bar").one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend",
function(){
$("#success-bar").addClass("animated bounceInDown")
});
});
});';
echo '</script>';
}
elseif(isset($_GET['id']) AND $_GET['id']==3) {
echo 'FALSE';
}
?>

jquery-mobile ajax runs one more time after every failed pass

I have my html page where people can sign up, which calls my php page for checks and inputs to db,
If i get an error, for example someone does not select their gender it alerts the user as it should. Problem is if the user does not select there gender and submits again the ajax is called twice now and i get two of the same alert messages, If done once more i get three alert messages and this contiunes growing on every press etc. How can i stop this happening.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="css/logout-button.min.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.min.css" />
<link rel="stylesheet" href="css/my.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script src="js/jquery.mobile-1.3.0.min.js"></script>
<script src="js/jquery.cookies.2.2.0.min.js"></script>
<script src="js/account-login.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="account-signup">
<script>
function submitForm() {
$(document).ready(function() {
$("form#signupForm").submit(function() {
var form_data = $('#signupForm').serialize();
$.ajax({
type: "POST",
url: "ajaxResponder.php",
dataType: 'html',
data: form_data,
complete: function(data){
if(data.responseText == 'yes'){
alert("Your Account has been created");
$.mobile.changePage( "account-login.html", { transition: "slide"} );
}else {
alert(data.responseText);
}
}
});
return false;
});
});
}
</script>
<div data-theme="a" data-role="header">
<a data-role="button" href="account-login.html" data-transition="slide"
data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<h3>
Sign-Up
</h3>
</div>
<div data-role="content">
<form id="signupForm" name="signupForm">
<input name="method" id="method" placeholder="method" value="account-signup" type="hidden" />
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="forename">
Forename *
</label>
<input name="forename" id="forename" placeholder="Forename" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="surname">
Surname *
</label>
<input name="surname" id="surname" placeholder="Surname" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<label for="gender">Gender</label>
<select name="gender" id="gender" data-native-menu="false">
<option>Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div data-role="fieldcontain">
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("ajaxResponder.php?method=account-signup-countries",function(data){
items+='<option value="Select Country">Select Country</option>';
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#countries").html(items);
$("#countries").trigger("change");
});
});
</script>
<legend>Country *</legend>
<select name="countries" id="countries" data-native-menu="false">
</select>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="email">
Email *
</label>
<input name="email" id="email" placeholder="Email" value="" type="text" />
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<label for="password">
Password *
</label>
<input name="password" id="password" placeholder="Password" value="" type="password" />
<label for="confirm">
Confirm Password *
</label>
<input name="confirm" id="confirm" placeholder="Confirm" value="" type="password" />
</fieldset>
</div>
<input data-theme="b" value="Sign-Up" type="submit" onclick="submitForm()" />
</form>
</div>
</div>
</body>
</html>
my php
case 'account-signup':
$password_minlength = 6;
$password_maxlength = 40;
$message == "";
function validusername($username) {
$allowedchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'";
for ($i = 0; $i < strlen($username); ++$i)
if (strpos($allowedchars, $username[$i]) === false)
return false;
return true;
}
$forename= $_POST["forename"];
$surname= $_POST["surname"];
$email= $_POST["email"];
$password= $_POST["password"];
$confirm= $_POST["confirm"];
$day = $_POST["select-choice-day"];
$month = $_POST["select-choice-month"];
$year = $_POST["select-choice-year"];
$country = $_POST["countries"];
$gender = $_POST["gender"];
if ($day =='Day' or $month == 'Mon' or $year =='Year')
$message = "You Need to fill in Your DOB";
if ($gender =='Gender')
$message ="Please select your Gender";
if ($country == "Select Country")
$message ="Please select a Country";
if (empty($password) || empty($forename) || empty($surname) || empty($email) || empty($confirm) )
$message = "All fields required to be filled in";
elseif ($password != $confirm)
$message = "Your passwords do not match";
elseif (strlen($password) < $password_minlength)
$message = sprintf("Your password needs to be more than $password_minlength char");
elseif (strlen($password) > $password_maxlength)
$message = sprintf("Your password needs to be less than $password_maxlength char");
elseif (!validusername($forename))
$message = "Invalid characters used in your forename";
elseif (!validusername($surname))
$message = "Invalid characters used in your surname";
elseif (!validemail($email))
$message = "A Valid email address is required";
if ($message == "") {
// check if email addy is already in use
$a = (#mysql_fetch_row(#SQL_Query_exec("select count(*) from users where email='$email'")));
if ($a[0] != 0)
$message = "Email Address $email has already signed up. Please use account-recovery ";
}
if ($message == "") {
$signupclass = '1';
$status = "confirmed";
$dob = "$year-$month-$day";
$secret = mksecret(); //generate secret field
$password = passhash($password);// hash the password
$forename1 = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($forename))));
$surname1 = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($surname))));
SQL_Query_exec("INSERT INTO users (forename,surname, password, secret, email, status, added, last_access, country, gender,dob, stylesheet, language, class, ip) VALUES (" .
implode(",", array_map("sqlesc", array($forename1,$surname1, $password, $secret, $email, $status, get_date_time(), get_date_time(), $country, $gender,$dob, $site_config["default_theme"], $site_config["default_language"], $signupclass, getip()))).")");
$message="yes";
}
echo "$message";
break;
You have an error in your javascript, when calling function, you don't need these lines:
$(document).ready(function() {
$("form#signupForm").submit(function() {
First of all you dont need document ready because you are not waiting for that state. Second thing, if you are using inline hjavascript with onclick=... you dont need to bind a submit event to the form.
Basically each time you call in again you are binding submit event to the form.
Third thing, this would not happen if validation was implemented on a client side, so think about that. You can easily implement jQuery Validate plugin.
My advice to you would be, remove onclick event from this line:
<input data-theme="b" value="Sign-Up" type="submit" onclick="submitForm()" />
Remove onclick function and just use everything like this:
$(document).ready(function() {
$('#signupForm').off('submit').on('submit',function(e) {
var form_data = $('#signupForm').serialize();
$.ajax({
type: "POST",
url: "ajaxResponder.php",
dataType: 'html',
data: form_data,
complete: function(data){
if(data.responseText == 'yes'){
alert("Your Account has been created");
$.mobile.changePage( "account-login.html", { transition: "slide"} );
}else {
alert(data.responseText);
}
}
});
return false;
});
});
Because of submit event this code will trigger when you press submit button, no need for onclick. And notice how submit is handled now:
$('#signupForm').off('submit').on('submit',function(e) {
This will prevent multiple submit events from happening.

Multi Stage Contact Form - PHP

http://webexpedition18.com/download/signup_form_WebExpedition18/
Hi Guys,
The above multi-stage contact form works great for my own project. It looks great and does the trick but i am stumped when trying to get the information submitted via email.
So i have a nice looking form but it wont send any information so is pretty useless to me. Even when i just upload the untouched demo files from the tutorial site, it still doesn't work.
Here's the html i have:
<div id="container">
<form action="contact.php" method="post">
<div id="first_step">
<div class="form">
<label for="full-name">Full Name:</label> <input id="username"
name="full-name" style="margin-bottom:10px;" type="text" value=
""> <label for="telephone">Telephone:</label> <input id=
"username" name="telephone" style="margin-bottom:10px;" type=
"text" value=""> <label for="email-address">Email
Address:</label> <input id="username" name="email-address"
style="margin-bottom:10px;" type="text" value="">
</div>
<div class="clear"></div><input class="submit" id="submit_first"
name="submit_first" type="submit" value="Next">
</div>
<div class="clear"></div>
<div id="second_step">
<div class="form">
<label for="company-name">Company Name (if you have
one):</label> <input id="username" name="company-name" style=
"margin-bottom:10px;" type="text" value=""> <label for=
"existing-website">Existing Website (if you have one):</label>
<input id="username" name="existing-website" style=
"margin-bottom:10px;" type="text" value=""> <label for=
"existing-domain">What domain would you like the new website to
be on?</label> <input id="username" name="existing-domain"
style="margin-bottom:10px;" type="text" value="">
</div>
<div class="clear"></div><input class="submit" id="submit_second"
name="submit_second" type="submit" value="Next">
</div>
<div class="clear"></div>
<div id="third_step">
<div class="form">
<label for="which-package">Which package would you
like?:</label>
<p><label><input id="RadioGroup1_0" name="RadioGroup1" type=
"radio" value="Standard"> Standard</label> <label><input id=
"RadioGroup1_1" name="RadioGroup1" type="radio" value=
"Business"> Business</label> <label><input id="RadioGroup1_2"
name="RadioGroup1" type="radio" value="Professional">
Professional</label></p><label for="which-template">Which
template would you like?:</label>
<p><label><input id="RadioGroup2_0" name="RadioGroup2" type=
"radio" value="1"> 1</label> <label><input id=
"RadioGroup2_1" name="RadioGroup2" type="radio" value=
"2"> 2</label> <label><input id="RadioGroup2_2"
name="RadioGroup2" type="radio" value="3">
3</label></p>
<div class="clear"></div>
</div>
<div class="clear"></div><input class="submit" id="submit_third"
name="submit_third" type="submit" value="Next">
</div>
<div class="clear"></div>
<div id="fourth_step">
<div class="form">
<h2>All done ...</h2>
<p style="margin-top:30px;">Press 'Submit' and we'll send you
everything you need to get you up and running.</p>
</div>
<div class="clear"></div><input class="send submit" id=
"submit_fourth" name="submit_fourth" type="submit" value="Submit">
</div>
</form>
</div>
</div>
The submit button just doesn't do anything. I have tried a number of different php form handler codes in my contact.php file but i still get nothing.
Any help is hugely appreciated guys. I'm getting really desperate now after 6 hours trying with this.
Thank you.
The JS file that comes with the demo is:
$(function(){
//original field values
var field_values = {
//id : value
'username' : 'username',
'password' : 'password',
'cpassword' : 'password',
'firstname' : 'first name',
'lastname' : 'last name',
'email' : 'email address'
};
//inputfocus
$('input#username').inputfocus({ value: field_values['username'] });
$('input#password').inputfocus({ value: field_values['password'] });
$('input#cpassword').inputfocus({ value: field_values['cpassword'] });
$('input#lastname').inputfocus({ value: field_values['lastname'] });
$('input#firstname').inputfocus({ value: field_values['firstname'] });
$('input#email').inputfocus({ value: field_values['email'] });
//reset progress bar
$('#progress').css('width','0');
$('#progress_text').html('0% Complete');
//first_step
$('form').submit(function(){ return false; });
$('#submit_first').click(function(){
//remove classes
$('#first_step input').removeClass('error').removeClass('valid');
//ckeck if inputs aren't empty
var fields = $('#first_step input[type=text], #first_step input[type=password]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<4 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
if( $('#password').val() != $('#cpassword').val() ) {
$('#first_step input[type=password]').each(function(){
$(this).removeClass('valid').addClass('error');
$(this).effect("shake", { times:3 }, 50);
});
return false;
} else {
//update progress bar
$('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
//slide steps
$('#first_step').slideUp();
$('#second_step').slideDown();
}
} else return false;
});
$('#submit_second').click(function(){
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#third_step').slideDown();
} else return false;
});
$('#submit_third').click(function(){
//update progress bar
$('#progress_text').html('100% Complete');
$('#progress').css('width','339px');
//prepare the fourth step
var fields = new Array(
$('#username').val(),
$('#password').val(),
$('#email').val(),
$('#firstname').val() + ' ' + $('#lastname').val(),
$('#age').val(),
$('#gender').val(),
$('#country').val()
);
var tr = $('#fourth_step tr');
tr.each(function(){
//alert( fields[$(this).index()] )
$(this).children('td:nth-child(2)').html(fields[$(this).index()]);
});
//slide steps
$('#third_step').slideUp();
$('#fourth_step').slideDown();
});
$('#submit_fourth').click(function(){
//send information to server
alert('Sent. Thank you!');
});
});
And the php is used within my contact.php file was:
<?php
$errors = '';
$myemail = 'yourname#website.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>
$('form').submit(function(){ return false; }); tells that submit should return false

Categories