I have a div with form fields in it including multiple attachments in my HTML. However, I am not sure how to recode the following to allow for zero to many attachments, and not sure about the PHPMailer part. Here is the Ajax part I've got so far. Is this part at least correct? What about sendContactFormEmail.php? Do I have to use the FormData interface?
<!-- validate and submit form input -->
<script type="text/javascript">
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
post_data = {
'form_firstname' : $('input[name=form_firstname]').val(),
'form_lastname' : $('input[name=form_lastname]').val(),
'form_address' : $('input[name=form_address]').val(),
'form_city' : $('input[name=form_city]').val(),
'form_email' : $('input[name=form_email]').val(),
'form_phone' : $('input[name=form_phone]').val(),
'form_attachment' : $('input[name=form_attachment]').val(),
'form_message' : $('textarea[name=form_message]').val(),
};
// Ajax post data to server
$.post('mail/sendContactFormEmail.php', post_data, function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
// display an animation with the form submission results
$(matchContactSubmitResult).hide().html(output).slideDown();
}, 'json');
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
</script>
Related
I am using the following code to allow users to submit content to an online board:
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
Unfortunately, if a user rapidly presses enter or rapidly clicks the send button, the code will execute multiple times and their message will be sent multiple times.
How can I modify my code to prevent this multiple execution?
A simple client-side fix would be to create a local variable that tracks whether or not anything has been submitted and have the function only execute if false.
var submitted = false;
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
if (submitted)
return false;
submitted = true;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
A better solution would be to send a unique token for the transaction to the client and have the client send it along with the request.
You could have server-side coded to verify that the token has only been used once.
found this solution here
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
I have callback plugin on my Wordpress web-site and try to add invisible recaptcha without using WP plugin. I tried some ways but no result. Can you correct a right code for jquery validation form I've already have?
I have input button in my form. PHP and HTML I can correct by myself.
jQuery(document).ready(function($) {
$('.callback-form-container').submit(function() {
var formInputs = $(this).find('.validate');
var errors = '';
$(formInputs).each(function() {
if($.trim(this.value) == '') {
fieldLabel = $(this).parent().find('span.label-text').html();
errors += '- ' + fieldLabel + '\n';
}
});
if(errors.length > 0) {
alert('Error:\n\n' + errors);
return false;
}
else {
$('.submit-button').val('Please wait...');
$('.submit-button').attr('disabled', 'disabled');
return true;
}
});
});
function onSubmit1(token){
document.getElementById("send").submit();
};
I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.
I am trying to use the localStorage API to grab an email value when the user submits a form and then populate another form field later.
I tried using vanilla javascript first:
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
document.getElementById('searchBooking').addEventListener('submit', function() {
// Get the value of the email field.
var email = document.getElementById('email').value;
// Save the email in localStorage.
localStorage.setItem('email', email);
});
}
// Retrieve the users email.
var email = localStorage.getItem('email');
if (email != "undefined" || email != "null") {
document.getElementById('guestEmail').innerHTML = email;
} else {
document.getElementById('guestEmail').innerHTML = "";
}
}
But got this error message in the browser console on line 21:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Then I tried with this jQuery:
$(function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
$('#searchBooking').on('submit', function() {
// Get the value of the email field.
var email = $('#email').value;
// Save the name in localStorage.
localStorage.setItem('#email', email);
});
}
var email = localStorage.getItem('#email');
if (email != "undefined" || email != "null") {
$('#guestEmail').html = email;
}
else {
$('#guestEmail').html = "";
}
});
I didn't get an error message but nothing worked.
Sorry, I am very new to Javascript and don't use it very often, but I really need to save this value and repopulate it in another form.
after looking at your gist link, I found that guestEmail is a textbox on your page so the innerHTML is not going to work here. also the jquery implementation for both .value and .html is not correct.
you need to update your jquery as follows
$(function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
$('form').on('submit', function() {
// Get the value of the email field.
var email = $('#email').val();
// Save the name in localStorage.
localStorage.setItem('#email', email);
$('#guestEmail').html(email);
console.log(localStorage.getItem('#email'));
});
}
var emailLocalStorage = localStorage.getItem('#email');
console.log(emailLocalStorage);
if (typeof emailLocalStorage != "undefined" && emailLocalStorage != "null") {
$('#guestEmail').val(emailLocalStorage);
console.log(emailLocalStorage)
} else {
$('#guestEmail').val("");
}
});
Hope this helps.
I'm making a simple form where a user submits a video, alongside their email address. I'd like to make it so that the person can not submit the form until they have filled in the email and saved the video.
The video part is working, but when I test with an empty email, it still seems to submit. The code is below, and the live version is at http://www.atlas-china.com/record-your-multi-lingual-abilties/
Help much appreciated!
// Global variable to hold player's reference.
var _Nimbb;
// Global variable to hold the guid of the recorded video.
var _Guid = "";
// Event: Nimbb Player has been initialized and is ready.
function Nimbb_initCompleted(idPlayer) {
// Get a reference to the player since it was successfully created.
_Nimbb = document[idPlayer];
}
// Event: the video was saved.
function Nimbb_videoSaved(idPlayer) {
_Guid = _Nimbb.getGuid();
}
jQuery(document).ready(function ($) {
// Get the data from the form. Check that everything is completed.
$('#video_submit').click(function (e) {
var email = document.getElementById("email").value;
var video_title = document.getElementById("video_title").value;
var form = document.myForm;
// Make sure the email is specified.
if (email.value == "") {
alert("Please enter your email to proceed.");
return;
}
// Verify that the video is not currently recording.
if (_Nimbb.getState() == "recording") {
alert("The video is being recorded. Please wait.");
return;
}
// Check that video has been recorded.
if (_Guid == "") {
alert("You did not save the video. Click save.");
return;
}
// Set the guid as hidden parameter.
form.guid.value = _Guid;
var dataString = 'email=' + email + '&guid=' + _Guid + '&video_title=' + video_title;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/send.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
}
});
document.forms["myForm"].submit();
});
});
After viewing your live site...
email = "" // Empty string
Whereas
email.value = undefined
Try changing your code to
if (email === "") {
alert("Please enter your email to proceed.");
return;
}
I assume you are doing .value twice by mistake as you have the following line earlier in your code
var email = document.getElementById("email").value;
When you return from that handler function, the browser will proceed to carry out the normal behavior of the "submit" event, which is to submit the form.
You can change your "abort" return statements to
return false;