Created
June 21, 2020 22:45
-
-
Save michelarteta/cfc2d33b7bda7860ee792a5d9acc2684 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Try to login, check the login credentials, and then redirect if required. | |
*/ | |
login(email, password).done(function (html) { | |
if (html.indexOf('Invalid login credentials') !== -1) { | |
// invalid password - show a message to the user | |
} else { | |
// All good! Let's redirect if required | |
var checkoutUrl = getCheckoutUrl(); | |
if (checkoutUrl) { | |
window.location.href = checkoutUrl; | |
} else { | |
// don't need to redirect, do what you like! | |
} | |
} | |
}); | |
/* | |
* Or if you're registering a user: | |
*/ | |
register(email, password, firstName, lastName).done(function (html) { | |
// logic for registration errors | |
if (html.indexOf('email is invalid') !== -1) { | |
} else if html.indexOf('email can't be blank') !== -1) { | |
} else if (html.indexOf('password can't be blank.') !== -1) { | |
} | |
}); | |
/* | |
* Log the customer in with their email and password. | |
*/ | |
function login(email, password) { | |
var data = { | |
'customer[email]': email, | |
'customer[password]': password, | |
form_type: 'customer_login', | |
utf8: '✓' | |
}; | |
var promise = $.ajax({ | |
url: '/account/login', | |
method: 'post', | |
data: data, | |
dataType: 'html', | |
async: true | |
}); | |
return promise; | |
} | |
/* | |
* Log the customer in with their email and password. | |
*/ | |
function register(email, password, firstName, lastName) { | |
var data = { | |
'customer[email]': email, | |
'customer[password]': password, | |
'customer[first_name]': firstName, | |
'customer[last_name]': lastName, | |
form_type: 'create_customer', | |
utf8: '✓' | |
}; | |
var promise = $.ajax({ | |
url: '/account', | |
method: 'post', | |
data: data, | |
dataType: 'html', | |
async: true | |
}); | |
return promise; | |
} | |
/* | |
* Get the `checkout_url` from the URL query parameter, if it exists. | |
* (It only ever exists on the /account/login page) | |
*/ | |
function getCheckoutUrl() { | |
function getParameterByName(name) { | |
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); | |
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), | |
results = regex.exec(location.search); | |
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); | |
} | |
return getParameterByName('checkout_url'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are a hero. I don't understand why this is not in official docs anywhere.