I have designed a Sidebar Floating Form with PhP/Ajax which is working and sending submission to my targeted email. Here is the Link: http://logohour.com/form.html but when a visitor fill and submit the form successfully it routes him to another page for the confirmation.
This shouldn't be like this and must be stick to the homepage with popup Message as per my coding:
<div id="sendingMMessage" class="statusMessage"> <p>Sending your message. Please wait...</p> </div>
<div id="successMMessage" class="statusMessage"> <p>Thanks for sending your message! We'll get back to you shortly.</p> </div>
Below you may find my Ajax & PHP for reference:
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );
// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";
// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {
$msgToSend = "Name: $Name\n";
$msgToSend .= "Email: $Email\n";
$msgToSend .= "Phone: $Phone\n";
$msgToSend .= "Sender Country: $Country\n";
$msgToSend .= "Sender Select: $Select\n";
$msgToSend .= "Message: $Message";
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $Name . " <" . $Email . ">";
$ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
var messageDDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$(init);
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false; });
// When the "Cancel" button is clicked, close the form
$('#cancel').click(function() {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);
});
// When the "Escape" key is pressed, close the form
$('#contact_form').keydown(function(event) {
if (event.which == 27) {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);}});}
// Submit the form via Ajax
function submitFForm() {
var contact_form = $(this);
// Are all the fields filled in?
if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
// No; display a warning message and return to the form
$('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
contact_form.fadeOut().delay(messageDDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMMessage').fadeIn();
contact_form.fadeOut();
$.ajax({
url: contact_form.attr('action') + "?ajax=true",
type: contact_form.attr('method'),
data: contact_form.serialize(),
ssuccess: submitFFinished }); }
// Prevent the default form submission occurring
return false; }
// Handle the Ajax response
function submitFFinished(response) {
response = $.trim(response);
$('#sendingMMessage').fadeOut();
if (response == "ssuccess") {
// Form submitted ssuccessfully:
// 1. Display the ssuccess message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#Name').val("");
$('#Email').val("");
$('#Phone').val("");
$('#Country').val("");
$('#Selct').val("");
$('#Message').val("");
$('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#contact_form').delay(messageDDelay + 500).fadeIn(); } }
Below the simple ajax form submission. Hope it will help your need.
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(function () {
$('form#consultationForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'receivedConfirmation.php',
data: $(this).serialize(),
success: function (result) {
console.log(result);
$('#receivedStatus').attr('style','display:block');
$('#receivedStatus').html(result);
}
});
e.preventDefault();
});
});
</script>
<form id="consultationForm" method="post">
Firstname: <input name="fname" />
Lastname: <input name="lname" />
<div style='clear:both;'></div>
<input type="submit" name="submit" value="save"/>
<input type="reset" name="cancel" value="cancel"/>
</form>
<div id='receivedStatus' style='display:none;'></div>
receivedConfirmation.php
<?php
echo "<PRE>";
print_r($_POST);
echo "</PRE><br>";
//do your DB stuffs here and finally echo your response based on success or failure
echo "Thanks for sending your message! We'll get back to you shortly.";
echo "<br>Click your browser's Back button to return to the page."
?>
First you have to avoid the normal form submission for this form and you can do this by using normal button instead of submit button.
<input type="button" id="sendMMessage" name="sendMMessage" value="Submit">
Execute a javascript ajax submit code onclick of sendMMessage id.
and this will solve your problem.
Updated answer :
$( "#target" ).click(function() {
// put your ajax form submit code here
$.ajax({
type: "POST",
url: 'http://logohour.com/sidebar-form.php',
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data); // show response from the php script.
}
});
});
If you are still unclear about this I will explain you more detail.
thanks.
Related
I'm have trouble resetting a from after submission. Currently I'm relying on auto refreshing the page to. I've never used php but I managed to hack something a php form set up with a MySQL database.
This form is hidden in a div which toggles in and out in visibility. So the webpage acts like a noticeboard the form is on the same page.
I have used a JQuery function to reset the form. But currently the div still displays the echo.
$(document).ready(function() {
$('submit').click(function() {
$('submission')[0].reset();
});
});
My current set up is this:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO mvmv3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('mvmv_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}else {
?>
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" required autocomplete="off">
<input name = "email" type = "text"
id = "email" autocomplete="off">
<textarea name = "proposal" type = "textarea" size="100"cols="40" rows="20"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
<?php
}
?>
What is the best way to go about this? Could I perhaps make the echo disappear after 4 seconds?
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO mvmv3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('mvmv_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
// WRAP THE "ECHOED" OUTPUT IN A DIV ELEMENT (WITH CLASS &/OR ID)
// SO YOU CAN EASILY REFERENCE IT IN JS
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
}else {
}
JAVASCRIPT
$(document).ready(function() {
$('submit').click(function() {
$('submission')[0].reset();
// FADE-OUT THE DIV 3 SECONDS AFTER CLICKING THE BUTTON USING window.setTimeout...
// THIS ASSUMES THAT YOUR FORM IS NOT SUBMITTING NORMALLY (AJAX OR SO)
/*
setTimeout(
function(){
$("#msg-box").fadeOut(500);
},
3000);
*/
});
// FADE-OUT THE DIV 3 SECONDS AFTER PROCESSING THE FORM-DATA USING window.setTimeout...
// THIS ASSUMES THAT YOUR FORM HAS SUBMITTED NORMALLY (VIA POST OR GET)
// AND THE MESSAGE IS DISPLAYED BY PHP AFTER PROCESSING...
setTimeout(
function(){
$("#msg-box").fadeOut(500);
},
3000);
});
Use something like
$('input').val('');
to clear all you input fields
I have a php function handling the results of a form delivered from a jQuery script, as the form content is also delivered to a Workbooks CRM url to be added to records there.
All works fine, except the email is sent 3 times. The button clicked is not inside the form, and the 'send' value for isset($_POST) is delivered from a hidden form field in the form.
I've tried:
Adding flags, both in PHP and in the jQuery.
Adding alerts in the jQuery.
Adding exit("sent"); after the mail() function.
The alert() experiment appeared to indicate the jQuery wasn't the issue, but flags seemed to indicate the same in the PHP!
Here's the jQuery:
$(document).ready(function () {
$("#test-vf-button1").click(function (event) {
event.preventDefault();
// Field values as array
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var formData = $("#wb_form").serialize();
var url = $(location).attr('hostname');
var pathname = $(location).attr('pathname');
var pageUrl = url + pathname;
console.log(pageUrl);
$("#validate-message").empty();
$("#confirm-message").empty();
if (name == '' || email == '' || message == '') {
$("#validate-message").append(" Fill in required fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: 'POST',
url: "http://visual-factory.co.uk/",
data: formData,
success: function () {
$.ajax({
type: 'POST',
url: "https://secure.workbooks.com/crm/web_leads",
crossDomain: true,
data: formData,
dataType: 'text',
success: function () {
PHP handling function:
function vf_deliver_mail() {
// if the submit button is clicked, send the email
if ( isset( $_POST['send'] ) ) {
// sanitize form values
$title = sanitize_text_field( $_POST['person_lead_party']['person_personal_title'] );
$name = sanitize_text_field( $_POST['person_lead_party']['name'] );
$jobrole = sanitize_text_field( $_POST['person_lead_party']['person_job_role'] );
$email = sanitize_text_field( $_POST['org_lead_party']['main_location']['email']);
$phone = sanitize_text_field( $_POST['org_lead_party']['main_location']['telephone'] );
$company = sanitize_text_field( $_POST['org_lead_party']['name'] );
$country = sanitize_text_field( $_POST['org_lead_party']['main_location']['country'] );
$messagecontent = esc_textarea( $_POST['vf-message'] );
$message = "<p>Title: ".$title."</p>";
$message .= "<p>Name of lead is: ".$name."</p>";
$message .= "<p>Job Role: ".$jobrole."</p>";
$message .= "<p>Email is: ".$email."</p>";
$message .= "<p>Phone is: ".$phone."</p>";
$message .= "<p>Company is: ".$company."</p>";
$message .= "<p>Country is: ".$country."</p>";
$message .= "<p>Message: ".$messagecontent.".</p>";
// get the blog administrator's email address
$to = get_option( 'admin_email' );
$subject = "Form response";
$headers = "From: $name <$email>" . "\r\n";
mail( $to, $subject, $message, $headers ) ;
}
}
I try to prepare simple contact form with jquery, ajax and php without refresh. Everything works fine besides event.preventDefault();
That's my files:
contact_engine.php
<?php
$name = $_POST['name'];
...
$from = 'from';
$to = 'to';
$subject = 'subject';
$human = '4';
$body = ".........";
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Thanks</p>';
} else {
echo '<p>Error</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
Ajax/jQuery
$('form').on('submit', function(event){
event.preventDefault();
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
}
});
});
PHP
<form method="post" action="<?php bloginfo('template_directory'); ?>/contact_engine.php">
<div class="box">
<input type="text" name="name" class="pola formbg name" placeholder="Name" />
.
.
.
.
<p><input id="form-button" type="submit" name="submit" value="Send" /></p>
</div>
<br style="clear: left;" />
</form>
When I remove event.preventDefault(); everything is ok, I receive a message from form but site are refreshing and I see 'thanks' message.
I used Wordpress as you probably seen.
Yeah, in this kind of instance why have a form/submit button.
Remove the form and change the input from a submit button to a standard button.
Put the function on the button, job done.
$('#form-button').on('click', function(event){
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
//do something with the return code
}
});
});
Give your form an ID - I think the problem is your submit handler does is not firing:
$( "#myForm" ).submit(function( event ) {...
and then change your jQuery to read:
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
...
See http://api.jquery.com/jquery.post/
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem
I currently have my jQuery outputting the result in the same div as per error or success:
HTML
<div id="error-message").html(res);
JQUERY
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
});
});
PHP
$error = '';
$uname = trim( $_POST['username'] );
$email = trim( $_POST['mail_id'] );
$fname = trim( $_POST['firname'] );
$lname = trim( $_POST['lasname'] );
$pswrd = $_POST['passwrd'];
if( empty( $_POST['username'] ) )
$error .= '<p class="error">Enter Username</p>';
if( empty( $_POST['mail_id'] ) )
$error .= '<p class="error">Enter Email Id</p>';
elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= '<p class="error">Enter Valid Email</p>';
if( empty( $_POST['passwrd'] ) )
$error .= '<p class="error">Password should not be blank</p>';
if( empty( $_POST['firname'] ) )
$error .= '<p class="error">Enter First Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
$error .= '<p class="error">Enter Valid First Name</p>';
if( empty( $_POST['lasname'] ) )
$error .= '<p class="error">Enter Last Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
$error .= '<p class="error">Enter Valid Last Name</p>';
if( empty( $error ) ){
$status = wp_create_user( $uname, $pswrd ,$email );
if( is_wp_error($status) ){
$msg = '';
foreach( $status->errors as $key=>$val ){
foreach( $val as $k=>$v ){
$msg = '<p class="error">'.$v.'</p>';
}
}
echo $msg;
} else {
$msg = '<p class="success">Registration Successful</p>';
echo $msg;
}
} else {
echo $error;
}
die(1);
}
}
I'm getting confused on how to get the results in 2 different places.
1: Error = display errors and show the form, ideally errors should be displayed below each form field, at the moment is a div on top of the form
2: Success = hide the form, display only the success msg
METHOD 1
If you would like to have an error message per validated field then:
You have a form input, for example:
<input name="myfield" id="myfield" type="text">
Next to it, you can add a div or span with your alert/error message and appropriate id, something like:
<input name="myfield" id="myfield" type="text">
<span id="myfield_Error" class="none">Please fill this field</span>
Where class="none" in your css, is used to hide the error container. Something like:
.none {display:none;}
Now for your jquery part:
var myfield= $("#myfield").val();
if (myfield=='') { $("#myfield_error").show(); }
The trick here is to named your error containers in a similar way as your target form element you validate. So for id="fieldA" you will have the error id="fieldA_error".
EDIT1:
If you need to use classes, you need to modify a little the code.
You need to form an array of element to check.
Loop through the array.
And use somethign like:
var fieldName = $(this).attr('name');
var fieldVallue = $(this).val();
if (fieldVallue=='')
{
$("#"+fieldName+"_error").show();
}
else
{
$("#"+fieldName+"_error").hide;
}
Method 2
If you just like to have 2 different containers, one for success and one for error/failed validation, then you need to output something different from your php file.
So your php file can output someting like:
$report['status'] = 'error'
$report['message'] = 'error in xxxx field - please use a proper email'
echo json_encode($report);
Then in your ajax success you can check what response you got. You parse your json response and based on your 'status', you put your 'message' in different containers
I hope this is what you look for.
Alternatively you can assign an error handler as follow
var jqxhr = jQuery.post(
ajaxurl,
ajaxdata,
function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
}
).fail(function() {
alert("error");
});
and send a non-2xx code from your php code (with http_response_code) if it doesn't validate.
It would be easier for you to return (for example) JSON to the front end instead of one string. The JSON would containt key/value pairs in the form of ID => Message.
For example:
$errors = array();
if( empty( $_POST['passwrd'] ) ) {
$errors['st-psw'] = "Password should not be blank";
}
if( empty( $_POST['firname'] ) ) {
$errors['st-fname'] = 'Enter First Name';
} elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) ) {
$errors['st-fname'] = 'Enter Valid First Name';
}
...
...
if( empty( $errors ) ){
$response['success'] = true;
} else {
$response['success'] = false;
$response['errors'] = $errors;
}
echo json_encode($response);
Then you will loop the JSON object in your javascript and insert the error messages after each target.
Encode result array in JSON format and return the response.
<?php
if ($validation==false)
{
$result = array ('response'=>'error','message'=>'Some validation error');
}
else
{
$result = array ('response'=>'success','message'=>'Success');
}
echo json_encode($result);
?>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'error') {
alert('error');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
});
</script>