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();
}
}
});
Related
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;
}
}
On line 24 where I test if the test2[1] == "invalid" never works it always goes to the else and takes me to the next page. I think test2[1] just isn't a string but I don't know what else it would be please help
function login() {
var email = document.getElementById("email").value;
var passW = document.getElementById("password").value;
if (email == "" || passW == "") {
alert("Please enter a valid email or password.");
} else {
var myXMLRequest = new XMLHttpRequest();
myXMLRequest.onload = openWorkout;
var url = "assignment10.php?em=" + email + "&pass=" + passW;
myXMLRequest.open("POST", url, true);
myXMLRequest.send();
}
}
function openWorkout() {
var invalid = "invalid";
var step = this.responseText;
var test = step.split(",");
var test2 = test[0].split(":");
console.log(step);
console.log(test);
console.log(test2[1]);
if (test2[1] == "invalid") {
alert("The email or password you entered is invalid. Please try again.");
} else {
window.location = "#workoutPage";
}
}
<?php
//TASK 1: MAKE A CONNECTION TO THE DATABASE, DISPLAY ERROR FOR FAILED CONNECTIONS
//(FOR GODADDY) NOTE: $mysqli = new mysqli("127.0.0.1", "username", "password", "database", 3306);
$mysqli = new mysqli("localhost", "User", "1234", "ass10");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//CHECK IF EMAIL AND ENTERED PASSWORD VALID (LOGIN PAGE [first part of open workout checks login password])
$entEmail = $_GET['em'];
$entPassword = $_GET['pass'];
$sql = "SELECT * FROM membership_table WHERE Email = $entEmail, Password = $entPassword";
$result = $mysqli->query($sql);
if($result->num_rows == 0) {
$data = "invalid";
} else {
$data = "valid";
}
//Pass to JSON
$json = array(
"data" => $data,
"Email" => $entEmail,
"Password" => $entPassword
);
header("Contenttype:Application/json");
print(json_encode($json));
?>
here are the console.log outputs on lines 21 - 23
assignment10.js:21 {"data":"invalid","Email":"q","Password":"1"}
assignment10.js:22 (3) ["{"data":"invalid"", ""Email":"q"", ""Password":"1"}"]
assignment10.js:23 "invalid"
You're returning JSON from your PHP, so process it as that using JSON.parse, rather than trying to split the string apart:
var response = JSON.parse(this.responseText);
var test = response.data;
if (test == 'invalid') {
...
Note the issue with your current code is that test2[1] is literally "invalid", including the double quotes, so for your test to work you'd need to use
if (test2[1] == '"invalid"') {
Here's a snippet to demonstrate the code using the output of console.log(step) from your question:
const responseText = '{"data":"invalid","Email":"q","Password":"1"}';
var response = JSON.parse(responseText);
var test = response.data;
if (test == 'invalid') {
console.log('Invalid!');
} else {
console.log('Valid!');
}
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 trying to set some global vars but a little stuck on how to then fire the custom function which does a AJAX request with the data, I collect email in one function and other events and also firstname and lastname but I'm now stuck.
I've not called fireCheckoutAC anywhere as this is what I'm stuck with. I'm new to jQuery and JS but think I've got as far as I can.
// 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();
}
}
});
Managed to work it out, here is the solution for anyone else wanting to know... just had to call the ajax function which handled the global vars
/* 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";
}