Forn Validation ignored with AJAX call - javascript

I have a form that uses an AJAX call to submit the info to Google Sheets which is working fine except when I try to add form validation. Then it is just running the AJAX call.
Below is my HTML Form:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<title>MooWoos Stall Booking</title>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800">
<link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--build:css css/styles.min.css-->
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/css/style.css">
<!--endbuild-->
</head>
<body>
<!-- Page Content -->
<div class="container">
<nav class="navbar navbar-toggleable-md navbar-light">
<a class="logo"><img src="assets/logo_opt.png"></a>
</nav>
<hr>
<div class="modal fade" id="redirect_page" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="form-horizontal">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="user_msg" align="left">Booking successful! Redirecting to PayPal... </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3 bookingform">
<h1>Stall Booking Form</h1>
<p class="lead">
Fill out the form to book and pay for your stall!
</p>
<form id="bookingForm">
<div class="form-group">
<label for="name">Name: </label>
<input type="text" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/>
</div>
<div class="form-group">
<label for="address">Address: </label>
<textarea name="address" class="form-control" placeholder="Your Address" value="" title="Please enter your address"></textarea>
</div>
<div class="form-group">
<label for="phone">Telephone Number: </label>
<input type="text" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on"/>
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="text" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address"/>
</div>
<div class="form-group">
<label for="date">Which date would you like to book?: </label>
<p><input type="radio" name="date" value="13th September" /> Sunday 13th September</p>
<p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p>
</div>
<div class="form-group">
<label>What type of stall do you require?</label>
<div>
<input type="radio" name="stallType" id="stallType-Preloved" value="Preloved">
<label for="stallType-Preloved">Preloved</label>
<div class="reveal-if-active">
<label for="c-rail">Will you be bringing a clothes rail?: </label>
<input type="radio" name="c-rail" value="Yes" /> Yes
<input type="radio" name="c-rail" value="No" /> No
</div>
</div>
<div>
<input type="radio" name="stallType" id="stallType-Craft" value="Craft">
<label for="stallType-Craft">Craft</label>
<div class="reveal-if-active">
<label for="craftName">What name do you use?</label>
<input type="text" id="craftName" name="craftName" class="require-if-active" placeholder="Craft Name" title="Please provide us with your Craft name" value="" />
</div>
</div>
<div>
<input type="radio" name="stallType" id="stallType-Business" value="Business">
<label for="stallType-Business">Business</label>
<div class="reveal-if-active">
<label for="bizName">What is your business name?</label>
<input type="text" id="bizName" name="bizName" class="require-if-active" placeholder="Business Name" title="Please provide us with your Business name" value="" />
<label for="insurance">Do you have Public Liability Insurance?</label>
<input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/> Yes
<input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/> No
</div>
</div>
</div>
<input type="button" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
</form>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © MooWoos 2018. Website by Luke Brewerton</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!--build:js js/mwbookings-min.js -->
<script src="js/jquery.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.serialize-object.min.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
</body>
</html>
And my JS file:
var $form = $('form#bookingForm'),
url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'
function validateForm() {
var errorMessage="";
var name=document.forms["bookingForm"]["name"].value;
if (name==null ||name==""){
errorMessage = "Your Name is required.\
";
}
if (errorMessage !=""){
alert(errorMessage);
return false;
}
}
$('#submit-form').on('click', function(e) {
//e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject(),
success: function () {
$('#redirect_page').modal('show');
window.setTimeout(function(){location.reload()},3000);
}
});
});
I have a sneaky feeling that I need to do my form validation within the submit function before the AJAX call but I am new to using JS to do this, previously I have used PHP to do it all.

The main issue is that you aren't calling the validateForm() function anywhere. You need to call that before the form is submit in order to check its validity.
You should also use a type="submit" button within your form for accessibility reasons. This will also allow users to submit the form by pressing the return key while a field is in focus. You can then hook to the submit event to handle the form submission. Try this:
<form id="bookingForm">
<!-- form fields... -->
<input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
</form>
function validateForm() {
var errorMessage = "";
var name = $('input[name="name"]').val();
if (name == null || name == "") {
errorMessage = "Your Name is required.\n";
}
return errorMessage;
}
$form.on('submit', function(e) {
e.preventDefault();
var error = validateForm();
if (error) {
alert(error);
return;
}
var jqxhr = $.ajax({
// ajax request...
});
});
You should however note that in most browsers the required attribute will achieve this logic for you without the need for any JS intervention.

