Is my HTML form sending to a Netlify lambda function correctly? - forms

With a site running on Netlify, I'm trying to send an automatic reply using Mailgun to a site visitor who submits a form.
I'm trying to follow this example to do it:
https://gist.github.com/flatlinediver/0bdca4c2ae09d34d351d45230d3b2489
However, when I try to run this locally and submit the form (using netlify dev), I keep running into this error:
Request from ::1: POST /.netlify/functions/submission-created
Response with status 500 in 1 ms.
SyntaxError: Unexpected token a in JSON at position 1
at JSON.parse (<anonymous>)
at Object.exports.handler (/Users/sam/Projects/wycd/functions/submission-created.js:15:23)
at /usr/local/lib/node_modules/netlify-cli/src/utils/serve-functions.js:117:29
at Layer.handle [as handle_request] (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/layer.js:95:5)
at next (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/route.js:137:13)
at next (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/route.js:131:14)
at next (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/route.js:131:14)
at next (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/route.js:131:14)
at next (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/route.js:131:14)
at next (/usr/local/lib/node_modules/netlify-cli/node_modules/express/lib/router/route.js:131:14)
Here is my file for the function submission-created
require('dotenv').config()
const apiKey = process.env.MAILGUN_API_KEY
const domain = process.env.DOMAIN
// const receiver_mail = process.env.RECEIVER_MAIL
const mailgun = require('mailgun-js')({ apiKey, domain })
exports.handler = function(event, context, callback) {
if(event.httpMethod!='POST' || !event.body){
return callback(new Error('An error occurred!'))
}
const data = JSON.parse(event.body);
if(data.antibot.length>0){
return callback(new Error('Forbidden access'))
}
let messageData = {
from: data.email,
to: data.email,
subject: `Message received from ${data.name}`,
text: `${data.message}`
}
mailgun.messages().send(messageData, function (error) {
if (error) {
return callback(error);
} else {
return callback(null, {
statusCode: 200,
body: 'success'
});
}
})
}
And here is my code for the HTML form on index.html
<form class="contact" id="contactForm" action="/.netlify/functions/submission-created" name="contactForm" method="POST" data-netlify="true">
<input type="text" class="large" id="name" name="name" placeholder="Your Name *" required>
<input type="text" class="large" id="email" name="email" placeholder="example#email.com *" required>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="tel" class="large" id="phone" name="phone">
<script src="build/js/utils.js"></script>
<script>
var input = document.querySelector("#phone"),
output = document.querySelector("#output");
var iti = window.intlTelInput(input, {
nationalMode: true,
utilsScript: "../../build/js/utils.js?1562189064761" // just for formatting/placeholders etc
});
var handleChange = function() {
var text = (iti.isValidNumber()) ? "International: " + iti.getNumber() : "Please enter a number below";
var textNode = document.createTextNode(text);
output.innerHTML = "";
output.appendChild(textNode);
};
// listen to "keyup", but also "change" to update when the user selects a country
input.addEventListener('change', handleChange);
input.addEventListener('keyup', handleChange);
</script>
<input type="text" id="role" name="role" style="display: none;">
<button type="submit" style="background: black; cursor: pointer;">Submit</button>
<p class="text-sm"><em>When you click Submit, we'll send your details to a top climate organization who will guide you on further action.</em></p>
</form>
Can anybody share advice to get this function working as expected?

Related

doGet fails when same commands are called as a subfunction within it

