validate and submit form via jquery ajax - javascript

I have below jquery code for validation and html code for form. I would like to validate the form and then submit. Both the pieces of code are working properly ie for validation and for submit. The thing is how should I combine the code so that it can validate the form first and then submit it.

To get this done i did several changes to your script.
$(document).ready(function(){
//global vars
var form = $("#subscribeForm");
var name = $("#name");
var email = $("#email");
var nameInfo = $("#nameInfo");
var emailInfo = $("#emailInfo");
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
var value = $('#button input').val();
var name1 = $('#button input').attr('name');
$('#button input').remove();
$('#button').html('<a href="#" class="cssSubmitButton" rel=' + name1 + '>' + value + '</a>');
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^(([^<>()[\]\\.,;:\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,}))$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("Valid E-mail please, you will need it to log in!");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Type a valid e-mail please :P");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
$('#button').on('click','a',function () {
var isValid = false;
if(validateName() & validateEmail())
isValid = true
else
isValid = false;
//You can use default form submission or with the ajax call below
//In this example, I'm using a dummy php call so that you can see the loading animation
//$('form[name=' + $(this).attr('rel') + ']').submit();
if(isValid)
{
var link = $(this);
$.ajax({
url : 'load.php',
data: '',
type: 'GET',
cache: 'false',
beforeSend: function () {
link.addClass('loading');
},
success: function () {
link.removeClass('loading');
$('#button').css('display','none');
$('#success').css('display','block');
alert('Submitted');
},
error: function() {
}
});
}
});
});
and added some id's to your html.
<form method="post" action="" id="subscribeForm" name="subscribeForm">
<fieldset>
<label>Name: </label><input type="text" class="effect" name="name" id="name">
<span id="nameInfo">What's your name?</span>
</fieldset>
<fieldset>
<label>Email: </label><input type="text" class="effect" name="email" id="email">
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</fieldset>
<div id="button">
<input type="submit" value="Subscribe" name="subscribeForm"/>
</div>
<div id="success">
<strong>Data Saved Successfully.</strong>
</div>

Thanks for your answers but even I got my code working. The below is the working code.
Java Script
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
var value = $('#button input').val();
var name = $('#button input').attr('name');
$('#button input').remove();
$('#button').html('<a href="#" class="cssSubmitButton" rel=' + name + '>' + value + '</a>');
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
//On Submitting
$('#button a').live('click', function () {
var link = $(this);
if(validateName() & validateEmail())
{
var link = $(this);
$.ajax({
url : 'load.php',
data: '',
type: 'GET',
cache: 'false',
beforeSend: function () {
link.addClass('loading');
},
success: function () {
link.removeClass('loading');
$('#button').css('display','none');
$('#success').css('display','block');
alert('Submitted');
},
error: function() {
}
});
return true
}
else
{
return false;
}
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("Valid E-mail please, you will need it to log in!");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Stop cowboy! Type a valid e-mail please :P");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
});
/*]]>*/
</script>
CSS Script.
<style type="text/css">
body {
font-family: arial;
font-size:12px;
margin:10px;
text-align:center;
}
form {
margin:0 auto;
text-align:left;
width:270px;
border:1px solid #ccc;
padding:15px;
background:#fff;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
box-shadow: 0 0 4px #ccc;
-webkit-box-shadow: 0 0 4px #ccc;
-moz-box-shadow: 0 0 4px #ccc;
}
fieldset {
overflow:hidden;
border:0;
height:30px;
margin:3px 0;
}
fieldset label {
display:block;
width:50px;
float:left;
font-weight:700;
color:#666;
line-height:2.2em;
}
fieldset input {
float:left;
border:1px solid #ccc;
height: 20px;
padding:3px;
width:190px;
font-size:12px;
}
#button {
margin-top:10px;
padding-right:20px;
text-align:right;
}
#button input {
margin:0 auto;
}
a.cssSubmitButton {
font-size: 12px;
background: #fff no-repeat 4px 5px;
display: inline-block;
padding: 5px 20px 6px;
color: #333;
border:1px solid #ccc;
text-decoration: none;
font-weight: bold;
line-height: 1.2em;
border-radius: 15px;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-moz-box-shadow: 0 1px 3px #999;
-webkit-box-shadow: 0 1px 3px #999;
position: relative;
cursor: pointer;
outline:none;
}
a.cssSubmitButton:visited {}
a.cssSubmitButton:hover {
border:1px solid #333;
}
.loading {
background-image:url('load.gif') !important;
color:#ccc !important;
-moz-box-shadow: 0 0 0 #fff !important;
-webkit-box-shadow: 0 0 0 #fff !important;
}
.effect {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#success{
text-align:center;
font-size:12px;
margin-top:10px;
display:none;
color:#458B00;
}
#subscribeForm div span.error{
color: #e46c6e;
}
#subscribeForm input.error{
background: #f8dbdb;
border-color: #e77776;
}
#subscribeForm span.error{
color: #e46c6e;
}
</style>
Html Form.
<form method="post" action="" id="subscribeForm" name="subscribeForm">
<fieldset>
<label>Name: </label><input type="text" class="effect" name="name" id="name" >
<span id="nameInfo">What's your name?</span>
</fieldset>
<fieldset>
<label>Email: </label><input type="text" class="effect" name="email" id="email" >
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</fieldset>
<div id="button">
<input type="submit" value="Subscribe" name="subscribeForm"/>
</div>
<div id="success">
<strong>Data Saved Successfully.</strong>
</div>
</form>

