I want the score of the game played stored in the usrObj next to topScore in the local storage. However, it only stores the score next to the user's name.
js code from index.html
<script>
loadRankingTable();
window.onload = ()=> {
//Check login
if(sessionStorage.loggedInUser !== undefined){
window.localStorage.setItem(sessionStorage.loggedInUser, highscore);
document.getElementById("Greeting").innerHTML = sessionStorage.loggedInUser;
}
}
</script>
prac.js
function register(){
let password1 = document.getElementById("PasswordInput").value
let password2 = document.getElementById("PasswordInputConfirm").value
let username = document.getElementById("Username").value
let name = document.getElementById("NameInput").value;
let password = document.getElementById("PasswordInput").value;
let usrObj = {
username: username,
password: password,
topScore: 0
}
if (password1 == password2){
localStorage[name] = JSON.stringify(usrObj);
document.getElementById("FeedbackPara").innerHTML= "";
}
else{
document.getElementById("FeedbackPara").innerHTML= "Passwords don't match.";
}
}
so basically instead of the local storage storing data like this: "user, 200", i want it to be like this: "username: username, password: password, topScore: 200 "
Retrieve the current value of the local storage as JSON, update the score, and then save it again.
loadRankingTable();
window.onload = () => {
//Check login
if (sessionStorage.loggedInUser !== undefined) {
let oldData = localStorage.getItem(sessionStorage.loggedInUser);
if (oldData) {
oldData = JSON.parse(oldData);
oldData.topScore = highscore;
localStorage.setItem(sessionStorage.loggedInUser, JSON.stringify(oldData);
}
document.getElementById("Greeting").innerHTML = sessionStorage.loggedInUser;
}
}
How do I trim any dots before #mail.com? I am doing jQuery email validation and need to get rid of all the dots from username.
$('document').ready(function(){
var email_state = false;
$('#email').on('keyup', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
return;
}
$.ajax({
url: 'index.php',
type: 'post',
data: {
'email_check' : 1,
'email' : email,
},
success: function(response){.....
Use .replace(/\./g, "") for the part before #
function removeDots(email){
var email_s = email.split("#");
return email_s[0].replace(/\./g, "")+"#"+email_s[1];
}
var email = "some.emai.l#mail.com";
console.log(removeDots(email));
In your code's context
function removeDots(email) {
var email_s = email.split("#");
return email_s[0].replace(/\./g, "") + "#" + email_s[1];
}
var email = "some.emai.l#mail.com";
console.log(removeDots(email));
$('document').ready(function() {
var email_state = false;
$('#email').on('keyup', function() {
var email = $('#email').val();
email = removeDots(email); // call function here to remove dots
if (email == '') {
email_state = false;
return;
}
// Rest of your code
});
// Rest of your code
});
Regex: \.(?![^#]+$)
One line code: email.replace(/\.(?![^#]+$)/gy, '')
function myFunction() {
console.clear()
var s = document.getElementById("input").value;
console.log(s.replace(/\.(?![^#]+$)/g, ''));
}
<form action="javascript:myFunction()">
<input id="input" type="text" value="bla.bla.bla.#mail.net.com"><br><br>
<input type="submit" value="Submit">
</form>
First get the username of email using String.prototype.split() then remove all the . using .replace() and /\./g. Below is an example:
var email = "abc.d.e#mail.com";
var splitted = email.split("#");
console.log(splitted[0].replace(/\./g,"") + "#" + splitted[1]);
For updated question:
var email_state = false;
$('#email').on('keyup', function(){
var email = $('#email').val();
if (email == '') {
email_state = false;
var splitted = email.split("#");
email = splitted[0].replace(/\./g,"") + "#" + splitted[1];
}
}
I'm having a few problems with this, so I'll try to keep it simple. What's happening in the first script is a new Google doc file gets made from a copy of a "master" doc I've defined, which gets its data populated from Form submissions, and that new copy is ultimately moved to a Folder on my Drive. The second script is supposed to send that copied file to the Google Cloud Print. The first script works perfect; I have it triggered on a form submit. The second script works by itself, but only when I explicitly define the master doc ID in the "content" section. Because with each Form submission a new doc gets made, I was having trouble integrating the new doc's ID with the second script. Right now, I tried pulling from the var file, but that's not working. I might have a syntax issue.
My other problem is I need to merge my second script with the first, in a way that gets triggered on the same Form Submit and probably execute after the PDF creation and Email send, but before it gets moved to the folder.
Any help or advice would be greatly appreciated.
And I've removed some of my IDs and sensitive information where you only see double quotes.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var image_services = e.values[9];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
**
Update 8/14 with Sandy Good's suggestion:
**
I've attempted to do what you suggested, but now it's not creating the doc or sending to the cloud print. Any thoughts?
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var image_services = e.values[9];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var values = e.values;
createNewDoc(values);
printGoogleDocument(file, docName);
}
Not sure if that is what you are after, but the easiest way to execute functions consecutively is to pass a callback function as an argument to your function.
Here's the list of simple functions assigned to variables.
var addFive = function(number, callback){
number += 5;
if (callback) {
return callback(number);
}
return number;
}
var multiplyByFive = function(number, callback){
number *= 5;
if (callback) {
return callback(number);
}
return number;
}
var subtractFive = function(number, callback){
number -= 5;
if (callback) {
return callback(number);
}
return number;
}
You can then just chain call them like this.
function test() {
var result = addFive(7, function(number) {
return multiplyByFive(number, function(number){
return subtractFive(number);
});
});
Logger.log(result); //logs (7 + 5) * 5 - 5 = 55
}
Of course, if your functions only perform operations like creating files and don't return values, feel free to omit the 'return' statement.
I have more questions in regards to this project, but I think this specific question has been answered, so here's the final code for future reference.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var ship_to = values[11];
var address = values[12];
var order_count = values[7];
var program = values[2];
var workspace = values[3];
var offer = values[4];
var sort_1 = values[5];
var sort_2 = values[6];
var image_services = values[9];
var print_services = values[10];
var priority = values[13];
var notes = values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
createNewDoc(values);
printGoogleDocument(file, docName);
}
im new to js/ jquery so think ive done ok to get this far however ive noticed an issue with my code and think i need to somehow merge it together.
If i enter email, it updates in database, however as soon as i do firstname or lastname it updates those but then removes the email...
here is the JS so far:
// function to check email field, validate and save to ac for this customer session
function checkIt(field) {
field = $(field);
var email = field.val();
var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
var emailInputId = field.attr('id');
if ($("." + emailInputId + "_error_message").length > 0) {
$("." + emailInputId + "_error_message").remove();
}
//console.log($(emailInputId+"_error_message"));
if (validEmail(email)) {
//alert('valid email');
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'email': email
},
caching: true
});
field.removeClass('cm-failed-field');
field.prev().removeClass('cm-failed-label');
field.next("span").remove();
} else {
field.addClass('cm-failed-field');
field.prev().addClass('cm-failed-label');
field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
}
}
// lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
var field = $('#onestepcheckout .ty-billing-email input')[0];
if ($(field).length > 0) {
if (field.value) {
checkIt(field);
}
}
// check email thats inputted and save to ac session for this customer, or if email changed to update
$('#onestepcheckout .ty-billing-email input').blur(function() {
checkIt(this);
});
// if first name entered lets grab it and add to the ac session for the customer
var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
$(firstname_sel+','+lastname_sel).blur(function() {
var firstname = $(firstname_sel).val();
var lastname = $(lastname_sel).val();
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'firstname': firstname,
'lastname': lastname
},
caching: true
});
});
// lets grab the first name and last name if already in input
var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
if (firstname_sel_pre.value || lastname_sel_pre.value) {
var firstname_pre = $(firstname_sel_pre).val();
var lastname_pre = $(firstname_sel_pre).val();
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'firstname': firstname_pre,
'lastname': lastname_pre
},
caching: true
});
}
}
PHP
if ($mode == 'email') {
//die('post was recieved from js to this controller! yippie!!');
//print_r($_POST['email']);
//die($_POST['email']);
/**************Start: Abandoned Carts *********************/
$_SESSION['cart']['user_data']['email'] = $_POST['email'];
$cartContents=mysql_escape_string(serialize($_SESSION['cart']['products']));
$shippingCost=$_SESSION['cart']['shipping_cost'];
$tax=$_SESSION['cart']['tax_summary']['total'];
$orderTotal=$_SESSION['cart']['total'];
$userFirstName=$_POST['firstname'];
$userLastName=$_POST['lastname'];
$userEmail=$_POST['email'];
$userId=$_SESSION['settings']['cu_id']['value'];
$userExpiry=$_SESSION['settings']['cu_id']['expiry'];
$date=date('Y-m-d h:i:s');
$userExist=db_get_fields("SELECT user_id FROM cscart_abandoned_cart WHERE user_id = '".$userId."'");
if($userExist) {
db_query("UPDATE cscart_abandoned_cart SET first_name='".$userFirstName."', last_name='".$userLastName."', email='".$userEmail."', shipping='".$shippingCost."',tax='".$tax."',order_total='".$orderTotal."',cart='".$cartContents."',last_updated='".$date."',status='0' WHERE user_id='".$userId."'");
} else {
db_query("INSERT INTO cscart_abandoned_cart (first_name,last_name,email,cart,user_id,expiry,last_updated,shipping,tax,order_total,status)values('".$userFirstName."','".$userLastName."','".$userEmail."','".$cartContents."','".$userId."','".$userExpiry."','".$date."','".$shippingCost."','".$tax."','".$orderTotal."','0')");
}
}
UPDATE
I have had a read about setting global vars but got as far as i can and a little stuck, i put the ajax request in a new function (not sure if that was right) or if i done correctly but a little lost now on how i should call the ajax function?
// set global variables
var checkoutEmail = "";
var checkoutFirstName = "";
var checkoutLastName = "";
$(document).ready(function() {
function fireCheckoutAC(checkoutEmail, checkoutFirstName, checkoutLastName) {
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'email': checkoutEmail,
'firstname': checkoutFirstName,
'lastname': checkoutLastName
},
caching: true
});
}
// function to check email field, validate and save to ac for this customer session
function checkIt(field) {
field = $(field);
var email = field.val();
var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
var emailInputId = field.attr('id');
if ($("." + emailInputId + "_error_message").length > 0) {
$("." + emailInputId + "_error_message").remove();
}
//console.log($(emailInputId+"_error_message"));
if (validEmail(email)) {
//alert('valid email');
checkoutEmail = email;
field.removeClass('cm-failed-field');
field.prev().removeClass('cm-failed-label');
field.next("span").remove();
} else {
field.addClass('cm-failed-field');
field.prev().addClass('cm-failed-label');
field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
}
}
// lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
var field = $('#onestepcheckout .ty-billing-email input')[0];
if ($(field).length > 0) {
if (field.value) {
checkIt(field);
}
}
// check email thats inputted and save to ac session for this customer, or if email changed to update
$('#onestepcheckout .ty-billing-email input').blur(function() {
checkIt(this);
});
// if first name entered lets grab it and add to the ac session for the customer
var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
$(firstname_sel+','+lastname_sel).blur(function() {
checkoutFirstName = $(firstname_sel).val();
checkoutLastName = $(lastname_sel).val();
});
// lets grab the first name and last name if already in input
var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
if (firstname_sel_pre.value || lastname_sel_pre.value) {
checkoutFirstName = $(firstname_sel_pre).val();
checkoutLastName = $(firstname_sel_pre).val();
}
}
});
I worked out the solution, here it is:
/* grab completed email when enetred into checkout and add to abandoned cart for that session */
function validEmail(v) {
var r = 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 (v.match(r) == null) ? false : true;
}
// set global variables
var checkoutEmail = "";
var checkoutFirstName = "";
var checkoutLastName = "";
$(document).ready(function() {
function fireCheckoutAC() {
$.ceAjax('request', fn_url('ac.email'), {
method: 'post',
data: {
'email': checkoutEmail,
'firstname': checkoutFirstName,
'lastname': checkoutLastName
},
caching: true
});
}
// function to check email field, validate and save to ac for this customer session
function checkIt(field) {
field = $(field);
var email = field.val();
var emailError = "<p>The email address in the <b>E-mail</b> field is invalid.</p>";
var emailInputId = field.attr('id');
if ($("." + emailInputId + "_error_message").length > 0) {
$("." + emailInputId + "_error_message").remove();
}
//console.log($(emailInputId+"_error_message"));
if (validEmail(email)) {
//alert('valid email');
checkoutEmail = email;
fireCheckoutAC();
field.removeClass('cm-failed-field');
field.prev().removeClass('cm-failed-label');
field.next("span").remove();
} else {
field.addClass('cm-failed-field');
field.prev().addClass('cm-failed-label');
field.after("<span class='" + emailInputId + "_error_message help-inline' ><p>" + emailError + "</p></span>");
}
}
// lets check if the email input was already populated, such as browser auto fill etc.. if so use that and save
var field = $('#onestepcheckout .ty-billing-email input')[0];
if ($(field).length > 0) {
if (field.value) {
checkIt(field);
}
}
// check email thats inputted and save to ac session for this customer, or if email changed to update
$('#onestepcheckout .ty-billing-email input').blur(function() {
checkIt(this);
});
// if first name entered lets grab it and add to the ac session for the customer
var firstname_sel = '#onestepcheckout .ty-billing-first-name input';
var lastname_sel = '#onestepcheckout .ty-billing-last-name input';
$(firstname_sel+','+lastname_sel).blur(function() {
checkoutFirstName = $(firstname_sel).val();
checkoutLastName = $(lastname_sel).val();
fireCheckoutAC();
});
// lets grab the first name and last name if already in input
var firstname_sel_pre = $('#onestepcheckout .ty-billing-first-name input')[0];
var lastname_sel_pre = $('#onestepcheckout .ty-billing-last-name input')[0];
if ($(firstname_sel_pre).length > 0 || $(lastname_sel_pre).length > 0) {
if (firstname_sel_pre.value || lastname_sel_pre.value) {
checkoutFirstName = $(firstname_sel_pre).val();
checkoutLastName = $(firstname_sel_pre).val();
fireCheckoutAC();
}
}
});
I m trying to save popup windows data in to database.but its throw error when i m trying pass data in queryString.Its just write "error".I dont know why its not call the update_clientstatus.php
Javscript :
function SaveNotes()
{
var notecontent = $("#txtPopNotes").val();
lookup(notecontent, globalNoteId);
overlay.appendTo(document.body).remove();
return false;
}
function lookup(inputstr, eleid) {
var inputString = inputstr;
// var row = parseFloat(eleId.substring(eleId.indexOf('_') + 1))+1;
var noteId = '#noteContent_' + eleid;
var editLinkId = '#editlink_' + eleid;
var saveLinkId = '#savelink_' + eleid;
var cancelLinkId = '#cancellink_' + eleid;
var txtBoxId = '#txt_' + eleid;
// var eleId = ele.id;
$.post("update_clientstatus.php", {queryString: ""+inputString+"", id: ""+eleid+"" }, function(data){
if(data=="success") {
alert("Status updated successfully");
$('.popup').hide();
var noteId = '#noteContent_' + globalNoteId;
$(noteId).html(inputstr);
$('.message').html('Status Updated successfully');
}
else
{
**document.write('error');**
}
});
} // lookup
PHP code(update_clientstatus.php)
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
}
try this
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
if ($query ) {
echo "success";
} else {
echo "error";
}
} else {
echo "error";
}