I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}
Related
I have a headless WordPress site. I'm working on the event handler to submit the contact form. I'm using Contact Form 7. I've tried using vanilla JS, I'm using jQuery here because it seems like a better option, and I'm losing my mind.
Essentially, the form submits but the fields do not clear. I've tried form.reset() in JS, $('#formid')[0].reset() in jQuery, and the code below. I don't know why this isn't working and the result is really suboptimal. Any ideas?
I will fully admit that I am more comfortable working in javascript than jQuery so I might be missing something obvious.
If I don't have the iframe set as the form target, the page redirects to a white page with JSON data. Am I missing something about event.preventDefault()? It's not working the way it should, and has in my experience.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(this)
}).done(resetForm());
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
There's several separate issues:
.done(resetForm()) is incorrect as it immediately calls resetForm() and sets the returned value from that call as the event handler.
You need to send the $form argument in the resetForm() method call, so provide a full function block to the done() handler, including that argument
When sending a FormData object in a jQuery AJAX call you need to set processData and contentType to false so the data is encoded correctly.
jQuery does not have :tel and :file pseudo selectors. Instead you can use :input to select all input, textarea and select elements to reset their values.
Changing the type of the date control to text and then back to date is not necessary, even without the above point.
$(document).ready(function() {
const $form = $('#formElem').on('submit', function(e) {
e.preventDefault();
let data = new FormData(this);
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: data,
contentType: false,
processData: false
}).done(function() {
resetForm($form)
});
})
function resetForm($form) {
$form.find(':input').val('');
// alternatively to reset the form to original state, not wipe all fields use this
// $form.get(0).reset();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
In your code you are calling resetForm and assigning what it returns to the done event handler. It is not calling that function when done is called.
You also are not passing the form reference to the function. So you will have an error message in your console.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
var form = this;
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(form)
}).done(function () { resetForm(form); });
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.
I've a contact form that sends data to a PHP script via AJAX. It's pretty basic but I can't get input values with serialize. The form id is correct, i obtain the input name but not their values. Here's my code. Thanks !
//Contact form AJAX
var form = $('#contact-form');
var formMessages = $('#form-messages');
// Serialize the form data.
var formData = $(form).serialize();
console.log($(form).serialize());
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).hide().fadeIn();
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#form_name').val('');
$('#form_email').val('');
$('#form_message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).hide().fadeIn();
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text("Something went wrong.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact-form" class="col-md-12" method="post">
<h1>Contact</h1>
<fieldset class="form-group">
<input type="text" id="form_name" name="form_name" class="form-control" placeholder="Your name">
</fieldset>
<fieldset class="form-group">
<input type="email" id="form_email" name="form_email" class="form-control" placeholder="Your email" required>
</fieldset>
<fieldset class="form-group">
<textarea class="form-control" id="form_message" name="form_message" rows="3" placeholder="Your message" required></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Send</button>
</form>
https://jsfiddle.net/huja5pru/2/
Use serialize() method when form is submit.
check this fiddle https://jsfiddle.net/6o6htoh1/1/
You have a syntax mistake when you use the jquery selector to a jquery object, when you select your form you must use it lately like this:
var form = $('#contact-form'); //and then use it directly in the ajax call like this
form.serialize(); // not $(form).serialize()
Here is your fiddle updated https://jsfiddle.net/ingemi/kbpnmptw/ you must use serialize directly in the ajax call
I am working as junior web master maybe that's why I have come with a simple question here. I have designed a single page application for client which has contact form at the end of page, validation is done using bootstrap but to send form data to mail id only method I know is using php with action directing different page. since my website is single page application i would like a popup on successful submission to mail id
Below is the HTML code for the contact form
<form class="form-inline" data-toggle="validator" role="form" method="post" id="enquiry" action="index.php">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Name</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail3" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Mobile Number</label>
<input type="text" class="form-control" id="exampleInputPassword3" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Email Id</label>
<input type="email" class="form-control col-lg-12" id="exampleInputPassword3" name="email" placeholder="Email Id" required>
</div>
<br/> <br/>
<div class=" col-lg-12 form-group">
<textarea cols="80" placeholder="Enter query Here" class="form-control" name="query" id="address" data-error ="Please Enter Your Query" required></textarea><br/><br/>
</div>
<button style="background-color:#f15a24; color:#FFF;" name="submit" id="submit" type="submit">Submit</button>
</form>
Can use php to send form data and still get a pop up in same page?
Or do I need to use jquery to send data and pop-up?
It would be great if somebody helps me out with code, thanks in advance
Updated
below(index.php page) i have added the code what you have given,
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/jquery.fittext.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/creative.js"></script>
<script src="js/validator.js"></script>
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success"){ alert("Success"); }else{ alert("Failed"); }
//Failure message if ret is false
});
}
});
});
</script>
Add this js to your script
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success")
{
alert("Success");
} else {
alert("Failed");
}
}
});
}
);
});
submit.php contains the code to send and exit it with the success (true) or failure (false) message. That will be caught in ret variable.
Edited
This will be more detailed answer I was looking for, I thought it be would be helpful for somebody so I have answered my own question as an alternative solution, check out the links below.
Show submitted form response on the same page. (No Reload)
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
I have been created subscribe form using php and jquery and sql to store data.
Now it is working fine, but it has some limitation.
When i enter invalid email address, it shows like this,
But i need to remove that message, i need only working effects with error button.
And If i enter blank, that time error button working fine[that is button will be shaken and says error], after that i enter valid address, it also working fine[that is success button].
One more think, if i enter invalid address at first, and second also enter invalid address,, the error button works fine at first time only.
Here is lib.js:
$(document).ready(function () {
$('#newsletter').submit(function () {
var $this = $(this),
$response = $('#response'),
$mail = $('#signup-email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$('#actbtn').removeClass('btn-error').addClass('btn-error');
//$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize(),
success: function(data){
if(data!=''){
$response.removeClass('loading');
if(data.status == 'success'){
$('#actbtn').removeClass('btn-error').addClass('btn-success');
}
else{
$('#actbtn').removeClass('btn-error').addClass('btn-error');
}
}
}
});
}
return false;
});
});
html:
<div id="newsletterform">
<div class="wrap">
<h3>Get Email Update</h3>
<form action="send.php" method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<button id="actbtn" class="btn btn-7 btn-7h icon-envelope">Submit form</button>
<span class="arrow"></span>
</form>
<div id="response"></div>
</div>
</div>
May i know,how to achieve this one, Any idea would be highly appreciated.
Thanks in advance.
You have used the
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
try to use it as input text because you did the script validation
<input type="text" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />