Ajax and jQuery custom form submission in Wordpress - php

I'm not a tech completely, and I'm trying to build my custom theme for WordPress.
So, I came to a point that I need to implement a custom JS script to send the form data. As far as I understand, it's going to be a PHP file, but now I'm concentrated on front-end. This is AJAX + jQuery validation.
I don't want my form to refresh the page after it sends the data, just a simple message telling that everything went successful.
Can anyone have a look at the code I wrote and tell me what's wrong with it? It took me just two days..
PS - the file, that stores that code is embedded into WP theme properly, with a jQuery as a dependancy. I wonder, do I have to do anything to implement AJAX, or it comes with jQuery?
http://codepen.io/anon/pen/MpdRpE
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">Sorry, but this field can't be empty.</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">Oopps, I haven't seen emails like that.</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Want to leave any message?*" class="textarea" required></textarea>
<p class="error-message">Nothing to say at all? Really?</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="error-message error-message_main_success val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
.error-message {
display: none;
}
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(){
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error", ".error-message").css("display", "block");
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});

First you need to prevent the default click event
Second you need a action variable to pass to the wordpress hook
3th you jquery selector for showing the errors is incorrect, the coma needs to be in the string
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();//a little bit cleaner
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
for more information read the wp documentation on ajax

Little changes required otherwise code is looking fine.Have a look
$(document).ready(function(){
$(".submit-btn").click(function(){
var name = $(".firstname").val();
var email = $(".email").val();
var message = $(".textarea").val();
if(name === "" || email === "" || message === "") {
$(".val-error", ".error-message").css("display", "block");
return false;
}
else {
$.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:name, email:email, message:message},
success: function(data) {
if(data){
$("form").trigger("reset");
$(".val-success").show(fast);
}
}
});
}
});
});

Related

jQuery Ajax form not submitting on iPhone

