Painfully slow ajax calls using jQuery - javascript

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.

Related

Access the session variables from controller inside ajax call

I have certain fields getting filled in my controller.
public string AjaxLogin()
{
//some code to check admin or not
Session["UserName"] = "Smith";
if(type="Admin")
{
Session["UserRole"] = 1;
}
Session["EmployeeID"] = 101;
}
I have an ajax call to this controller like below and if it is success, I need to access these session variables inside success to check the user role.
$.ajax(
{
url: GLOBAL.GetAppPath() + 'Home/AjaxLogin',
data: data,
type: 'POST',
error: function (xhr, status, error) {
console.log(error);
},
success: function (result, status, xhr) {
if (result == 'OK')
{
var UserVal = '#Session["UserRole"]';
alert(UserVal);
if(UserVal ==1)
{
var baseUrl ="#Url.Action("Admin","AdminPage")";
window.location.href = baseUrl;
}
else
{
var baseUrl ="#Url.Action("Admin","RegularPage")";
window.location.href = baseUrl;
}
}
else {
$('#msgError').html('Error: ' + result);
$('#msgError').css('display', 'block');
}
},
});
But I cannot access this variable in this call. I want to check the user role variable and give url actions accordingly.
If you want to redirect to a controller in your project you can use the Url helper for you
Sample:
return JavaScript( "window.location = '" + Url.Action("Edit","Dispatch") + "'" );
P.S: I couldn't comment since it asks for 50 reputation that's why I'm commenting it over here.

Django: Best way to give Stripe ACH deposit verification Error

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 !")
}

my ajax post request is called twice

I have some javascript code in my wordpress site that post an ajax request to a php file and then the file generates a pdf with a quote.
It all works, but I don't understand why the second time I submit the request (to create the second quote, basically), the ajax request then is called twice?
the first time is correct, and it's called one time.
from the second time, it's always called twice.
here's the code:
$('#add-to-cart-quote-email-button').on('click', function() {
var statusIcon;
statusIcon = $('#quote-send-spinner');
$('.send-quote-from-cart-page-container').slideToggle();
statusIcon.removeClass('fa fa-check');
statusIcon.removeClass('fa fa-times');
$('#cart-quote-email-send-button').on('click', function(e) {
var data, email, name, quote_type, role;
e.preventDefault();
name = $('.send-quote-from-cart-page-container #name');
email = $('.send-quote-from-cart-page-container #email-address');
role = $('.send-quote-from-cart-page-container #user-role').val();
quote_type = $('.send-quote-from-cart-page-container #quote-type').val();
if (!name.val()) {
console.log("empty name");
name.addClass('invalid');
return;
} else {
if (name.hasClass('invalid')) {
name.removeClass('invalid');
}
}
if (!validateEmail(email.val())) {
console.log("invalid email");
email.addClass('invalid');
return;
} else {
if (email.hasClass('invalid')) {
email.removeClass('invalid');
}
}
console.log("sent! to email " + (email.val()) + " and name " + (name.val()));
data = {
name: name.val(),
email: email.val(),
role: role,
quote_type: quote_type
};
statusIcon.addClass('fa fa-spinner fa-spin fa-fw');
$.ajax({
type: 'post',
dataType: 'json',
url: '/wp-admin/admin-ajax.php',
data: 'cxecrt-success-get-link-url=&cxecrt-saved-cart-name=&cxecrt-landing-page=cart&action=save_cart_and_get_link_ajax',
success: function(response) {
data.cartURL = response.cart_url;
return $.ajax({
method: 'POST',
url: '/wp-content/themes/theme/generate_pdf_quotes/emailQuote.php',
data: data,
success: function() {
console.log("success!");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
statusIcon.addClass('fa fa-check');
return setTimeout(function() {
return $('.send-quote-from-cart-page-container').slideToggle();
}, 2000);
},
fail: function() {
console.log("fail");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
return statusIcon.addClass('fa fa-times');
}
});
}
});
});
});
return;
I need to call the second ajax on success of the first one, as they do two completely different things and the first one is required by the second one, that it's meant to be like that and it's not (i believe) the cause of this issue
I inspected the code but I couldn't see anything wrong in here.
Any thoughts?
thanks
You are defining an eventHandler within the first eventHandler.
On line 1:
$('#add-to-cart-quote-email-button').on('click', function() {
On line 7:
$('#cart-quote-email-send-button').on('click', function(e) {
That's why the second time it is clicked, it calls twice. I bet if you click it a third time it calls 3x ;-)

Angular use variable before running rest of the code

I know the problem is the order of execution, the scope fires async and loads the data after the rest of the code has been processed. I have a httpGET that gets the information from a web service and it's inside my Facebook share function when the user clicks the Facebook share button. But i tried adding a watch and .then with return promise in the httpget but both i could not get to work.
So the idea is the following: I have an CDImage that the user shares on facebook and i have another directory that holds promotional images for that same CD, not all of them so the httpGET checks if the promotionCDid exists if it exists the variable CDImage should be updated with the CDPromotionalURL instead of the standard url is get from CDImage so the user shares the Promotional image instead of the default CD cover.
So far the problem is that the CDImage does not change directly and console.log(CDImage) displays the CDCover the first time and when you click the button after several seconds the CDImage shows the CDPRomotionURL image.
var CDPromotionalImageUrl = "EMPTY";
$('#facebookshare').click(function () {
$scope.GetCDdata = function () {
$http({
method: 'Get',
url: "/GetCDPromotionImage?id_CD=" + promotionCDId,
})
.success(function (data, status, headers, config) {
$scope.CDdata = data;
CDPromotionalImage = $scope.CDdata[0].filename
$scope.CDPromotionalImageUrl = "https://website.com/" + CDPromotionalImage
})
.error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
};
if (CDPromotionalImageUrl == "EMPTY") {
CDImage = CDImage;
} else {
CDImage = CDPromotionalImageUrl;
}
console.log(CDImage)
var $this = $(this);
var urlShare = (window.location.href);
var obj = {
method: 'share',
href: (urlShare),
picture: (CDImage),
title: 'The ' + CDName,
caption: "As heard on website.com",
description:(description)
};
function callback(response) {
//alert("Post ID: " + response['post_id']);
}
FB.ui(obj, callback);
});
$scope.GetCDdata();

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources