Django: Best way to give Stripe ACH deposit verification Error - javascript

I'm working on Stripe ACH verification where I have the user input two numbers corresponding to deposits in their bank account. What's the best way to error out the html field when they enter a value that isn't a integer between 1 and 99. Should this be done javascript side (jquery?) or in my view. My gut tells me that it needs to be done in the view, but I don't know how to relay an error message back to the user. Should I create a form for this? I wouldn't think so since I'm not saving things to the database.
Thoughts?
My View in Django
def ach_payment_verify_updateview(request):
request.stripe_id = request._post['token']
print('hi')
try:
if not isinstance(request._post['deposit_1'], int):
### some kind of error message here
print(request._post['deposit_1'])
print(request._post['deposit_2'])
My current javascript code.
document.querySelector('form.ach-payment-verify-form').addEventListener('submit', function(e) {
e.preventDefault();
var nextUrl = paymentForm.attr('data-next-url');
var deposit_1 = document.getElementById('deposit-1').value;
var deposit_2 = document.getElementById('deposit-2').value;
stripeDepositHandler(nextUrl, deposit_1, deposit_2)
});
function stripeDepositHandler(nextUrl, deposit_1, deposit_2){
var paymentMethodEndpoint = '/billing/ach-payment-verify/create/'
var data = {
'token': 'ba_1CWoJSFAasdfafsdReMae',
'deposit_1':deposit_1,
'deposit_2':deposit_2,
}
$.ajax({
data: data,
url: paymentMethodEndpoint,
method: "POST",
success: function(data){
var successMsg = data.message || "Success! Your account has been verified."
$("form.ach-payment-verify-form")[0].reset();
if (nextUrl){
successMsg = successMsg + "<br/><br/><i class='fa fa-spin fa-spinner'></i> Redirecting..." //<i class> - 'font awesome'
}
if ($.alert){ // if alert message is installed
$.alert(successMsg)
} else {
alert("")
}
redirectToNext(nextUrl, 1500)
},
error: function(error){
console.log(error)
}
})
}