I have a jQuery Ajax form that looks like this:
<form method="post" action="contact.php" class="contact-form">
<div class="contact-empty">
<input type="text" name="name" id="name" placeholder="Name *" class="txt-name" />
<input type="text" name="email" id="contact-email" placeholder="Email Address *" class="txt-email" />
<textarea rows="4" name="message" cols="60" id="message" placeholder="Message *" class="txt-message"></textarea>
<span class="btn-contact-container">
<button id="contact-submit" class="btn-contact">Submit</button>
<img src="images/loading.gif" alt="Loading..." width="62" height="62" id="contact-loading">
</span>
<span class="contact-error-field"></span>
</div>
<div class="contact-message"></div>
</form>
Here's my js that sends it:
$(document).ready(function () {
$('#contact-submit').click(function () {
$('.contact-error-field').hide();
var nameVal = $('input[name=name]').val();
var emailReg = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
var emailVal = $('#contact-email').val();
var messageVal = $('textarea[name=message]').val();
//validate
if (nameVal == '' || nameVal == 'Name *') {
$('.contact-error-field').html('Your name is required.').fadeIn();
return false;
}
if (emailVal == "" || emailVal == "Email Address *") {
$('.contact-error-field').html('Your email address is required.').fadeIn();
return false;
}
else if (!emailReg.test(emailVal)) {
$('.contact-error-field').html('Invalid email address.').fadeIn();
return false;
}
if (messageVal == '' || messageVal == 'Message *') {
$('.contact-error-field').html('Please provide a message.').fadeIn();
return false;
}
var data_string = $('.contact-form').serialize();
$('.btn-contact').hide();
$('#contact-loading').fadeIn();
$('.contact-error-field').fadeOut();
$.ajax({
type: "POST",
url: "contact.php",
data: data_string,
//success
success: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-check contact-success"></i>Your message has been sent.').fadeIn();
},
error: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-times contact-error"></i>Something went wrong, please try again later.').fadeIn();
}
}) //end ajax call
return false;
});
});
I have a subscribe form that uses the same code with just an email input and that submits fine on an iphone.
The contact form, however, gets stuck at 'Invalid email address.' when trying to submit from an iPhone even though the email you enter is correct. It works on desktop.
I've tried changing the button to a type="submit" input. Didn't change anything.
UPDATE: My regex was wrong, I replaced it with the following and it worked:
var emailReg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
Instead of using click() to submit your form, use submit():
Just change the top of your javascript code so it looks like this:
$(document).ready(function () {
$('form.contact-form').submit(function (e) {
e.preventDefault(); // <-- prevents normal submit behavior
And change your button to type=submit
<button type="submit" id="contact-submit" class="btn-contact">Submit</button>

Form when submitted to display a result (Firstname) on the thank you page

Stuck on a thing with PHP, i know it is something simple but am not sure of the correct way of doing it, either by jquery or php.
I have a contact form which when it submits its form, i want the results of some of the fields to display on the results thank you paeg saying:
Thank you for entering YOURNAME. Blah blah blah
Is this acheivable with a simple line of php or does it need to called through jquery.
Thanks, only new to php so somethings are still bit confusing
<?php
define('is_freetrial-celebrity', 1);
include_once('includes/header.inc.php');
?>
<div role="main" id="main">
<article id="mainFreetrial" class="greyBlock twoColumnsLayout">
<header>
<h1>Get Started</h1>
</header>
<div>
<form method="get" action="/forms_validation/freetrial.php" class="trialForm ajaxForm">
<div class="column">
<p>
<label for="firstNameTrial">First name<sup class="red">*</sup></label><input type="text" id="firstNameTrial" name="firstNameTrial" value="" required/>
</p>
<p>
<label for="lastNameTrial">Last name<sup class="red">*</sup></label><input type="text" id="lastNameTrial" name="lastNameTrial" value="" required/>
</p>
<p>
<label for="ageTrial">Age</label><input type="text" id="ageTrial" name="ageTrial" value=""/>
</p>
<p>
<label for="celebrityTrial" style="display: block; width: auto; margin-bottom: 5px;">Name the celebrity you would most like to meet, and why?<sup class="red">*</sup></label>
<textarea id="celebrityTrial" name="celebrityWhyTrial" style="width: 430px; height: 3em;" required></textarea>
</p>
<p class="ajaxFormBeforeValid">
<input type="submit" value="Submit now" class="redButton"/><span class="ajaxFormWait"></span><span class="ajaxFormError error"></span>
</p>
<div class="ajaxFormValid">
<p>
Thank you! Your local consultant will contact you soon. 'Like' us while you wait for all the latest VIP offers and promotions!
</p>
</div>
<p>
<small>
<sup class="red">*</sup>These are mandatory fields.
</small>
</p>
</div>
</form>
</div>
</article>
</div>
<?php include_once('includes/footer.inc.php'); ?>
Heres the jquery part
/*************************
plugin to manage ajax forms
*************************/
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm'),
ajaxForm = $('<div />', {
text : $this.attr('title')
});
// If the plugin hasn't been initialized yet
if ( ! data ) {
$(this).data('ajaxForm', {
target : $this,
ajaxForm : ajaxForm
});
//get the spinner, the valid box and the error box
var mySpinner = $this.find('.ajaxFormWait');
var myValid = $this.find('.ajaxFormValid');
var myError = $this.find('.ajaxFormError');
var myBeforeValid = $this.find('.ajaxFormBeforeValid');
myError.hide();
mySpinner.hide();
//add an event to send the form via AJAX
$this.submit(function(){
// get all the inputs into an array.
var $inputs = $this.find(':input:not([type="submit"], [type="button"])');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
if (this.type == "radio" || this.type == "checkbox"){
if($(this).is(':checked')){
if(typeof(values[this.name]) === 'undefined'){
values[this.name] = $(this).val();
}else{
values[this.name] += ', '+($(this).val());
}
}
} else
values[this.name] = $(this).val();
});
function defineTheInvalidsFields(fieldsList){
for(var i in fieldsList){
if(fieldsList[i] == 'closestStudio'){
$this.find('[name="'+fieldsList[i]+'"]').parent().addClass('invalid');
}else{
$this.find('[name="'+fieldsList[i]+'"]').addClass('invalid');
}
}
}
//send an AJAX request
$.ajax({
url: $this.attr('action'),
dataType: 'json',
data: values,
beforeSend: function(){
mySpinner.show();
},
success: function(result){
mySpinner.hide();
$this.find('.invalid').removeClass('invalid');
//error management
if(typeof(result.valid) === 'undefined'){
if(result.multipleSend){ //if multiple send
myError.html('Your request is already sent.');
}else if(result.required){ //if fields are required
defineTheInvalidsFields(result.required);
myError.html('The fields in red are required.');
}else if(result.format){ //if the forma is incorrect
defineTheInvalidsFields(result.format);
myError.html('The fields in red have invalid content.');
}else if(result.loginInvalid){
myError.html(result.loginInvalid);
}else{
myError.html('An unknown error occured.');
}
myValid.slideUp(300);
myError.slideDown(300);
}else if(typeof(result.loginUrl) !== 'undefined'){
window.location.href = result.loginUrl;
}else{
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
}
}
});
return false;
});
//special case for the heardAbout
$('#heardAbout').change(function(){
if($(this).find('option:selected').attr('value') == 'Other'){
$('#otherHeardAbout').slideDown(300);
}else{
$('#otherHeardAbout').slideUp(300);
}
});
}
});
},
destroy : function(){
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm');
// Namespacing FTW
$(window).unbind('.ajaxForm');
data.ajaxForm.remove();
$this.removeData('ajaxForm');
})
}
};
$.fn.ajaxForm = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.ajaxForm' );
}
};
})( jQuery );
The form gets sent to the other page, is there a way to target a specific div and add the custom message with the name.
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
if You wand to fetch specific element div via ajax call You can do like this:
$.ajax({
url: 'page.html',
success: function(data) {
item=$(data).filter('#specific_element');
$(selector).html(item);
}
});
If You wand to redirect to other page using
window.location = '/free-trial-thank-you/';
and then show data on a different page You should pass needet parameters like
window.location = '/free-trial-thank-you/page.php?name1=Daniel&name2=Pablo;
and on different site show parameters using _GET or _POST for example:
echo $_GET['name1'] or echo $_POST['name1'] if You use PSOT method in Your Ajax request
One way that I can think of is using session to store the information.
At freetrial.php store the form information in session like this:
session_start();
$_SESSION['firtNameTrial'] = $_GET['firstNameTrial'];
On ajax success, redirect the page to the thank you page using javascript windows.location.replace:
// similar behavior as an HTTP redirect
window.location.replace("http://yourwebpageaddress.com/thankyou.php");
Get the session on the thank you page. If you don't know, you may look at this example: Click here for session example