var $form = $('form#bookingForm'),
url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'
function validateForm() {
var errorMessage="";
var name=document.forms["bookingForm"]["name"].value;
if (name==null ||name==""){
errorMessage = "Your Name is required.\
";
return true;
}
if (errorMessage !=""){
alert(errorMessage);
return false;
}
}
$('#submit-form').on('click', function(e) {
//e.preventDefault();
var res = validateForm();
if(res != false) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject(),
success: function () {
$('#redirect_page').modal('show');
window.setTimeout(function(){location.reload()},3000);
}
});
} else {
//handle else condition however u want
}
});

Related

page redirect after success bootstrap validation without using php

Team,
I am trying to redirect after success form validation. If it is not success it has to be there in same page if it is success it has to redirect other page
I have added below line after was class validated code
$(location).attr('href', 'data.html');
it is redirecting to next page but I am not seeing any error message I am missing some valdiation.
Here is my entire code.
$(function () {
'use strict'
$('#data_input').on('submit', function (event) {
if (!event.target.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
$(this).addClass('was-validated')
$(location).attr('href', 'data.html');
return true;
});
$("#resetbtn").on("click", function (event) {
event.preventDefault();
$('#data_input')
.trigger("reset")
.removeClass('was-validated')
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<form class="requires-validation" id="data_input" method="post" novalidate>
<div class="form-group row">
<div class="col">
<label> Name</label> <input type="text" class="form-control" name="projectName" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="col">
<label>Code</label> <input type="text" class="form-control" name="projectCode" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<div class="col">
<label>Number</label> <input class="form-control" type="text" name="sprintNumber" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<div class="col"> <label>Start Date:</label> <input type="text" class="form-control has-feedback-left" id="fromdate" placeholder="Please Enter Start Date" name="fromdate" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="col"> <label>End Date:</label> <input type="text" class="form-control has-feedback-left" id="todate" placeholder="Please Enter End Date" name="todate" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<!--<div class="form-group row">
<div class="col">
<label>Total Days</label> <input type="text" class="form-control has-feedback-left"
name="numberdays" id="numberdays" disabled>
</div>
</div>-->
<br />
<button id="submit" type="submit" class="btn btn-primary">Next</button>
<button id="resetbtn" type="button" class="btn btn-secondary">Clear</button>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
Please let me know what I am doing wrong here
in your event submit. You use a validation if statement (checkvalidity).
$('#data_input').on('submit', function (event) {
**if (!event.target.checkValidity()) {**
event.preventDefault()
event.stopPropagation()
}
$(this).addClass('was-validated')
**$(location).attr('href', 'data.html');**
return true; ...
but whether it is valid or not you still perform the location redirect afterwards.
the redirect should be placed in a if instead you will always be redirected before any validation.

What Missing in my JavaScript Code ? It does not work inside a WordPress Post

JavaScript, jQuery Experts,
I have the following coding, It work perfect when i check it in JSFiddle, but it does not work when I insert it in a WordPress post, so what should I do?
JSFiddle example: https://jsfiddle.net/m1aaaqo9/11/
WordPrss page link: https://kahoothack.net/kahoot-flood/
Note: The login button does not work in WordPress post neither it accept password and username. It seems the JavaScript is not working there. So how to fix it?
Check my WordPress post and below see the login box why it is not working. Thanks
HTML Part
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Validation Form</title>
<link href="https://fonts.googleapis.com/css?family=Alegreya+Sans" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Login Form</h1>
<span>Name:admin</span>
<span>password:123</span>
<div class="row">
<div class="col-md-4">
<form action="#" method="post" class="form-box" id="form">
<div class="form-group">
<label>Name:</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Enter Name"/>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" id="pass" name="pass" class="form-control" placeholder="Enter Password"/>
</div>
<div class="form-group">
<input type="submit" id="submit" name="pass" class="btn btn-md btn-info" value="Login"/>
<span id="Required" style="color:#ff0000;"></span>
</div>
<span id="error" style="color:#ff0000"></span>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</body>
</html>
JavaScript Part
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
var pass = $("#pass").val();
if(name == '' || pass == ''){
$("#Required").html('All Feild Are Required').css('color','red');
}else if(name == 'admin' && pass == '123'){
$("#form").html('<h4>User Login Successfully</h4>Back').css('color','green');
}else{
$("#error").html('User Are Not Valid');
}
});
});
CSS Part
h1{
font-size:25px;
margin:10px 0;
}
.form-box{
border:1px solid #d3d3d3;
padding:20px;
}
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
var pass = $("#pass").val();
if(name == '' || pass == ''){
$("#Required").html('All Feild Are Required').css('color','red');
}else if(name == 'admin' && pass == '123'){
$("#form").html('<h4>User Login Successfully</h4>Click').css('color','green');
}else{
$("#error").html('User Are Not Valid');
}
});
});
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Validation Form</title>
<link href="https://fonts.googleapis.com/css?family=Alegreya+Sans" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Login Form</h1>
<span>Name:admin</span>
<span>password:123</span>
<div class="row">
<div class="col-md-4">
<form action="#" method="post" class="form-box" id="form">
<div class="form-group">
<label>Name:</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Enter Name"/>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" id="pass" name="pass" class="form-control" placeholder="Enter Password"/>
</div>
<div class="form-group">
<input type="submit" id="submit" name="pass" class="btn btn-md btn-info" value="Login"/>
<span id="Required" style="color:#ff0000;"></span>
</div>
<span id="error" style="color:#ff0000"></span>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</body>
</html>
When you want to handle form submission in JavaScript, bind to the submit event of the form, not the click event of the submit button. Further, you need to cancel the default form submission event like so:
$('#form').submit(function handler(event) {
event.preventDefault(); // Cancel default form submission
const data = new FormData(this); // JQuery binds `this` to the form DOMNode
console.log("process the form data", data);
});
Keep in mind that form submission does not require JS by default. You're sometimes better off just submitting to the server and letting it do its work.
Remove all HTML, CSS and JS/jQuery code from your post and put just the following code inside your post:
<div class="container lh-custom">
<h1>Login Form</h1>
<span>Name:admin</span>
<span>password:123</span>
<div class="row">
<div class="col-md-4">
<form action="#" method="post" class="form-box" id="form">
<div class="form-group">
<label>Name:</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Enter Name"/>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" id="pass" name="pass" class="form-control" placeholder="Enter Password"/>
</div>
<div class="form-group">
<input type="submit" id="submit" name="pass" class="btn btn-md btn-info" value="Login"/>
<span id="Required" style="color:#ff0000;"></span>
</div>
<span id="error" style="color:#ff0000"></span>
</form>
</div>
</div>
</div>
Save your post.
Then put following code in your current theme's (Aspire Pro) functions.php:
/* Add custom jQuery and CSS */
function lh_add_custom_js_css(){
?>
<script>
jQuery(document).ready(function($){
$("#submit").click(function(){
var name= $("#name").val();
var pass = $("#pass").val();
if(name == '' || pass == ''){
$("#Required").html("All Feild Are Required").css("color","red");
}else if(name == "admin" && pass == "123"){
$("#form").html('<h4>User Login Successfully</h4>Back').css('color','green');
}else{
$("#error").html("User Are Not Valid");
}
});
});
</script>
<style>
.lh-custom h1{
font-size:25px;
margin:10px 0;
}
.lh-custom .form-box{
border:1px solid #d3d3d3;
padding:20px;
}
</style>
<?php
}
add_action( 'wp_footer', 'lh_add_custom_js_css' );
Save functions.php file and check the page again.