Related

How to return Google App Script result to external web page?

I found a GAS that will search a column for an ID number that has been entered to a Google Sheet by means of an HTML form. Once the ID# is found it will check a date in a different column and will return a message based on the date in the column relative to today's date. When I run the GAS I get the message returned to me from the result of the script but what I am looking to do is return the result of the script back to the webform to notify a user of the message after they submit the form. It doesn't have to be a GAS ... if anyone can do the same with Javascript I am all ears. Thanks in advance.
I have already tried to figure out how to call on the GAS from the html page but have had no success.
GAS:
<!-- Search Sheet for Bottle Expiration date -->
var ss = SpreadsheetApp.openByUrl("GSURL");
var sheet = ss.getSheetByName("Entries");
function doGet(e){
return search(e) ;
}
function doPost(e){
return search(e) ;
}
function search(e){
var id = e.parameter.last_name;
var values = sheet.getRange(2, 2, sheet.getLastRow(),sheet.getLastColumn()).getValues();
for(var i = 0;i<values.length; i++){
if(values[i][0] == id ){
i=i+2;
var name = sheet.getRange(i,4).getValue();
var hydroDate = Date.now()+14;
var hydroalert = ContentService.createTextOutput("Bottle is due for Hydro").setMimeType(ContentService.MimeType.TEXT)
if (hydroDate <= name)
return hydroalert;
}
}
return ContentService.createTextOutput("Id not found").setMimeType(ContentService.MimeType.TEXT);
}
HTML Page
<!DOCTYPE html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>UFD Tour 2 Monthlies</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css" media="screen, handheld"/> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="ufd_tour_2_monthlies.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="qrscan.js?rev=<?php echo time();?>"></script>
<script src="https://rawgit.com/sitepoint-editors/jsqrcode/master/src/qr_packed.js">
</script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- Place this within the <head> tag or just before the end of your <body> tag. -->
<script src="https://awesome-table.com/AwesomeTableInclude.js"></script>
</head>
<style>
h2 {
text-align: center;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
.cancelbtn,.signupbtn {
float: left;
width: 50%;
}
.container {
padding: 16px;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
.form_container { width: 90%; max-width:450px; margin:20px 30px 40px 30px; padding:15px 20px; font-size:15px; line-height:25px; text-align:left; background:#EBEBEB; }
.form_field { display:block; width:100%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.form_button { display:block; width:100%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.form_message { }
body, input {font-size:14pt}
input, label {vertical-align:middle}
.qrcode-text { display:block; width:90%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.qrcode-text-btn { display:block; text-align:center; width:90%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.qrcode-text-btn > input[type=file] {position:absolute; overflow:hidden; width:1px; height:1px; opacity:0}
</style>
<body>
<h2>Tour 2 Monthlies</h2>
<div class="container">
<form id="sheets" name="sheets" class="form_body">
<label for="first_name">Date</label>
<input id="first_name" name="first_name" type="date" class="form_field" value="" placeholder="Select Date"/>
<label for="last_name">Bottle Number</label>
<input id="last_name" name="last_name" class="form_field" onfocus="this.value='';" value="" placeholder="Select here to scan or enter manually"/>
<input type="button" name="btnScanBarcode" id="btnScanBarcode" class="form_button" value="Scan Bottle" onclick="javascript:openQRCamera(this);"></button>
<!-- <input id="last_name" name="last_name" type=text placeholder="Select here to scan or enter manually" class="qrcode-text"><label class="qrcode-text-btn"><input type=file accept="image/*" capture=environment onclick="openQRCamera(this);" tabindex=-1>Scan Bottle</label>
<script>function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("No QR code found. Please make sure the QR code is within the camera's frame and try again.");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}</script> -->
<script>
function startBarcodeScanner()
{
window.location.href = 'bwstw://startscanner?field=last_name';
}
</script>
<label for="email">Bottle Location</label>
<select id="email" name="email" class="form_field" value="" placeholder="Bottle Location"/>
<option>ENGINE 1</option>
<option>ENGINE 2</option>
<option>ENGINE 3</option>
<option>SQUAD 4</option>
<option>SQUAD 41</option>
<option>LADDER 1</option>
<option>TRUCK 1</option>
<option>TRUCK 2</option>
<option>TRUCK 3</option>
<option>ENGINE 5</option>
<option>ENGINE 6</option>
<option>ENGINE 7</option>
<option>RESCUE 1</option>
<option>RESCUE 2</option>
<option>RESCUE 3</option>
<option>STATION 1 SPARE</option>
<option>STATION 2 SPARE</option>
<option>STATION 3 SPARE</option>
<option>SPECIAL OPS</option>
<option>BC</option>
<option>COD</option>
<option>DC</option>
<option>EMSC</option>
<option>FINV</option>
<option>COMM</option>
<option>TRAIN</option>
<option>BOAT</option>
<option>SPARE MASK</option>
<option>O/S</option>
<option>OTHER LOCATION</option>
<option>OTHER VEHICLE</option>
</select>
<input id="gs_code" name="gs_code" type="hidden" class="" value="=VLOOKUP(B:B,HydroBottles,4,FALSE)" placeholder=""/>
<div class="clearfix">
<input id="submit" name="submit" type="button" class="form_button" value="Enter Bottle" onClick="submit_form(); document.getElementById('last_name').value = ''; playAudio()"/>
<audio id="beep">
<source src="bleep.mp3" type="audio/mpeg">
</audio>
<div class="form_message" id="message">
<script>
var gs_hydrosearch = 'https://script.google.com/macros/s/AKfycby0VsXuYk-dODBhKpL-zFUeb5xI79Y8jGR0e20I/exec?id=gs_field';
var gs_field = ['last_name'];
function HydroSearch() {
doPost(
</script>
</div>
</div>
</div>
<!-- Place this tag where you want the Awesome Table Widget to render -->
<div data-type="AwesomeTableView" data-viewID="-LfNI2wu42vUdIl5oy9c"></div>
</form>
</body>
</html>
JS file that sends the data from the form to the Google Spreadsheet:
function submit_form() {
// Check Fields
var complete = true;
var error_color = '#FFD9D9';
var fields = ['first_name','last_name','email','gs_code'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
// Validate Field
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
// Sheet Data
row += '"'+value+'",';
}
}
// Submission
if(complete) {
// Clean Row
row = row.slice(0, -1);
// Config
var gs_sid = 'GSID'; // Enter your Google Sheet ID here
var gs_clid = 'Client ID'; // Enter your API Client ID here
var gs_clis = 'API Client Secret'; // Enter your API Client Secret here
var gs_rtok = '0Auth RT'; // Enter your OAuth Refresh Token here
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Entries!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
// HTTP Request Token Refresh
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
// HTTP Request Append Data
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-length', gs_body.length);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.onload = function() {
if(xxhr.status == 200) {
// Success
$('audio#beep')[0].play();
$('#message').hide().html("Bottle has been Entered! Scan next Bottle.").fadeIn().delay('1000').fadeOut().delay('7000');
}
else {
// Fail
$('#message').html('<p>Row Not Added</p><p>Response:<br/>'+xxhr.responseText+'</p>');
}
};
xxhr.send(gs_body);
}
};
xhr.send();
}
}
The answer to your question is encapsulated in this documentation It's called client to server communication. Presently your question is far to broad you need to do more research and perhaps some of your own debugging. I also recommend that you take this opportunity to take the [tour] and learn how to [ask] and [mcve].

Why is the item in the array undefined? [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
So I want to pass my JS array to my PHP code with AJAX, and I am facing a problem.
My problem is the following: When I send my array to the php, it gives me the following error:
Notice: Undefined index: foods_added in
C:\xampp\htdocs\etterem\order-food.php on line 2
My codes are the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rendelés felvétele</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
.list {
padding-top: 20px;
}
.result {
background-color: white;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// var fields = 1;
// function add_fields() {
// fields++;
// var objTo = document.querySelector('.search-box')
// var divtest = document.createElement("div");
// divtest.innerHTML = '<input type="text" autocomplete="off" placeholder="Étel keresése"/><div class="result"></div>';
// objTo.appendChild(divtest)
// }
var foods_added = [];
function add_food() {
var food_name = document.getElementById('food_name').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(food_name));
list.appendChild(entry);
foods_added.push(food_name);
document.getElementById('food_name').value = "";
}
function submit_list() {
$.ajax({
url: "order-food.php",
method: "post",
data: { foods_added : JSON.stringify(foods_added) },
success: function(res) {
console.log(res);
}
})
window.location.href = "order-food.php";
}
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<!-- <input type="button" onclick="add_fields();" value="Hozzáad"> -->
<div class="search-box">
<input id="food_name" type="text" autocomplete="off" placeholder="Étel keresése" />
<div class="result"></div>
<input style="width: 130px;" type="button" onclick="add_food();" value="Hozzáad">
<input style="width: 130px;" type="button" onclick="submit_list();" value="Rendelés felvétele">
</div>
<div class="list">
<ol id="list" name="food"></ol>
</div>
</body>
</html>
<?php
$added_foods = json_decode($_POST['foods_added']);
?>
The second code is order-food.php, which I would use to work with the array (in the end it would submit the items of the array into a database)
You start the ajax request but then you refresh the page by calling
window.location.href = "order-food.php";
so the ajax request is halted and the page reloads, with no post values. Just delete that line, to let the request finish.
Then the method is set with the "type" parameter, not "method". So change the line in the ajax request from
method:"POST"
to
type:"POST"

Jquery functions continue to apply even the CSS is changed. How do I stop this?

The fiddle first.
I have nameCards which expand and contract when clicked by adding/removing classes. Additionally, they move to different sections in the page when buttons are clicked (again by adding/removing classes). The problem: Despite them no longer having the classes needed to trigger the functions, the function still applies to them.
In the code, they move from .unmatched to .matched, so the function selector $('.matched.nameCard') should no longer work, but it does, as shown by the fact that the alert from the .click() still shows after it got moved.
I've tried event.stopProgation() basically everywhere in the functions, tried using a local variable instead of the global variable currentCard, and have double checked that the classes are changing by inspecting using .html. By my reasoning, the second they change from .unmatched to .matched the original function should stop working. Can anybody help me figure out why it's not?
Final note, the formatting got screwed up a little in the switch to fiddle, please forgive the funkyness. I tried to get rid of as much extra stuff as possible.
Edit: Changed from #matched in my question to .matched
Full code:
HTML
<div class="col-xs-3 col-sm-4 col-md-2">
<h2>Unmatched:</h2>
<div class="container-fluid matchBoxes" id="unmatched">
<div class="namesAndModals">
<div class="nameCard preClick unmatched" id="unmatchedFunctionalityShell">
<h2 class="memberName"></h2>
<div class="nameCardContents">
<button type="button" class="btn checkmark" id="yesBtn" href="#" data-toggle="modal" data-target="#pairModal">
<div class="checkmark_circle"></div>
<div class="checkmark_stem"></div>
<div class="checkmark_kick"></div>
</button>
<input type="text" placeholder="PNM ID#" class="IDnum ansField" autofocus/>
<input type="text" placeholder="Last Name" class="lastName ansField" id="lastName"/>
<input type="text" placeholder="First Name" class="firstName ansField" id="firstName"/>
</div>
</div>
<div class="nameCard preClick unmatched">
<h2 class="memberName">Jane Doe</h2>
</div>
<div class="nameCard preClick unmatched">
<h2 class="memberName">Jane Doe</h2>
</div>
<!-- Pairing Modal -->
<div id="pairModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ready to Pair?</h4>
</div>
<div class="modal-body">
<p id="pairDialog"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="pairButton" data-dismiss="modal">Pair</button>
<button type="button" class="btn btn-default" id="dismissButton" data-dismiss="modal">Never Mind</button>
</div>
</div>
</div>
</div>
</div>
</div>
<h2>Matched:</h2>
<div class="container-fluid matchBoxes" id="matched">
<div class="nameCard preClick matched">
<h2 class="memberName">Jane Doe</h2>
<div class="matchedNameCardContents">
<p class="pnmName">Jaime Doe</p>
</div>
</div>
</div>
CSS
* {
font-family: 'Gill Sans MT', 'Microsoft YaHai UI', sans-serif;
font-weight: 200;
}
#unmatched {
width: auto;
height: 300px;
background-color: rgba(211, 211, 211, .55);
border-radius: 10px;
margin: 10px 0;
overflow-y:scroll;
min-width: 270px;
}
#matched {
width: 110%;
height: 200px;
background-color: rgba(211, 211, 211, .55);
border-radius: 10px;
margin: 10px 0;
overflow-y:scroll;
min-width: 270px;
}
.nameCard {
width: 100%;
height: 70px;
background-color: rgba(255,100,171,.5);
border-radius: 10px;
display: block;
margin: 2px 1px;
overflow:auto;
}
.nameCard.preClick {
height: 30px;
}
.nameCard .nameCardContents {
display:none;
}
.nameCard h2 {
display:inline-block;
font-size: 20px;
font-weight: 500;
padding: 5px 0 3px 10px;
text-align: left;
width: 75%;
float:left;
}
.nameCard .IDnum {
display:inline-block;
margin: 5px 2px 3px 10px;
padding: 3px 0px 3px 2px;
width: 25%;
}
.nameCard .lastName {
display:inline-block;
margin: 5px 2px 3px 2px;
padding: 3px 0px 3px 2px;
width: 30%;
}
.nameCard .firstName {
display:inline-block;
margin: 5px 2px 3px 2px;
padding: 3px 0px 3px 2px;
width: 30%;
}
#unmatchedFunctionalityShell {
display:none;
}
.checkmark {
display:inline-block;
margin:auto;
margin-right:2px;
padding-right:0px;
-ms-transform: rotate(45deg); /* IE 9 */
-webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
transform: rotate(45deg);
}
.checkmark_circle {
position: absolute;
width:22px;
height:22px;
background-color: rgba(46,195,1,.8);
border-radius:11px;
left:0;
top:0;
}
.checkmark_stem {
position: absolute;
width:3px;
height:9px;
background-color:#fff;
left:11px;
top:6px;
}
.checkmark_kick {
position: absolute;
width:3px;
height:3px;
background-color:#fff;
left:8px;
top:12px;
}
#yesBtn{
display:inline-block;
background-color: rgba(46,195,1,0);
width:20px;
height:20px;
border-radius:11px;
}
/* Matched Members */
.matched.nameCard {
background-color: rgba(50, 205, 50, .5);
}
.matched p {
display: inline-block;
text-align: left;
margin-left: 10px;
padding-top: 5px;
}
.matched .btn {
display: inline-block;
background-color: rgba(255,37,37,.7);
padding: 4px;
float:right;
}
/*I had to use important here to get rid of the nameCardContents. Try and remove it later */
#matched .nameCardContents {
display:none !important;
}
#matched .preClick .matchedNameCardContents {
display:none;
}
Javascript
$(document).ready(function(){
$('.unmatched.nameCard').hover(function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
currentCard.off('click').on("click", function(event) {
// alert("hello");
//switches between "active" and "inactive (preClick)" card
$("#unmatched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.nameCardContents');
cardContents.appendTo(currentCard);
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
alert("this shouldn't happen after being moved to #matched");
} else {
cardContents.show();
alert("this shouldn't happen after being moved to #matched");
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.off('click', ".btn").on("click", ".btn", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
$("#pairDialog").text("Are you sure you want to pair " + memberName + " with " + pnmFirstName + " " + pnmLastName + "?");
});
currentCard.off('click', ".ansField").on("click", ".ansField", function(event) {
event.stopPropagation();
});
//Unmatched to Matched
$('#pairModal #pairButton').off('click').on("click", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
currentCard.removeClass('unmatched');
currentCard.addClass('matched');
currentCard.children(".nameCardContents").hide();
currentCard.append("<div class='matchedNameCardContents'><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.addClass('preClick');
currentCard.prependTo("#matched");
$("#lastName").val("");
$("#firstName").val("");
});
//Move from Unmatched to Unavailible
//Remove for one party
$('#discardModal #onePartyButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed for one party</p></div>")
newDiv.appendTo(currentCard);
});
//Remove for one round
$('#discardModal #oneRoundButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed for one round</p></div>")
newDiv.appendTo(currentCard);
});
//Remove for all recruitment
$('#discardModal #allRecruitmentButton').off('click').on("click", function(event) {
currentCard.removeClass('unmatched');
currentCard.addClass('unavailable');
currentCard.prependTo("#unavailable");
var newDiv = $("<div><p>Removed from recruitment</p></div>")
newDiv.appendTo(currentCard);
});
});
});
//Matched Name cards
$(document).ready(function(){
$('.matched.nameCard').off().hover(function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
var pnmName = $(this).children(".pnmName").text();
currentCard.on("click", function(event) {
//switches between "active" and "inactive (preClick)" card
//$("#matched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.matchedNameCardContents');
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
} else {
cardContents.show();
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.on("click", ".btn", function(event) {
$("#unpairButton").text("Are you sure you want to unpair " + memberName + " and " + pnmName + "?");
});
currentCard.on("click", ".ansField", function(event) {
event.stopPropagation();
});
//.unbind() is the best thing to happen to me
//Unmatched to Matched
$('#pairModal #pairButton').unbind('click').on("click", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
currentCard.removeClass('unmatched');
currentCard.addClass('matched');
currentCard.children(".nameCardContents").hide();
var addPNM = $("<div class='matchedNameCardContents'><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.append("<div><p class='pnmName'>" + pnmFirstName + " " + pnmLastName + "</p><button type='button' class='btn btn-default' data-toggle='modal' data-target='#unpairModal'>Unpair</button></div>");
currentCard.prependTo("#matched");
});
});
});
I figured it out! I looked into event delegation based on the comments and changed everything to take that into account. Here's a preview of what my new functions look like:
$(document).ready(function(){
$('#unmatched').off().on("mouseover", ".unmatched.nameCard", function() {
var currentCard = $(this);
var memberName = $(this).children(".memberName").text();
currentCard.off('click').on("click", function() {
//switches between "active" and "inactive (preClick)" card
$("#unmatched .nameCard").addClass('nameCard preClick');
currentCard.toggleClass('nameCard');
currentCard.toggleClass('nameCard preClick');
var cardContents = $('.nameCardContents');
cardContents.appendTo(currentCard);
if (currentCard.is(".nameCard.preClick") ) {
cardContents.hide();
} else {
cardContents.show();
}
});
//stops card from closing if you click on buttons/input and carries out button events
currentCard.off('click', ".btn").on("click", ".btn", function(event) {
var pnmLastName = $("#lastName").val();
var pnmFirstName = $('#firstName').val();
$("#pairDialog").text("Are you sure you want to pair " + memberName + " with " + pnmFirstName + " " + pnmLastName + "?");
$("#removeMember").text("How long do you want to remove " + memberName + " from recruitment?");
});
});
});

Typeahead.js with a large database gives Uncaught TypeError: $(...).typeahead is not a function

In my project typeahead.js gives error:
Uncaught TypeError: $(...).typeahead is not a function
PHP
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="public/js/typeahead.js"></script>
<script>
jQuery(document).ready(function() {
var offset = 250;
var duration = 300;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
});
$('input.search').typeahead({
name: 'companyName',
remote:'ser_sug.php?key=%QUERY',
limit : 10
});
});
</script>
<style type="text/css">
.bs-example{
font-family: sans-serif;
position: relative;
margin: 50px;
}
.typeahead, .tt-query, .tt-hint {
border: 2px solid #CCCCCC;
border-radius: 8px;
font-size: 24px;
height: 30px;
line-height: 30px;
outline: medium none;
padding: 8px 12px;
width: 396px;
}
.typeahead {
background-color: #FFFFFF;
}
.typeahead:focus {
border: 2px solid #0097CF;
}
.tt-query {
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}
.tt-hint {
color: #999999;
}
.tt-dropdown-menu {
background-color: #FFFFFF;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 8px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
margin-top: 12px;
padding: 8px 0;
width: 422px;
}
.tt-suggestion {
font-size: 24px;
line-height: 24px;
padding: 3px 20px;
}
.tt-suggestion.tt-is-under-cursor {
background-color: #0097CF;
color: #FFFFFF;
}
.tt-suggestion p {
margin: 0;
}
</style>
</head>
<div class="col-lg-3 cd-row">
<div class="heading" style="padding:0;margin:0;border:none;">
<h3 class="advSearchHeading" style="color:#fff;">Search Ceramic</h3>
</div>
<form role="form" class="advSearchForm" action="<?php echo SLASHES;?>search/" method="get" style="overflow:hidden;">
<div class="form-group">
<input name="companyName" type="text" value="" placeholder="Company name" class="search" id="searchid">
</div>
<div class="form-group">
<select name="category" class="form-control">
<option selected value="">Select Category</option>
<?php
$categoryResult = mysql_query("SELECT * FROM `category` where flag = 1 order by `sequence`");
while($categoryRow = mysql_fetch_assoc($categoryResult))
echo '<option value="'.$categoryRow['cid'].'">'.$categoryRow['cat_name'].'</option>';
?>
</select>
</div>
<div class="form-group">
<select name="productSize" id="productSize" class="form-control">
<option selected value="">Select Size(CentiMeter)</option>
<?php
$sizeResult = mysql_query("SELECT * FROM sizes ORDER BY sequence");
while($sizeRow = mysql_fetch_assoc($sizeResult))
echo '<option value="'.$sizeRow['id'].'">'.$sizeRow['inch'].'</option>';
?>
</select>
</div>
<div class="form-group">
<input name="location" type="text" value="" placeholder="Addr / city / state / country / pin" class="form-control">
</div>
<button type="submit" class="btn btn-default pull-right" style="font-weight: bold; font-size: 12px;">Search</button>
</form>
</div>
</div>
sur_sug.php
<?php
mysql_connect('localhost','username','pass');
mysql_select_db("database");
$key=$_GET['key'];
$array = array();
$query=mysql_query("select com_name from company_details where com_name LIKE '%{$key}%'");
while($row=mysql_fetch_assoc($query))
{
$array[] = $row['com_name'];
}
echo json_encode($array);
?>
I have tried to put my $(document).ready in a different place, but it's giving the following error:
Please help me.
It have nothing to do with the amount of data but the fact that public/js/typeahead.js is not found
Change it to /js/typeahead.js and it will properly work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/js/typeahead.js"></script>
<script>
// ...
Actually it is not a problem due to large database.Your script file is not fetching in line
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="public/js/typeahead.js"></script>
<script>
jQuery(document).ready(function() {
var offset = 250;
var duration = 300;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
});
$('input.search').typeahead({
name: 'companyName',
remote:'ser_sug.php?key=%QUERY',
limit : 10
});
});
</script>
To clear that issue you have to give exact path for this script file typeahead.js or replace that script line with
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/3.1.1/bootstrap3-typeahead.js"></script>
<script>
jQuery(document).ready(function() {
var offset = 250;
var duration = 300;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
});
$('input.search').typeahead({
name: 'companyName',
remote:'ser_sug.php?key=%QUERY',
limit : 10
});
});
</script>
Bootstrap Typeahead is a Bootstrap plugin. For this to work it's essential that bootstrap is loaded first. Also make sure Bootstrap and jQuery is loaded only once at the top of any dependent code.
Any new instances of Bootstrap or jQuery after loading plugin instance will override the plugin methods.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/3.1.1/bootstrap3-typeahead.js"></script>

JavaScript success message after form submit/page re-load

I'm looking for a way to display a simple JS message/pop up when my form has been successfully submitted.
I tried doing this as an 'alert' but it stopped the 'action' from happening (page reloading) and just displayed the message instead.
If I could do this as a js alert after the action has happened and the page has reloaded this would be great but I'm open to suggestions...
Regards,
Marc
function validate() // Required Fields Validation
{
if (document.myForm.Name.value == "") {
alert("Please provide your name");
document.myForm.Name.focus();
return false;
}
if (document.myForm.Company.value == "") {
alert("Please provide your Company name");
document.myForm.Company.focus();
return false;
}
if (document.myForm.Email.value == "") {
alert("Please provide your Email address");
document.myForm.Email.focus();
return false;
}
if (document.myForm.Message.value == "") {
alert("Leave us a message");
document.myForm.Message.focus();
return false;
}
return (true);
}
function validateEmail() // Correct Email Format Validation
{
var emailID = document.myForm.Email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter a valid Email address")
document.myForm.Email.focus();
return false;
}
return (true);
}
function nameLength() { // Max Character Validation
x = document.myForm
input = x.Name.value
if (input.length > 40) {
alert("The Name field cannot contain more than 40 characters")
return false
} else {
return true
}
}
function companyLength() {
x = document.myForm
input = x.Company.value
if (input.length > 50) {
alert("The Company field cannot contain more than 50 characters")
return false
} else {
return true
}
}
function emailLength() {
x = document.myForm
input = x.Email.value
if (input.length > 50) {
alert("The Email field cannot contain more than 50 characters")
return false
} else {
return true
}
}
function messageLength() {
x = document.myForm
input = x.Message.value
if (input.length > 300) {
alert("The Message field cannot contain more than 300 characters")
return false
} else {
return true
}
}
#contact-area {
width: 500px;
max-height: 200px;
margin-top: 0px;
float: left;
}
#contact-area input,
#contact-area textarea {
padding: 3px;
width: 520px;
font-family: 'Lato', sans-serif;
font-size: 14px;
margin: 0px 0px 0px 0px;
border: 1px solid #ccc;
}
#contact-area textarea {
height: 90px;
}
#contact-area textarea:focus,
#contact-area input:focus {
border: 1px solid #ffc423;
}
#contact-area input.submit-button {
width: 100px;
float: left;
background-color: #ffc423;
color: black;
margin-top: 13px;
cursor: pointer;
}
#contact-area input.submit-button:hover {
background-color: #002b51;
color: white;
}
label {
float: left;
text-align: left;
margin-right: 15px;
width: 100px;
padding-top: 10px;
padding-bottom: 5px;
font-size: 15px;
color: #ffc423;
font-weight: 700;
}
textarea {
resize: none;
}
<div id="contact-area">
<form method="post" action="contactengine.php" name="myForm" onsubmit="return !!(validate() & validateEmail() & nameLength() & companyLength() & emailLength() & messageLength())">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name">
<label for="Company">Company:</label>
<input type="text" name="Company" id="Company">
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email">
<label for="Message">Message:</label>
<textarea name="Message" rows="20" cols="20" id="Message" title="Your message | max 300 characters"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button">
</form>
<div style="clear: both;"></div>
</div>
you can set a value to a querystring param and check this on your page to alert success:
Redirect function update:
if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=contact.html\?success=true">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; }
Your page script:
you can have an on page load function to run the below:
var success = How can I get query string values in JavaScript? ;
if(success != ""){
alert(success); // javascript alert
}

Categories