I have the following contact form with its contact.php and JS files.
It uses AJAX to change div with class "messages-contact" with appropriate messages when form is submitted.
I want the entire form to collapse and only the message to remain.
How can I modify this code to do that?
My form is:
<section id="contact">
<h1>Contact Us</h1>
<div class="myform">
<form id="contactform" method="post" action="./stellarcontact.php" role="form">
<div class="messages-contact"></div>
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="firstname">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="lastname">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email">
<label for="form_subject">Subject *</label>
<input id="form_subject" type="text" name="subject">
</form>
</div>
</section>
My contact.php is
<?php
//Removed code un-needed for this question
// if requested by AJAX request return JSON response
if ( !empty( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) == 'xmlhttprequest' ) {
$encoded = json_encode( $responseArray );
header( 'Content-Type: application/json' );
echo $encoded;
}
// else just display the message
else {
echo $responseArray[ 'message' ];
}
My Javascript is:
$(function() {
window.verifyRecaptchaCallback = function(response) {
$('input[data-recaptcha]').val(response).trigger('change')
}
window.expiredRecaptchaCallback = function() {
$('input[data-recaptcha]').val("").trigger('change')
}
$('#contactform').validator();
$('#contactform').on('submit', function(e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contactform').find('.messages-contact').html(alertBox);
$('#contactform')[0].reset();
grecaptcha.reset()
}
}
});
return !1
}
})
});
Edit See this code snippet, click the button to simulate your ajax call. You can include this code in the ajax success function.
$("#ajaxBtn").click(function(){
var messageAlert = "Some Alert";
var messageText = "Some Message";
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
$('.messages-contact').html(alertBox);
$('.myform').fadeOut();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="contact">
<h1>Contact Us</h1>
<div class="messages-contact"></div>
<div class="myform">
<form id="contactform" method="post" action="./stellarcontact.php" role="form">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="firstname"><br/>
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="lastname"><br/>
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email"><br/>
<label for="form_subject">Subject *</label>
<input id="form_subject" type="text" name="subject"><br/>
</form>
</div><br/>
<button id="ajaxBtn">Simulate AJAX Call</button>
</section>
You must include <div class="messages-contact"></div> outside the form and do $('.messages-contact').html(alertBox); in your success function. Then you can hide the form using CSS display/visibility or jQuery hide/fadeOut, etc
Related
I would like to ask you for help.
I created a contact form in HTML and JavaScript, but when I try to send the email, it just doesn't do anything, nothing happens.
See the code below:
/*----------------------------------------------------*/
/* contact form
------------------------------------------------------*/
$('form#contactForm button.submit').click(function() {
$('#image-loader').fadeIn();
var contactName = $('#contactForm #contactName').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- form -->
<form action="mailto:yuridiamond#icloud.com" method="post" enctype="multipart/form-data" id="contactForm" name="contactForm">
<fieldset>
<div>
<label for="contactName">Nome <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactName" name="contactName">
</div>
<div>
<label for="contactEmail">E-mail <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactEmail" name="contactEmail">
</div>
<div>
<label for="contactSubject">Assunto</label>
<input type="text" value="" size="35" id="contactSubject" name="contactSubject">
</div>
<div>
<label for="contactMessage">Mensagem <span class="required">*</span></label>
<textarea cols="50" rows="15" id="contactMessage" name="contactMessage"></textarea>
</div>
<div>
<button class="submit" action="mailto:yuridiamond#icloud.com">Enviar</button>
<span id="image-loader">
<img alt="" src="images/loader.gif">
</span>
</div> -->
</fieldset>
</form>
<!-- Form End -->
I hope you can help me.
Thank you in advance.
I apologize if it's a simple problem, but I'm still new to programming.
$(document).ready(function(){
$('.submit').click(function() {
$('#image-loader').fadeIn();
var contactName = $('#contactForm #contactName').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
});
I found a solution, faster, simpler and very cool.
See the code below:
<form action="https://formspree.io/f/mbjwrqov" method="POST" enctype="multipart/form-data" id="contactForm" name="contactForm">
<fieldset>
<div>
<label for="contactName">Nome <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactName" name="Nome">
</div>
<div>
<label for="contactEmail">E-mail <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactEmail" name="Email">
</div>
<div>
<label for="contactSubject">Assunto</label>
<input type="text" value="" size="35" id="contactSubject" name="Assunto">
</div>
<div>
<label for="contactMessage">Mensagem <span class="required">*</span></label>
<textarea cols="50" rows="15" id="contactMessage" name="Mensagem"></textarea>
</div>
<div>
<button class="submit">Enviar</button>
<span id="image-loader">
<img alt="" src="images/loader.gif">
</span>
</div>
</fieldset>
</form>
<!-- Form End -->
Formspree
http://formspree.io/
The site itself already creates HTML, and I just had to comment on the JavaScript part so as not to give problem or conflict.
Basically, the site already does the intermediary.
A note: The site I created is hosted on GitHub Pages.
I have a form on my site that I want to send an email on submit. The email gets sent but none of the content gets sent along with it. It seems that isset($_POST['email']) is failing.
Here is my form:
<form id="sponsorForm" name="sponsor" role="form">
<div class="modal-body">
<div class="form-group col-md-12">
<label for="sponsorname">Name</label>
<input type="text" name="sponsorname" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsoremail">Email</label>
<input type="email" name="sponsoremail" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsormessage">Message</label>
<textarea class="form-control" name="sponsormessage" rows="7" placeholder="Message...">
</textarea>
</div>
</div>
<div class="modal-footer" style="border: none;">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" data-toggle="modal" data-target="#sponsor-thanks" id="sponsor-submit">
</div>
</form>
Here is some javascript to call the php:
$(document).ready(function(){
$("#sponsorForm").submit(function(event){
submitSponsorForm();
return false;
});
});
function submitSponsorForm(){
$.ajax({
type: "POST",
url: "sendSponsor.php",
cache:false,
data: $('form#sponsorForm').serialize(),
success: function(response){
$("#sponsor").html(response)
$("#sponsor-modal").modal('hide');
},
error: function(){
alert("Error");
}
});
}
And here is the php:
<?php
if (isset($_POST['email'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
}
mail("xxx#xxx.com", "subject", $message, "from: xxx");
?>
In your form, the name of your email input field is 'sponsoremail'
So you should use the name sponsoremail as the index of $_POST variable as $_POST['sponsoremail'] to check if user fill the email or not but you have used $_POST['email'] which is not found in your form.
Use if (isset($_POST['sponsoremail'])) instead of if (isset($_POST['email'])) and it should work.
Try this
<?php
if (isset($_POST['sponsoremail'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
mail("xxx#xxx.com", "subject", $message, "from: xxx");
}
?>
I have problem with AJAX and jQuery. I write function for login to system, but it works only first time. Here is my code:
html in modal:
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
here is jquery:
function login(){
login=document.getElementById('userName').value;
pass=document.getElementById('password').value;
var dataString="emailLogin="+login+"&passLogin="+pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text){
if(text=='0'){
$("#loginError").removeClass('hidden');
}else{
$("#loginOk").removeClass('hidden');
$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">"+login+" (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html(""+login+" (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
}
});
return false;
}
You are overwriting your login function with a string.
function foo() {
alert('foo');
foo = function () {
alert('bar');
}
}
<a onclick="foo()">
click me!
</a>
See how the second click here causes a different alert? In your case you're replacing the function with a string instead of a function, causing a syntax error. Don't forget to var your variables.
var login=document.getElementById('userName').value;
var pass=document.getElementById('password').value;
The snippet tests your logic and there was a console error for your login and pass variables. I set them as 'var' and put your success logic in the 'error' section of the ajax request since I cannot reach your server, but it does create the logout button. Is that what you wanted?
function login() {
var login = document.getElementById('userName').value;
var pass = document.getElementById('password').value;
var dataString = "emailLogin=" + login + "&passLogin=" + pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text) {
/* Success logic */
},
error: function() {
alert('Test - success logic');
$("#loginOk").removeClass('hidden');
//$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">" + login + " (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html("" + login + " (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
<div id="loginLi"></div>
<div id="regLi"></div>
<div id="loginOk">Login OK</div>
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
Htmlcode and after html is js code
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
--
ajax code
var form = $('#main-contact-form');
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
This is what your ajax call should look like
$('#main-contact-form').on('submit', function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
make sure your ajax response which is
function(data)
is really an object variable
because if not this code will not execute because of error of data.message
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
also kindly check your network status check the response of that ajax request
using the dev tools F12
UPDATED ANSWER BELOW
so your response is json but still need to be parse in your javascript.
SOLUTION: Parse your ajax response to make it json object
data = JSON.parse(data);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
The problem is, that you don't send your form data with the ajax-call.
Like adeneo wrote, you only have to add one line to your code.
data : $(this).serialize(),
Setting the data-type is relevant, because the destination needs to know in which format the data is sent.
Try using the Jquery-POST-function. It looks much better in the code.
Hi I submit my form using modal in bootstrap
How can I make this work with dismissal message and not closing the modal?
HTML
<div class="modal fade bs-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header modal-header-custom">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body text-center">
<form class="form-inline requestaccessForm" role="form" name="requestaccessForm">
<div class="form-group">
<label class="sr-only" for="First Name">First Name</label>
<input type="text" class="form-control" id="request_first_name" placeholder="First Name">
</div>
<div class="form-group">
<label class="sr-only" for="Last Name">Last Name</label>
<input type="text" class="form-control" id="request_last_name" placeholder="Last Name">
</div>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<input type="email" class="form-control" id="request_email" placeholder="Email">
</div>
<button type="submit" id="requestformSubmit" class="btn btn-green">Submit</button>
</form>
</div>
</div>
</div>
</div>
PHP
<?php
$myemail = 'dummyemail#email.com';
if (isset($_POST['request_first_name'])) {
$request_first_name = strip_tags($_POST['request_first_name']);
$request_last_name = strip_tags($_POST['request_last_name']);
$request_email = strip_tags($_POST['request_email']);
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!
Here is what you submitted:</span><br><br>";
echo "<stong>Name:</strong> ".$request_first_name."<br>";
echo "<stong>Name:</strong> ".$request_last_name."<br>";
echo "<stong>Email:</strong> ".$request_email."<br>";
$to = $myemail;
$email_subject = "Contact form submission: $request_first_name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $request_first_name \n ".
"Email: $request_email\n";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $request_email";
mail($to,$email_subject,$email_body,$headers);
}?>
Javascript
$(document).ready(function () {
$("button#requestformSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //
data: $('form.requestaccessForm').serialize(),
success: function(msg){
alert("success");
},
error: function(){
alert("failure");
}
});
});
});
Thank you
To achieve that you have to take some steps first..
Add a div inside the modal which will serve as the success message container.
Before closing the <div class="modal-body text-center"> add the following code:
...
<div id="successMessage"/></div>
...
Change the success handler of the $.ajax request to add the dismissal/success message into the div created in the previous step.
Add the following code to your $.ajax success handler:
...
success: function(msg){
$("#successMessage").html(msg);
},
...
Prevent default actions from the button click so that the modal will not be closed after the request.
Add the following line at the end of your jQuery click function:
return false;
So your jQuery code will look something like this:
$(document).ready(function () {
$("button#requestformSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //
data: $('form.requestaccessForm').serialize(),
success: function(msg){
$("#successMessage").html(msg);
},
error: function(){
alert("failure");
}
});
return false;
});
});
Hope this helps you out