Remove 'undefined' values from JSON in AJAX

I have a form that submits data to a GoogleSheet as JSON via AJAX.
I want to change it so that blank fields show as just empty rather than showing as undefined in the GoogleSheet.
Below is my code:
HTML Form:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<title>MooWoos Stall Booking</title>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="UTF-8">
<link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--build:css css/styles.min.css-->
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/css/style.css">
<!--endbuild-->
</head>
<body>
<div class="container">
<nav class="navbar navbar-toggleable-md navbar-light">
<a class="logo"><img src="assets/logo_opt.png" alt="MooWoos Stall Booking"></a>
</nav>
<hr>
<div class="modal fade" id="redirect_page" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="form-horizontal">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="user_msg">Booking successful! Redirecting to PayPal... </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3 bookingform">
<h1>Stall Booking Form</h1>
<p class="lead">
Fill out the form to book and pay for your stall!
</p>
<form id="bookingForm" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<!-- BELOW ARE PAYPAL FIELDS FROM PAYPAL GENERATION -->
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" id="hosted_button_id" name="hosted_button_id" value="js_value">
<input type="hidden" name="currency_code" value="GBP">
<div class="form-group">
<label for="name">Name </label>
<input type="text" id="name" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/>
</div>
<div class="form-group">
<label for="address">Address </label>
<textarea id="address" name="address" class="form-control" placeholder="Your Address" title="Please enter your address" required></textarea>
</div>
<div class="form-group">
<label for="phone">Telephone Number </label>
<input type="tel" id="phone" pattern="(([0]{1})|([\+][4]{2}))([1]|[2]|[3]|[7]){1}\d{9}$" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on" required/>
</div>
<div class="form-group">
<label for="email">Email </label>
<input type="email" id="email" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address" required/>
</div>
<div class="form-group">
Which date would you like to book?
<p></p>
<p><input type="radio" name="date" value="13th September" required/> Sunday 13th September</p>
<p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p>
</div>
<div class="form-group">
<label>What type of stall do you require?</label>
<div>
<input type="radio" name="stallType" id="stallType-Preloved" value="Preloved" required>
<label for="stallType-Preloved">Preloved</label>
<div class="reveal-if-active form-inline">
Will you be bringing a clothes rail?
<label class="stallLabel" for="c-rail-yes">Yes</label> <input type="radio" id=c-rail-yes name="c-rail" value="Yes" />
<label class="stallLabel" for="c-rail-no">No</label> <input type="radio" id=c-rail-no name="c-rail" value="No" />
</div>
</div>
<div>
<input type="radio" name="stallType" id="stallType-Craft" value="Craft">
<label for="stallType-Craft">Craft</label>
<div class="reveal-if-active">
<label for="craftName">What name do you use?</label>
<input type="text" id="craftName" name="craftName" class="require-if-active form-control" placeholder="Craft Name" title="Please provide us with your Craft name" value="" />
</div>
</div>
<div>
<input type="radio" name="stallType" id="stallType-Business" value="Business">
<label for="stallType-Business">Business</label>
<div class="reveal-if-active">
<label for="bizName">What is your business name?</label>
<input type="text" id="bizName" name="bizName" class="require-if-active form-control" placeholder="Business Name" title="Please provide us with your Business name" value="" />
<br>
Do you have Public Liability Insurance?
<label class="insuranceLabel" for="insurance-yes">Yes</label> <input type="radio" id="insurance-yes" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/>
<label class="insuranceLabel" for="insurance-no">No</label> <input type="radio" id="insurance-no" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/>
</div>
</div>
</div>
<div>
<input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
</div>
</form>
<p></p>
</div>
</div>
<hr>
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © MooWoos 2018. Booking Form by Luke Brewerton</p>
</div>
</div>
</footer>
</div>
<!--build:js js/mwbookings-min.js -->
<script src="js/jquery.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.serialize-object.min.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
</body>
</html>
JS Code:
var $form = $('form#bookingForm'),
url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'
function disableAll() {
$('#c-rail-yes').attr('required', false).attr('disabled', true);
$('#c-rail-no').attr('required', false).attr('disabled', true);
$('#craftName').attr('required', false).attr('disabled', true);
$('#bizName').attr('required', false).attr('disabled', true);
$('#insurance-yes').attr('required', false).attr('disabled', true);
$('#insurance-no').attr('required', false).attr('disabled', true);
}
$('#stallType-Preloved').change(function () {
if(this.checked) {
disableAll();
$('#c-rail-yes').attr('required', true).attr('disabled', false);
$('#c-rail-no').attr('required', true).attr('disabled', false);
$('#hosted_button_id').attr('value', '7L75UXEHSKFLG');
}
});
$('#stallType-Craft').change(function () {
if(this.checked) {
disableAll();
$('#craftName').attr('required', true).attr('disabled', false);
$('#hosted_button_id').attr('value', 'HFTF3KS5T2ETA');
}
});
$('#stallType-Business').change(function () {
if(this.checked) {
disableAll();
$('#bizName').attr('required', true).attr('disabled', false);
$('#insurance-yes').attr('required', true).attr('disabled', false);
$('#insurance-no').attr('required', true).attr('disabled', false);
$('#hosted_button_id').attr('value', '48R67JG4F7H4J');
}
});
$('#submit-form').on('click', function(e) {
var valid = this.form.checkValidity();
if (valid) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
dataType: "json",
data: $form.serializeObject(),
beforeSend: function (key,value) {
return (value == undefined) ? "" : value
},
success: function () {
$('#redirect_page').modal('show');
$('#bookingForm').submit();
}
});
}
});
I have tried using beforeSend but this does not seem to have any effect.
Assuming there are no nested objects in your form, you can simply loop on your object elements before sending them
let jsObj = $form.serializeObject();
Object.keys(jsObj).forEach(key => {
jsObj[key] = jsObj[key] ? jsObj[key] : "";
})
Then you'll just have to send that object via AJAX :
$('#submit-form').on('click', function(e) {
var valid = this.form.checkValidity();
if (valid) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
dataType: "json",
data: jsObj,
beforeSend: function (key,value) {
return (value == undefined) ? "" : value
},
success: function () {
$('#redirect_page').modal('show');
$('#bookingForm').submit();
}
});
}
});