Please try this validation in your code :
document.querySelector('form.ach-payment-verify-form').addEventListener('submit', function(e) {
e.preventDefault();
var nextUrl = paymentForm.attr('data-next-url');
var deposit_1 = document.getElementById('deposit-1').value;
var deposit_2 = document.getElementById('deposit-2').value;
if (Number.isInteger(deposit_1) && Number.isInteger(deposit_2)) {
stripeDepositHandler(nextUrl, deposit_1, deposit_2)
}
else {
console.log("Please enter valide number. Thank You !")
}

Related

Jetbrains PHPstorm 2019.3.3 warns me I have a duplicated jQuery selector

How can I fix this warning about the duplication? Is there any better way to do this process for the interaction on the database and front end forms? Also are there any additional improvements that I could add to this work to make it flow better?
$(document).ready(function() {
function authenticate(mode) {
if (mode === "Login") {
let User_email = $("input#log_User_email").val();
let Password = $("input#log_Password").val();
let error_collector = "";
let $log_response = $("div.box_response p#log_response");
$log_response.html("");
if (User_email.length <= 0)
error_collector += "Please enter a user email.";
if (Password.length <= 0)
error_collector += "Please enter a user password.";
if (error_collector !== "") {
$log_response.html(error_collector);
} else {
$log_response.html("Logging in");
$.ajax({
method: "POST",
url: "Resources/PHP/Processes/UserLogin.php",
data: {
User_email: User_email,
Password: Password
},
success: function(response) {
if (response === "Success") {
window.location = "details.php";
} else {
$log_response.html(response);
$("input#log_Password").val("");
}
}
});
}
}
How can fix this warning error for the duplication
Hopefully PHPstorm told you which one! In this case the selector you've duplicated is $("input#log_Password")
let Password = $("input#log_Password").val();
...
$("input#log_Password").val("");
You can remove the duplication by saving the value of the selector in the first instance at the point you read the password value, then reusing it later when you want to set the value i.e.
const $Password = $("input#log_Password");
let Password = $Password.val();
...
$Password.val("");

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

Painfully slow ajax calls using jQuery

I'm using knockout in my application to register/login from a form but the wait times on ajax calls are painfully slow first time 'round (guessing it's caching afterwards as it's really quick second time 'round) - around fifteen seconds to login when I upload the site online, and when I wrap it up as an iOS app (HTML5 application) it takes over SIXTY seconds to complete login. Why could this be happening? Have I missed something? Is it more likely to be server-side? Hopefully I can give enough info but unfortunately I'm new to this. I'll add the Login code below:
$(document).ready(function(){
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
var Domain = "http://example.com";
//Declare User observables which will be bind with UI
self.UserId = ko.observable();
self.Name = ko.observable();
self.Email = ko.observable();
self.Occupation = ko.observable();
self.Country = ko.observable();
self.RegistrationNumber = ko.observable();
//Create User object
var User = {
UserId: self.UserId,
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
};
//Assign knockout observables to User/s objects
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//onload set status of user
UserStatus();
//Login handler
self.login = function () {
try {
if (User.Email() != "" && User.RegistrationNumber() != "") {
//try logging in
Login();
} else {
viewModel.UserId("Please login with the correct email and registration number.");
}
}
catch (err) {
viewModel.UserId("There was an error, please try again.");
}
};
//Login
function Login() {
$.ajax({
url: Domain + '/User/Login',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Email":"' + User.Email() + '","RegistrationNumber":"' + User.RegistrationNumber() + '"}',
beforeSend: function () {
// setting a timeout
$('.splash').show();
},
success: function (data) {
$('.splash').hide();
if (data != 0) {
SetUserVars(data.UserId, data.Name, data.Email, data.Occupation, data.Country, data.RegistrationNumber);
viewModel.UserId(ActionToTake());
}
else {
viewModel.UserId("The supplied credentials are invalid, please try again.");
}
},
complete: function () {
//$('.splash').hide();
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
viewModel.UserId("There was an error, please try again.");
});
}
function UserStatus() {
if (localStorage.getItem("UserId") === null) {
//not logged in
$("a.menu-status").text("Login").attr("href", "index.html#login-screen");
}
if (localStorage.getItem("UserId") != null) {
//logged in
$("a.menu-status").text("Logout").attr("href", "index.html#login-screen");
}
//allow user to logout and reset all user storage
$("a.menu-status").click(function () {
//show logged off status
$("a.menu-status").text("Login");
alert('You have logged off, please login if you wish to continue.');
self.reset();
//redirect
window.location.replace("index.html#login-screen");
location.reload();
viewModel.UserId("You have logged off.");
ResetUserLocalStorage();
});
}
Id be inclined to agree with the comments that the issue lies with the server side and not the client side.
The steps id take initially would be to use something like postman https://www.getpostman.com/ and hit the API through that, verify that its the slow part.
If that shows the issue then can you get yourself in a debug situation with the code thats running on the server? Then step through the code and try to pin point exactly whats happening and where its slowing down.

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

Page Refresh Only After Page Is Validated

Hi I wonder whether someone may be able to help me please.
I've put together this page which has working 'client' and 'server' side validation.
What I'm now trying to do is add a page refresh and 'scroll to top', once the page has passed validation.
To the script used in the first link I've added the following code to try and invoke this functionality:
setTimeout(function() {
$('body').fadeOut(400, function() {
location.reload();
setTimeout(function() {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
The problem I'm having, is that irrespective of whether the the form passes validation, the page refreshes as can be seen in this page. So the full JavaScript code looks like this:
Post Update - Through working with #rahul, I've now have a working solution as below. NB I only needed to change the JavaScript code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#saverecordresponse');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is a cut down version (I've deleted most of the validation rules for preview purposes) the PHP code which works in conjunction with the JavaScript and saves the record to a MySQL database.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
if(empty($locationname)){
$status = "error";
$message = "You need to enter a name for this location!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I must admit, I'm not sure where the problem lies, but I'm the first to admit I'm a little new to JavaScript and jQuery.
I just wondered whether someone may be able to look at this please and let me know where I'm going wrong, or even perhaps suggest a better alternative to make the page refresh once the form passes validation.
you can easily get it done using return false
check if validation not passed return false
if(Yourvalidation!=true)
{
return false;
}
after this section
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
check value of klass like this
responseMsg.fadeOut(200, function () {
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200, function () {
//set timeout to hide response message
setTimeout(function () {
responseMsg.fadeOut(200, function () {
$(this).removeClass(klass);
form.data('formstatus', 'idle');
});
}, 3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
else
{
return false; //use return false in else condition
}
});
});
You can check the client and server side validation by using this
if(Page_ClientValidate())
return true;
else
return false;

Categories

Resources