Cannot pass textarea input to PHP variable

To begin, I'm working with 3 languages. HTML, Javascript and PHP. I'm unable to pass user inputted textarea text to a PHP variable which would be used as a message in an email that would be sent out. What I believe to be the problem is that my textarea is actually in a modal window and for some reason I think that is what is screwing things up.
Here is my HTML Code:
<div class="rejectModal" title="rejectModal" id="rejectModal" style="display: none; padding:15px ">
<form name="rejectForm" action="">
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43">{$rejectAreaNote}</textarea>
<input type="button" value="Reject" class="btn success" id="submitReject" name="Reject" />
<input class="btn" type="reset" value="Cancel" id="btnCancelSaveModal" />
</form>
</div>
JS Code:
$(function() {
$(".submitReject").click(function() {
// validate and process form here
$('.error').hide();
var rejectAreaNote = $("textarea#rejectArea").val();
var noteLength = rejectAreaNote.length;
if (rejectAreaNote == "" || noteLength < 5) {
$("label#rejectArea_error").show();
$("textarea#rejectArea").focus();
return false;
}
var dataString = rejectAreaNote;
alert (dataString);
//return false;
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: {
"Reject" : "Reject",
"rejectAreaNote" : "rejectAreaNote"
},
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Submitted!");
}
});
return false;
});
});
What creates the Modal (JS):
$('.rejectModal').css("background", "lightblue");
$('#btnRejectDocument').bind(isTouchScreen ? "touchstart" : "click", function(){
if (!gsSelection.unselectElem()) return false;
$('.rejectModal').dialog({
modal:true,
resizable:false,
width: 400,
}).removeClass("ui-widget-content");
$(".ui-dialog-titlebar").hide();
return;
});
$('#btnRejectDocumentModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
$('#btnCancelSaveModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
PHP Code:
if(isset($_POST['Reject'])&&$_POST['Reject']=='Reject')
{
$isReject = true;
RejectAction($DocumentID, $ClientName, $ClientEmail);
$smartyvalues["isReject"] = $isReject;
$smartyvalues["RejectMsg"] = "successfully rejected!";
}
Also pretty new tot his
Any help is greatly appreciated.
Textarea does not have a value attribute. If you want to add a value to your textarea, add it inside the tag: <textarea>value</textarea>
So try changing it to this:
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43"/>{$rejectAreaNote}</textarea>
if(isset($_POST['Reject']) ...
You are not sending this to the server. Instead, you're sending "dataString", which is just the text from textarea. What you should do instead is send an object with needed fields:
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: {
"Reject" : "Reject",
"rejectAreaNote" : "rejectAreaNote"
},
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Submitted!");
}
});
I'm still not sure what your code is supposed to do and how it glues together, but this here is definitely wrong.

Adding reCaptcha to this jQuery AJAX form