Mailchimp api using Jquery Ajax

I am having trouble getting the input to subscribe on submit and having it post to a Mailchimp subscription list.
I am using Jquery and Ajax as you can see in the code. I know my api endpoint is good because I tested it on Postman and was able to add a subscriber. However when I run my code locally it does not work.
I also tried to use the embedded code that mailchimp provides and when I would test, it would say that it is sending me an email to confirm addition to the subscribe list. But I never get an email to confirm and it never added to my subscription list. The code doesnt have https: in the links but I did have it in when I tested and did not work.
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="//bigbreakbjj.us14.list-manage.com/subscribe/post?u=06d10966e94997bd9b2564cb2&id=2eb203c03a" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<div id="mc_embed_signup_scroll">
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name </label>
<input type="text" value="" name="FNAME" class="" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name </label>
<input type="text" value="" name="LNAME" class="" id="mce-LNAME">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_06d10966e94997bd9b2564cb2_2eb203c03a" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
$("#new-person-form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "https://bigbreakbjj.us14.list-manage.com/subscribe/post?u=06d10966e94997bd9b2564cb2&id=2eb203c03a",
dataType: "jsonp",
data: {
"EMAIL": $("#email").val()
},
success: function(data) {
console.log(data);
alert("Subscribed!");
},
error: function() {
alert("Cannot subscribe");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3">
<h4><strong>Sign Up Today</strong></h4>
<form id="new-person-form" action="https://bigbreakbjj.us14.list-manage.com/subscribe/post?u=06d10966e94997bd9b2564cb2&id=2eb203c03a">
<h6>First Name</h6>
<div>
<input type="text" id="first-name" />
</div>
<h6>Last Name</h6>
<div>
<input type="text" id="last-name" />
</div>
<h6>Phone Number</h6>
<div>
<input type="text" id="phoneNumber" />
</div>
<h6>Email</h6>
<div>
<input type="email" id="email" />
</div>
<div>
<button type="submit">Submit Form</button>
</div>
</form>
</div>

Uncaught SyntaxError: Unexpected token : error in API call to Desk.com

I am receiving an error whenever I make a call to the Desk.com API. The error is:
users?callback=jQuery1122045…_1462470520820&_=1462470520821:1 Uncaught SyntaxError: Unexpected token :
I have tried a different API endpoint as well as different settings within the AJAX method with no change. Here is my jquery:
$(document).ready(function () {
//On Click Submission
$( "#submit" ).click(function(evt) {
//Prevent Default of changing pages
evt.preventDefault();
var data;
//Variable List
var email = document.getElementById("InputEmail").value;
var password = document.getElementById("InputPassword").value;
var url = document.getElementById("InputUrl").value;
var input = document.getElementById("csv-file");
console.log(email,password,url);
// //Papa Parse Module to parse data
// Papa.parse(input.files[0], {
// header: true,
// dynamicTyping: true,
// complete: function(results) {
// data=results;
// console.log(data);
// }
// });
//Ajax request
var test_url = "https://zzz-leaflet.desk.com/api/v2/users";
var test_email = "e*******m";
var test_pw = "B****1";
$.ajax(test_url,{
'contentType':'application/json',
'accepts':{'json':'application/json'},
'username':test_email,
'password':test_pw,
'method':'GET',
'dataType':'jsonp',
success: function(data) {
console.log(data);
}
});
return;
})
});
Here is my HTML as well:
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="main.js"></script>
<script src="node_modules/papaparse/papaparse.min.js"></script>
</head>
<body>
<div>
<form>
<!-- Email Adress -->
<fieldset class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="InputEmail" placeholder="Enter email">
<small class="text-muted">We'll never share your email with anyone else.</small>
</fieldset>
<!-- Password -->
<fieldset class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="InputPassword" placeholder="Password">
</fieldset>
<!-- URL -->
<fieldset class="form-group">
<label for="exampleInputUrl1">URL</label>
<input type="url" class="form-control" id="InputUrl" placeholder="URL ex. https://companyname.desk.com/">
</fieldset>
<!-- FIle Input -->
<fieldset class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" class="form-control-file" id="csv-file">
<small class="text-muted">Make sure your CSV is correctly formatted</small>
</fieldset>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
Cases
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
Customers
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios3" value="option3" >
Companies
</label>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>
<div>
</body>
</html>

Categories

Resources