Trying to learn Google Web Apps, I'm having the hardest time in 4 years of studying Google services. At this point, with help from other people, I have assembled a Web App form which successfully processes a few questions and accepts the submission of a file, sending the file to a folder on my Google Drive, appending the form answers to a Google Sheet, and sending me an email alerting me to the form submission. I think I understand how it works, but in trying to make the simplest of changes to it, it stopped working and gave me an error message I don't what to do with.
The form requires the user to upload an image of their COVID vaccination card. Since some people have more than one card, the form allows the user to upload more than file. This screen shot shows what the form displays upon successful submission.
The form fields and their answers remain in place, and below them appears the message "Uploaded successfully! You may upload another." What I want to have happen, besides a message like this appearing, is for all form fields and their answers disappear except for the Vacc Card/Choose File and Submit buttons.
So, I am trying to follow the instructions in this video from the highly popular YouTube Channel Learn Google Sheets & Excel Spreadsheets: Create Views (Pages) in Web App - Google Apps Script Web App Tutorial - Part 7
In this video, we see how to make the submission of a Web App form add to the current URL the string "?v=form" or "?v=whatever" and have the DoGet(e) function offer a different HTML file depending on whether the URL contains "&v" and if does, what follows that.
However, in following THE VERY FIRST STEP in the instructions, the App stopped working. All I did was cut what was inside the function doGet(e), place it inside a new function loadForm(), and put inside the doGet a calling of that function:
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
}
This one change caused the App to fail, returning nothing but a screen reading "The script completed but did not return anything."
My code:
/*
* Original doGet function; works fine. */
// function doGet(e){
// return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
// .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
// }
/** Step that caused this to fail: */
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} // else {HtmlService.createHtmlOutput('<h1>Hello<h1>')} // This would have been the next step, and the step after that making a second HTML file.
// Commenting out this step did NOT help.
}
function loadForm(){
return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
} /** There you have it. All that follows is part of what works. */
function uploadFiles(formObject) {
var folderID = "1nvhxUoj9uRlE0KpBNjW3cosIuuRpAQly"; // Massage / VaccinationCards
try {
var folder = DriveApp.getFolderById(folderID);
var fileUrl = "";
//Upload file if exists
if (formObject.myFile.length > 0) {
var name = formObject.name;
var namePref = formObject.namePref;
var pronouns = formObject.pronouns;
var ready = formObject.ready;
var email = formObject.email;
var phone = formObject.phone;
var callTimes = formObject.callTimes;
var questions = formObject.questions;
var blob = formObject.myFile;
var file = folder.createFile(blob);
fileUrl = file.getUrl();
} else {
fileUrl = null;
}
SpreadsheetApp.openById("1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50").getSheetByName("cards")
.appendRow([name, namePref, pronouns, ready, email, phone, callTimes, questions, fileUrl, new Date()]);
GmailApp.sendEmail('atiqzabinski#gmail.com', 'New Vax Card Uploaded!', 'Hey sweetie, smells like business! https://docs.google.com/spreadsheets/d/1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50/edit', {name: 'Vacc Card Robot'});
return fileUrl;
} catch (error) {
return error.message;
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style = "background:none transparent;">
<!-- <link href="/tpm-styles.css" rel="stylesheet" type="text/css"> -->
<link href="https://transformphillymassage.com/tpm-styles.css" rel="stylesheet" type="text/css">
<link href="https://transformphillymassage.com/formstyles.css" rel="stylesheet" type="text/css">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p>
<label for="FormControlFile">Legal Name:</label>
<input name="name" class="form-control-file" type="text" size="35" required/>
<br>
<label for="FormControlFile">Preferred Name:</label>
<input name="namePref" class="form-control-file" type="text" size="30">
<br> <label for="FormControlFile">Pronouns:</label>
<input name="pronouns" class="form-control-file" type="text" size = "35">
</p>
<p>
<label for="FormControlFile">Choose One:</label>
<!-- <select id = "id_ready" name = "ready" class="form-control-file" required/> -->
<!-- <select id = "id_ready" name = "ready" required/> -->
<select name = "ready" class="form-control-file" required/>
<option value = "I'm ready to book!">I'm ready to book!</option>
<option value = "I have questions.">I have questions.</option>
</select>
</p>
<p>
<label for="FormControlFile">email:</label>
<input name="email" class="form-control-file" type="text" size = "40" required/>
<br>
<label for="FormControlFile">Phone Number:</label>
<input name="phone" class="form-control-file" type="text" size = "28" />
<br>
<label for="FormControlFile">Best Times To Call:</label><br>
<input name="callTimes" class="form-control-file" type="text" size="50"/>
</p>
<p>
<label for="FormControlFile">Vacc Card:</label>
<input name="myFile" class="form-control-file" type="file" required/>
</p>
<p>
<label for="FormControlFile">Questions / Comments:</label><br>
<textarea name ="questions" class="form-control-file" cols="45" rows="4"></textarea>
<br>
<button type="submit"><span class="charm spanlavender">Submit</span></button>
</p>
</form>
<div id="urlOutput"></div>
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject){
google.script.run.withSuccessHandler(updateUrl).withFailureHandler(onFailure).uploadFiles(formObject);
}
function updateUrl(url) {
var div = document.getElementById('urlOutput');
if(isValidURL(url)){
div.innerHTML = '<div class="alert alert-success" role="alert">Uploaded successfully!<br>You may upload another.</div>';
// document.getElementById("myForm").reset();
} else {
//Show warning message if file is not uploaded or provided
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ url +'!</div>';
}
}
function onFailure(error) {
var div = document.getElementById('urlOutput');
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ error.message +'!</div>';
}
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null);
}
</script>
</body>
</html>
return is missing on the else part of your if-else statement
Replace your doGet function by
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} else {
return HtmlService.createHtmlOutput('<h1>Hello<h1>')
}
}
Below are a couple of function that could be used to debug your doGet function by using the Google Apps Script editor.
/**
* Test case 1: v parameter equal to 'form'
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
e.parameter.v = 'form';
doGet(e);
}
/**
* Test case 2: No v parameter
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
doGet(e);
}
Related
Google App Script how to load different pages using HTML Service?
How can I test a trigger function in GAS?
getting parameters from a url returns 'parameter is undefined"
How to get a URL string parameter passed to Google Apps Script doGet(e)
Serve separate HTML pages Google apps script not working
doGet(e) parameter undefined

How to add a 'Send Message To' button on contact page?

I'm trying to add a "Send Message To" button on a contact form but I'm having trouble with the javascript/PHP. I'm using code I edited that came with the start bootstrap modern business theme, so far I have just added the $to = '$department', set the select tag ID as department and the value of option tags to the appropriate emails.
Not sure if any of that is correct.
HTML:
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Send Message To</label>
<select class="form-control" id="department">
<option value="sales#website.com">Sales</option>
<option value="support#website.com">Support</option>
</select>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-CMD" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
PHP:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$message = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = '$department';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Javascript
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
Im not quite sure about your questions, but if you're just trying to get the item from the department form, and send it to that email address, this is the code for that.
JS:
data: {
name: name,
email: email,
message: message,
department: document.getElementById('department').value
},
You must pass the value of the form to the PHP script. You originally had the $message var set to the message and then the next line would set that variable to the department. You need to keep them separate.
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$department = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = $department;
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Hope this works!

SharpSpring - Prevent form from automatically appearing if user has filled out form (without relying on cookies)

Ok, this is related to the question I asked a short while ago: Silverstripe/PHP/jQuery - Once form has been filled out by user, prevent it from automatically appearing for each visit
Something has changed since then. Per request of the client, the form must not automatically appear if the user has already filled it out and has thus been placed into SharpSpring. Originally, I was creating a cookie on successful form submission using JavaScript. However, the latest concern is that it's not effective enough as cookies are registered only to certain devices and browsers, and users can clear their cookies at any time.
Essentially, the desired result is to prevent the form from automatically appearing if the user has been registered in SharpSpring (a separate domain) without having to rely on cookies.
Has anyone ever attempted something like this, checking to see if a user has submitted a form to another domain?
For reference, here is the form code I have setup:
<?php
/*
Plugin Name: SharpSpring Form Plugin
Description: A custom form plugin that is SharpSpring-compatible and uses HTML, CSS, jQuery, and AJAX
Version: 1.0
*/
define('SSCFURL', WP_PLUGIN_URL . "/" . dirname(plugin_basename(__FILE__)));
define('SSCFPATH', WP_PLUGIN_DIR . "/" . dirname(plugin_basename(__FILE__)));
function sharpspringform_enqueuescripts()
{
wp_enqueue_script('jquery-src', SSCFURL . '/js/jquery.js', array('jquery'));
wp_enqueue_script('jquery-ui', SSCFURL . '/js/jquery-ui.js', array('jquery'));
wp_enqueue_script('boootstrap', SSCFURL . '/js/bootstrap.js', array('jquery'));
wp_localize_script('sharpspringform', 'sharpspringformajax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'sharpspringform_enqueuescripts');
function sharpspringform_show_form()
{
wp_enqueue_style( 'boilerplate', SSCFURL.'/css/boilerplate.css');
wp_enqueue_style( 'bootstrapcss', SSCFURL.'/css/bootstrap.css');
wp_enqueue_style( 'bookregistration', SSCFURL.'/css/Book-Registration.css');
wp_enqueue_style( 'formstyles', SSCFURL.'/css/styles.css');
?>
<div class="mobile-view" style="right: 51px;">
<a class="mobile-btn">
<span class="glyphicon glyphicon-arrow-left icon-arrow-mobile mobile-form-btn"></span>
</a>
</div>
<div class="slider register-photo">
<div class="form-inner">
<div class="form-container">
<form method="post" enctype="multipart/form-data" class="signupForm" id="browserHangFormPV">
<a class="sidebar">
<span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
</a>
<a class="closeBtn">
<span class="glyphicon glyphicon-remove"></span>
</a>
<h2 class="text-center black">Sign up for our newsletter.</h2>
<p class="errors-container light">Please fill in the required fields.</p>
<div class="success">Thank you for signing up!</div>
<div class="form-field-content">
<div class="form-group">
<input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
autofocus="">
</div>
<div class="form-group">
<input class="form-control CompanyTxt" type="text" name="company" placeholder="*Company"
autofocus="">
</div>
<div class="form-group submit-button">
<button class="btn btn-primary btn-block button-submit" type="button">SIGN ME UP</button>
<img src="/wp-content/plugins/sharpspring-form/img/ajax-loader.gif" class="progress" alt="Submitting...">
</div>
</div>
<br/>
<div class="privacy-link">
<a href="[privacy policy link]" class="already" target="_blank"><span
class="glyphicon glyphicon-lock icon-lock"></span>We will never share your information.</a>
</div>
</form>
<input type="hidden" id="gatewayEmbedID" value="<?php echo get_option( 'pv_signup_sharpspring_ID' ); ?>" />
<script type="text/javascript">
var embedID = document.getElementById("gatewayEmbedID").value;
var __ss_noform = __ss_noform || [];
__ss_noform.push(['baseURI', 'https://app-3QNAHNE212.marketingautomation.services/webforms/receivePostback/[redacted]']);
__ss_noform.push(['form', 'browserHangFormPV', embedID]);
__ss_noform.push(['submitType', 'manual']);
</script>
<script type="text/javascript" src="https://koi-3QNAHNE212.marketingautomation.services/client/noform.js?ver=1.24" ></script>
</div>
</div>
</div>
<?php
}
function sharpspringform_shortcode_func( $atts )
{
ob_start();
sharpspringform_show_form();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'sharpspringform', 'sharpspringform_shortcode_func' );
The form submission code with generates a cookie using JS:
;
(function ($) {
$(document).ready(function () {
var successMessage = $('.success');
var error = $('.errors-container');
var sharpSpringID = $('#gatewayEmbedID').val();
var submitbtn = $('.button-submit');
var SubmitProgress = $('img.progress');
var formdata = {};
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
submitbtn.click(function (e) {
resetErrors();
postForm();
});
function resetErrors() {
$('.signupForm input').removeClass('error-field');
}
function postForm() {
$.each($('.signupForm input'), function (i, v) {
if (v.type !== 'submit') {
formdata[v.name] = v.value;
}
});
submitbtn.hide();
error.hide();
SubmitProgress.show();
$.ajax({
type: "POST",
data: formdata,
url: '/wp-content/plugins/sharpspring-form/sharpsring-form-submission.php',
dataType: "json"
}).done(function (response) {
submitbtn.show();
SubmitProgress.hide();
if (response.errors) {
error.show();
var errors = response.errors;
errors.forEach(function (error) {
$('input[name="' + error + '"]').addClass('error-field');
})
}
else {
__ss_noform.push(['submit', null, sharpSpringID]);
setCookie('SignupSuccess', 'NewsletterSignup', 3650);
$('#browserHangFormPV')[0].reset();
$('.form-field-content').hide();
successMessage.show();
$('.button-submit').html("Submitted");
}
});
}
});
}(jQuery));
The jQuery code that sets up the form sliding animation and popup feature, as well as checks for the existence of the JS cookie created on successful form submit:
jQuery.noConflict();
(function ($) {
$(document).ready(function () {
//This function checks if we are in mobile view or not to determine the
//UI behavior of the form.
checkCookie();
window.onload = checkWindowSize();
var arrowicon = $(".arrow");
var overlay = $("#overlay");
var slidingDiv = $(".slider");
var closeBtn = $(".closeBtn");
var mobileBtn = $(".mobile-btn");
//When the page loads, check the screen size.
//If the screen size is less than 768px, you want to get the function
//that opens the form as a popup in the center of the screen
//Otherwise, you want it to be a slide-out animation from the right side
function checkWindowSize() {
if ($(window).width() <= 768) {
//get function to open form at center of screen
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(formModal, 5000);
function formModal() {
slidingDiv.addClass("showForm")
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
}
}
}
else {
//when we aren't in mobile view, let's just have the form slide out from the right
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(slideOut, 5000);
function slideOut() {
slidingDiv.animate({'right': '-20px'}).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("SignupSuccess");
if (user != "") {
return true;
} else {
return false;
}
}
/*
------------------------------------------------------------
Functions to open/close form like a modal in center of screen in mobile view
------------------------------------------------------------
*/
mobileBtn.click(function () {
slidingDiv.addClass("showForm");
slidingDiv.removeClass("hideForm");
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
});
closeBtn.click(function () {
slidingDiv.addClass("hideForm");
slidingDiv.removeClass("showForm");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay")
mobileBtn.removeClass("hideBtn");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
});
/*
------------------------------------------------------------
Function to slide the sidebar form out/in
------------------------------------------------------------
*/
arrowicon.click(function () {
if (slidingDiv.hasClass('open')) {
slidingDiv.animate({'right': '-390px'}, 200).removeClass('open');
arrowicon.addClass("glyphicon-arrow-left");
arrowicon.removeClass("glyphicon-arrow-right");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
} else {
slidingDiv.animate({'right': '-20px'}, 200).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
});
});
}(jQuery));
I'm confused by the WordPress code here, rather than SilverStripe, it's not clear in your question which platform you're using.
Basically, if you want something more robust than cookies, you'll need to store the registration in the database and check it there (assuming the registration form is on your site). This means you handle the form submission on your site, send the data to the remote site and check the responses, and if all goes well, save the fact that the user has registered remotely into your database where you can check when deciding whether to show the form or not, next time.
If you don't have access to the registration form, or you want to also notice registrations made independently of your site, then you need to have an API you can query on the remote site in order to see if the user is registered.
I found a sharpspring API, but I'm not sure if it's relevant.

cannot submit a form with jQuery

I've this form
<form id="frm_main" action="#" method=POST>
<input type=hidden name="MAX_FILE_SIZE" value="100000" />
<input id='file' name="file" type="file">
<input type=submit id='btn_import' name='btn_import' value='Importar' />
<input type=hidden id="uploadResponseType" name="mimetype" value="html" />
<input type=hidden id="func" name="func" value="upload" />
<div id="uploadOutput"></div>
</form>
So, the problem became when I try to post the upleaded file. If I use ajaxSubmit function the form is submited but it doesn't return to the page; and if I use $.ajax function, it doesn't sent the uploeade file. The thing is that I need to return to the same page because I've to do some stuff with the file content. I've already tried lot of combinations but I'm still having the same results. The code to handle submit look like this
$( '#frm_main' ).bind( 'submit', function( e ) {
// e.preventDefault(); // <-- important
$( this ).ajaxSubmit({
target: '#uploadOutput', // <-- div container
type: "POST", // <-- override, just in case.
url: "/process.php", // <-- server-side handler
data: "func=upload", // <-- parameter for post purpouse
beforeSubmit: function(a,f,o) {
o.dataType = $('#uploadResponseType').val(); // should be 'html'.
$('#uploadOutput').html('Submitting...');
},
success: function(data) {
var $out = $('#uploadOutput');
$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
$out.append('<div><pre>'+ data +'</pre></div>');
}
});
return false;
});
And I've already tried with next code
$('#frm_main').bind('submit', function() {
var formdata = $(this).serialize();
$.ajax({
url: '/process.php',
data: formdata,
dataType: 'html',
success: function(data){
var $out = $('#uploadOutput');
$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
}
});
return false;
});
And process.php code looks like this
switch($_POST['func']) {
case 'upload' :
$output = upload_file ();
echo $output;
break;
default :
echo "<BR/>INVALID";
break;
}
?>
Can somebody help me with this situation, please? Any help will be gratefully appreciated
Don't you need form enctype="multipart/form-data" to upload files?

jQuery Ajax Submit issues

the Form
<article id="signup-form">
<form id="signupform" method="post" action="signup.php" accept-charset="utf-8">
<label for="email">Email Address</label>
<input type="text" id="email" name="email"/>
<input type="image" src="images/btn_signup.png" value="Sign up" alt="Sign up"/>
</form>
<br />
</article>
the Javascript
$(document).ready(function () {
$('#signupform').submit(function () {
var email = $('#email').val();
if (email != 0) {
if (isValidEmailAddress(email)) {
$(this).ajaxSubmit(options);
} else {
alert("Please Enter a Valid Email Address");
}
} else {
alert("Please Enter a an Email Address");
}
return false;
});
var options = {
success: showResponse,
dataType: 'json',
resetForm: true
};
function showResponse(responseText, statusText, xhr, $form) {
if (responseText == 'false') {
alert("Please try again. We could not sign you up.");
}
if (responseText == 'true') {
alert("Success");
}
}
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
i get the folowing error and the form submits and goes to the signup.php
You can prevent the forms default event by altering your call
$('#signupform').submit(function (event) and the entering event.preventDefault