I am having some problems adding a reCaptcha to my jQuery AJAX form.
I have tried following the documentation, in particular this page, but had no luck.
If I use the "Challenge and Non-JavaScript API", adding the code
before the send button, I get no output.
If I try with the method
called "AJAX API" adding a custom div inside the form, I don't get
anything anyway. Basically I am not able to show and then validate
it.
This is the code that I have so far.
My form:
<div id="contactForm"><img src="img/contact-form.png" width="250" height="365" alt="contact" /></div>
Name: <span class="contactErrorFloat" id="err-name">Need the name</span>
<input name="name" id="name" type="text" placeholder="Name.." />
Email: <span class="contactErrorFloat" id="err-email">Need email</span><span class="contactErrorFloat" id="err-emailvld">Email not valid.</span>
<input name="email" id="email" type="text" placeholder="Email.." />
Message:
<textarea name="message" id="message" rows="10" placeholder="Message.."></textarea>
<button id="send">Send</button>
<div class="contactError" id="err-form">Error during validation</div>
<div class="contactError" id="err-timedout">Timeout</div>
<div class="contactError" id="err-state"></div>
<div id="ajaxsuccess">Email sent!</div>
</form>
My Script:
jQuery(document).ready(function ($) {
$('#send').click(function(){
$('.error').fadeOut('slow'); // Resetta i messaggi di errore, nascondendoli
var error = false;
var name = $('input#name').val();
if (name == "" || name == " ") {
$('#err-name').fadeIn('slow');
error = true;
}
var email_compare = /^([a-z0-9_.-]+)#([da-z.-]+).([a-z.]{2,6})$/;
var email = $('input#email').val();
if (email == "" || email == " ") {
$('#err-email').fadeIn('slow');
error = true;
} else if (!email_compare.test(email)) {
$('#err-emailvld').fadeIn('slow');
error = true;
}
if (error == true) {
$('#err-form').slideDown('slow');
return false;
}
var data_string = $('#ajax-form').serialize();
$.ajax({
type: "POST",
url: $('#ajax-form').attr('action'),
data: data_string,
timeout: 6000,
error: function(request, error) {
if (error == "timeout") {
$('#err-timedout').slideDown('slow');
} else {
$('#err-state').slideDown('slow');
$('#err-state').html('C\'รจ stato un errore: ' + error + '');
}
},
success: function () {
$('ajax-form').slideUp('slow');
$('#ajaxsuccess').slideDown('slow');
}
});
return false;
});
});
There is also a PHP file with the php function to send the email but I don't think it's much important actually. I would really LOVE if someone could give me any help to implement this. Thanks a lot!
first of all you have to sign in to recaptcha. You can do this here:
recaptcha.net
then you can get your key. Then you embed the key into the sample code.
Here
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=**your_public_key**">
and here
<iframe src="http://www.google.com/recaptcha/api/noscript?k=**your_public_key**"
height="300" width="500" frameborder="0"></iframe>

Jquery Mobile - Getting an ajax result issue

Trying to do a simple web app with jquery mobile. I have put together a simple log in form with ajax results to be displayed. Problem is my ajax is not getting a result even when I alert out to see if the URL is valid. Is there something special I need to do using jquery mobile?
Any thoughts/answers much appreciated!
Here is the HTML code:
<div data-role="page" id="login" data-theme="a" data-add-back-btn="true">
<div data-role="header">
<h2>Log in</h2>
</div>
<div data-role="content" data-theme="a" data-add-back-btn="true">
<form action="mobilelogin.php" method="post">
Email: <input type="text" name="email" id="useremail">
Password: <input type="password" name="password" id="userpassword">
<input type="submit" value="Enter">
</form>
<div id="loginresult"></div>
</div>
<div data-role="footer"><h4>Chris Sherwood Design 2012</h4></div>
</div>
Js file:
$(document).ready(function() {
$('form').submit(function() {
var emailchecker = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $("#useremail").val();
var userpassword = $("#userpassword").val();
var checklength = userpassword.length;
if(email == ""){
alert('Please fill in email field');
return false;
}else if(userpassword == ""){
alert('Please fill in password field');
return false;
}else if((!emailchecker.test(email))){
alert('Please use a valid email');
return false;
}else if(checklength < 6 || checklength > 6){
alert('Password must be six characters');
return false;
}else{
var datastring = $(this).serialize();
alert(datastring);
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
}
});
PHP
<?php
echo 'nothing special here...';
?>
From your code:
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
You are returning false before the ajax request.
EDIT (assumed it was a simple mistake, have added more explanation)
You will need to either move that return false; to below the ajax() call, or use the event object like so:
$('form').submit(function(e) {
e.preventDefault();
The problem with just using return false; is that if there is an error in something before it it will not stop the default action. So if your ajax request errors it will miss the return false; and start loading the action page.

Categories