TRUE single checkout page on BigCommerce - javascript
Currently BigCommerce has this hide/show effect only displaying one step of the checkout process at a time. It's rather an annoying accordion. I am trying to have the accordion info all open on the page. Also, I would love to combined and/or change the steps order. Any help with any of this would be great! Here is an example of the JS being used for the checkout process.
var ExpressCheckout = {
completedSteps: new Array(),
currentStep: 'AccountDetails',
signedIn: 0,
digitalOrder: 0,
createAccount: 0,
anonymousCheckout: 0,
checkoutLogin: 0,
init: function()
{
if($('#CheckoutStepAccountDetails').css('display') == 'none') {
ExpressCheckout.currentStep = 'BillingAddress';
}
else {
$('#BillingDetailsLabel').html(lang.ExpressCheckoutStepBillingAccountDetails);
}
$('.ExpressCheckoutBlock').hover(function() {
if($(this).hasClass('ExpressCheckoutBlockCompleted')) {
$(this).css('cursor', 'pointer');
}
},
function() {
$(this).css('cursor', 'default');
});
$('.ExpressCheckoutTitle').click(function() {
if($(this).hasClass('ExpressCheckoutBlockCompleted')) {
$(this).find('.ChangeLink').click();
}
});
// Capture any loading errors
$(document).ajaxError(function(event, request, settings) {
ExpressCheckout.HideLoadingIndicators();
alert(lang.ExpressCheckoutLoadError);
});
},
Login: function()
{
$('#CheckoutLoginError').hide();
ExpressCheckout.anonymousCheckout = 0;
ExpressCheckout.createAccount = 0;
if(ExpressCheckout.validateEmailAddress($('#login_email').val()) == false) {
alert(lang.LoginEnterValidEmail);
$('#login_email').focus();
$('#login_email').select();
return false;
}
if($('#login_pass').val() == '') {
alert(lang.LoginEnterPassword);
$('#login_pass').focus();
return false;
}
ExpressCheckout.ShowLoadingIndicator('#LoginForm');
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=expressCheckoutLogin&'+$('#LoginForm').serialize(),
success: ExpressCheckout.HandleResponse
});
return false;
},
HandleResponse: function(response)
{
ExpressCheckout.HideLoadingIndicators();
if(response.completedSteps != undefined) {
$.each(response.completedSteps, function() {
var value = document.createTextNode(this.message);
$('#CheckoutStep'+this.id+' .ExpressCheckoutCompletedContent').html(value);
$('#CheckoutStep'+this.id).addClass('ExpressCheckoutBlockCompleted');
ExpressCheckout.completedSteps[ExpressCheckout.completedSteps.length] = this.id;
});
}
if(response.stepContent != undefined) {
$.each(response.stepContent, function() {
$('#CheckoutStep'+this.id+' .ExpressCheckoutContent').html(this.content);
$('#CheckoutStep'+this.id+' .ExpressCheckoutContent .FormField.JSHidden').show();
});
}
ExpressCheckout.HandleResponseStatus(response);
},
HandleResponseStatus: function(response)
{
if(response.status == 0) {
if(response.errorContainer) {
$(response.errorContainer).html(response.errorMessage).show();
}
else {
alert(response.errorMessage);
}
}
if(response.changeStep) {
ExpressCheckout.ChangeStep(response.changeStep);
ExpressCheckout.ResetNextSteps();
}
// Set focus to a particular field
if(response.focus) {
try {
$(response.focus).focus().select();
}
catch(e) { }
}
},
GuestCheckout: function()
{
$('#CreateAccountForm').show();
$('#CheckoutLoginError').hide();
if($('#CheckoutGuestForm').css('display') != 'none' && !$('#checkout_type_register:checked').val()) {
type = 'guest';
ExpressCheckout.anonymousCheckout = 1;
ExpressCheckout.createAccount = 0;
}
else {
type = 'account';
ExpressCheckout.anonymousCheckout = 0;
ExpressCheckout.createAccount = 1;
}
ExpressCheckout.ShowLoadingIndicator('#CheckoutGuestForm');
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: {
w: 'expressCheckoutGetAddressFields',
type: type
},
success: ExpressCheckout.HandleResponse
});
},
ResetNextSteps:function()
{
steps = ExpressCheckout.GetSteps();
var beginReset = false;
var newCompleted = Array();
$.each(steps, function(i, step) {
if(step == ExpressCheckout.currentStep) {
newCompleted[newCompleted.length] = step;
beginReset = true;
}
else if(beginReset == true) {
$('#CheckoutStep'+step).removeClass('ExpressCheckoutBlockCompleted');
$('#CheckoutStep'+step+' .ExpressCheckoutCompletedContent').html('');
}
});
ExpressCheckout.completedSteps = newCompleted;
},
ChangeStep: function(step)
{
if(typeof(step) == 'undefined') {
step = ExpressCheckout.CalculateNextStep(ExpressCheckout.currentStep);
}
if(step == ExpressCheckout.currentStep) {
return false;
}
$('#CheckoutStep'+ExpressCheckout.currentStep+' .ExpressCheckoutContent').slideUp('slow');
$('#CheckoutStep'+ExpressCheckout.currentStep).addClass('ExpressCheckoutBlockCollapsed');
if($.inArray(ExpressCheckout.currentStep, ExpressCheckout.completedSteps) != -1) {
$('#CheckoutStep'+ExpressCheckout.currentStep).addClass('ExpressCheckoutBlockCompleted');
}
$('#CheckoutStep'+step+' .ExpressCheckoutContent').slideDown('slow');
$('#CheckoutStep'+step).removeClass('ExpressCheckoutBlockCollapsed');
ExpressCheckout.currentStep = step;
return false;
},
GetSteps: function()
{
var steps = Array();
if(ExpressCheckout.signedIn == 0) {
steps[steps.length] = 'AccountDetails';
}
steps[steps.length] = 'BillingAddress';
if(!ExpressCheckout.digitalOrder) {
steps[steps.length] = 'ShippingAddress';
steps[steps.length] = 'ShippingProvider';
}
steps[steps.length] = 'Confirmation';
steps[steps.length] = 'PaymentDetails';
return steps;
},
CalculateNextStep: function(currentStep) {
steps = ExpressCheckout.GetSteps();
var nextStep = '';
$.each(steps, function(i, step) {
if(step == currentStep) {
nextStep = steps[i + 1];
}
});
if(nextStep) {
return nextStep;
}
},
ChooseBillingAddress: function()
{
// Chosen to use a new address?
if(!$('#BillingAddressTypeExisting:checked').val() || $('#ChooseBillingAddress').css('display') == 'none') {
// If creating a new account, validate the account fields as well
if((ExpressCheckout.anonymousCheckout || ExpressCheckout.createAccount) &&
!ExpressCheckout.ValidateNewAccount(true)) {
return false;
}
if(!ExpressCheckout.ValidateNewAddress('billing')) {
return false;
}
addressType = 'new';
}
// An address wasn't selected
else if($('.SelectBillingAddress select option:selected').val() == -1) {
alert(lang.ExpressCheckoutChooseBilling);
$('.SelectBillingAddress select').focus();
return false;
}
else {
addressType = 'existing';
}
createAppend = '';
if(ExpressCheckout.createAccount) {
createAppend = '&createAccount=1';
}
// ISC-1214: no script issue in webkit browser, with serialized form submission
$('noscript').remove();
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=saveExpressCheckoutBillingAddress&'
+ $('#NewBillingAddress').serialize()
+ '&BillingAddressType=' + addressType
+ createAppend,
success: ExpressCheckout.HandleResponse
});
return false;
},
ChooseShippingAddress: function(copyBilling)
{
// Chosen to use a new address?
if(!$('#ShippingAddressTypeExisting:checked').val() || $('#ChooseShippingAddress').css('display') == 'none') {
if(!ExpressCheckout.ValidateNewAddress('shipping')) {
return false;
}
addressType = 'new';
}
// An address wasn't selected
else if($('.SelectShippingAddress select option:selected').val() == -1) {
alert(lang.ExpressCheckoutChooseShipping);
$('.SelectShippingAddress select').focus();
return false;
}
else {
addressType = 'existing';
}
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=saveExpressCheckoutShippingAddress&'
+$('#NewShippingAddress').serialize()
+'&ShippingAddressType='+addressType,
success: ExpressCheckout.HandleResponse
});
return false;
},
SetBillingAndShippingAddress: function()
{
// billing address is pre-selected so update the HTML block content from selected index
billingAddress = $('.SelectBillingAddress select option:selected').html().substring(0, 58);
$('#CheckoutStepBillingAddress .ExpressCheckoutCompletedContent').html(billingAddress + '...');
$('#CheckoutStepBillingAddress').addClass('ExpressCheckoutBlockCompleted');
// select given shipping address and reset the cart step to ShippingProvider
ExpressCheckout.ChooseShippingAddress();
return false;
},
ChooseShippingProvider: function()
{
// A shipping provider hasn't been selected
var shippingValid = true;
$('#CheckoutStepShippingProvider .ShippingProviderList').each(function() {
if(!$(this).find('input[type=radio]:checked').val()) {
alert(lang.ExpressCheckoutChooseShipper);
$(this).find('input[type=radio]').get(0).focus();
shippingValid = false;
return false;
}
});
if(shippingValid == false) {
return false;
}
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=saveExpressCheckoutShippingProvider&'+$('#CheckoutStepShippingProvider form').serialize(),
success: ExpressCheckout.HandleResponse
});
return false;
},
ShowLoadingIndicator: function(step) {
if(typeof(step) == 'undefined') {
step = 'body';
}
$(step).find('.ExpressCheckoutBlock input[type=submit]').each(function() {
$(this).attr('oldValue', $(this).val());
$(this).val(lang.ExpressCheckoutLoading);
$(this).attr('disabled', true);
});
$(step).find('.LoadingIndicator').show();
$('body').css('cursor', 'wait');
},
HideLoadingIndicators: function()
{
HideLoadingIndicator();
$('.ExpressCheckoutBlock input[type=submit]').each(function() {
if($(this).attr('oldValue') && $(this).attr('disabled') == true) {
$(this).val($(this).attr('oldValue'));
$(this).attr('disabled', false);
}
});
$('.LoadingIndicator').hide();
$('body').css('cursor', 'default');
},
LoadOrderConfirmation: function()
{
postVars.w = 'expressCheckoutShowConfirmation';
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: postVars,
success: ExpressCheckout.HandleResponse
});
},
HidePaymentForm: function()
{
$('#CheckoutStepPaymentDetails').hide();
$('#CheckoutStepPaymentDetails .ExpressCheckoutContent').html('');
},
LoadPaymentForm: function(provider)
{
$.ajax({
url: 'remote.php',
data: 'w=expressCheckoutLoadPaymentForm&'+$('#CheckoutStepConfirmation form').serialize(),
dataType: 'json',
type: 'post',
success: ExpressCheckout.HandleResponse
});
},
ShowSingleMethodPaymentForm: function()
{
$('#CheckoutStepPaymentDetails').show();
ShowContinueButton();
},
ValidateNewAccount: function()
{
var password, confirmPassword, formfield = FormField.GetValues(CustomCheckoutFormNewAccount);
for (var i=0; i<formfield.length; i++) {
// Check email
if (formfield[i].privateId == 'EmailAddress') {
if (ExpressCheckout.validateEmailAddress(formfield[i].value) == false) {
alert(lang.LoginEnterValidEmail);
FormField.Focus(formfield[i].field);
return false;
}
}
if (formfield[i].privateId == 'Password') {
if(!ExpressCheckout.createAccount) {
continue;
}
password = formfield[i];
}
else if(formfield[i].privateId == 'ConfirmPassword') {
if(!ExpressCheckout.createAccount) {
continue;
}
confirmPassword = formfield[i];
}
var rtn = FormField.Validate(formfield[i].field);
if (!rtn.status) {
alert(rtn.msg);
FormField.Focus(formfield[i].field);
return false;
}
}
// Compare the passwords
if (ExpressCheckout.createAccount && password && password.value !== confirmPassword.value) {
alert(lang.AccountPasswordsDontMatch);
FormField.Focus(confirmPassword.field);
return false;
}
return true;
},
BuildAddressLine: function(type)
{
var fieldList = {
'FirstName' : '',
'LastName' : '',
'Company' : '',
'AddressLine1' : '',
'City' : '',
'State' : '',
'Zip' : '',
'Country' : ''
};
if(type == 'billing') {
var formId = CustomCheckoutFormBillingAddress;
}
else {
var formId = CustomCheckoutFormShippingAddress;
}
var formfields = FormField.GetValues(formId);
var addressLine = '';
for (var i=0; i<formfields.length; i++) {
fieldList[formfields[i].privateId] = formfields[i].value;
}
for (var i in fieldList) {
var val = fieldList[i];
if (val !== '') {
if(addressLine != '' && i != 'LastName') {
addressLine += ', ';
} else if(i == 'LastName') {
addressLine += ' ';
}
addressLine += val;
}
};
return addressLine;
},
ValidateNewAddress: function(lowerType, resultOnly)
{
if (resultOnly !== true) {
resultOnly = false;
}
if(lowerType == 'billing') {
var formId = CustomCheckoutFormBillingAddress;
} else {
var formId = CustomCheckoutFormShippingAddress;
}
var formfields = FormField.GetValues(formId);
var hasErrors = false;
for (var i=0; i<formfields.length; i++) {
var rtn = FormField.Validate(formfields[i].field);
if (!rtn.status) {
if (!resultOnly) {
alert(rtn.msg);
}
FormField.Focus(formfields[i].field);
hasErrors = true;
return false;
}
}
if(hasErrors == true) {
return false;
}
else {
return true;
}
},
validateEmailAddress: function(email)
{
if(email.indexOf('#') == -1 || email.indexOf('.') == -1) {
return false;
}
return true;
},
ToggleAddressType: function(address, type)
{
if(type == 'Select') {
$('.Select'+address+'Address').show();
$('.Add'+address+'Address').hide();
}
else {
$('.Add'+address+'Address').show();
$('.Select'+address+'Address').hide();
}
},
SelectedPaymentProvider: function() {
var paymentProvider = '';
// Get the ID of the selected payment provider
if($('#use_store_credit').css('display') != "none") {
if($('#store_credit:checked').val()) {
if($('#credit_provider_list').css('display') != "none") {
paymentProvider = $('#credit_provider_list input:checked');
}
}
else {
paymentProvider = $('#provider_list input:checked');
}
}
else {
paymentProvider = $('#provider_list input:checked');
}
return paymentProvider
},
ConfirmPaymentProvider: function()
{
//if terms and conditions is enabled and the customer didn't tick agree terms and conditions
if($('.CheckoutHideOrderTermsAndConditions').css('display') != "none" && $('#AgreeTermsAndConditions').prop('checked') != true){
alert(lang.TickArgeeTermsAndConditions);
return false;
}
if(!confirm_payment_provider()) {
return false;
}
var paymentProvider = ExpressCheckout.SelectedPaymentProvider();
if(paymentProvider != '' && $(paymentProvider).hasClass('ProviderHasPaymentForm')) {
var providerName = $('.ProviderName'+paymentProvider.val()).html();
$('#CheckoutStepConfirmation .ExpressCheckoutCompletedContent').html(providerName);
ExpressCheckout.LoadPaymentForm($(paymentProvider).val());
return false;
}
else {
ExpressCheckout.HidePaymentForm();
return true;
}
},
ApplyCouponCode: function()
{
if($('#couponcode').val() == '') {
alert(lang.EnterCouponCode);
$('#couponcode').focus();
return false;
}
// Reload the order confirmation
$.ajax({
url: 'remote.php',
data: 'w=getExpressCheckoutConfirmation&'+$('#CheckoutStepConfirmation form').serialize(),
dataType: 'json',
type: 'post',
success: ExpressCheckout.HandleResponse
});
return false;
},
UncheckPaymentProvider: function()
{
$('#provider_list input').each(function() {
$(this).attr('checked', false);
});
}
};
I could get the top three accordions open at the same time (the bottom ones are shipping methods and order confirmations, which I think are tied to the previous steps)
$('.ExpressCheckoutBlockCollapsed').addClass('ExpressCheckoutBlockCompleted')
$('.ExpressCheckoutBlockCollapsed').removeClass('ExpressCheckoutBlockCollapsed')
I think if you have this code trigger on the checkout page, it might help a little. Regarding changing the order of elements, chrome console shows the following IDs associated with these elements, can't you anchor them to different locations, as you need it?
$('.ExpressCheckoutBlockCollapsed').addClass('ExpressCheckoutBlockCompleted')
[
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCompleted" id="CheckoutStepBillingAddress" style="cursor: default;">…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepShippingAddress" style>…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepShippingProvider" style>…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepConfirmation">…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepPaymentDetails" style="display: none">…</div>
]
Related
How can I store the data in a variable of an ajax call and print it?
I have two files one with a login form, and one with the response content if the call is successful, it executes another one for loading buttons. What I would like to do is that inside the first call there is a field called RSociale and that inside has the name and surname of the user who logged in. How can I retrieve that field and print it in the part where the buttons are already there? This is the ajax call to login: function lg_controllacredenziali() { sem_PulisciCampiObbligatori(); if ($('#password').hasClass("form-required") == false) { $('#password').addClass("form-required"); } if ($('#password').hasClass("form-text") == false) { $('#password').addClass("form-text"); } if ($('#user').val() == '') { sem_ControllaCampiRichiesti(); lg_ControllaCampiText(); } if ($('#user').hasClass("input-text") == true) { $('#user').removeClass("input-text"); } if ($('#user').hasClass("input-user") == true) { $('#user').removeClass("input-user"); } if ($('#password').hasClass("input-text") == true) { $('#password').removeClass("input-text"); } if ($('#password').val() == '') { sem_ControllaCampiRichiesti(); lg_ControllaCampiText(); } else { jQuery.ajax({ url: sem_wsurl + 'ws_json_intra_logon', type: 'GET', data: { login: $('#user').val(), clear: 'S', password: encodeURI($('#password').val()) }, dataType: 'jsonp', processData: true, success: function(json) { if (json.Response[0].ResultCode != "000") { lg_ControllaCampifalse(); if ($('#password').hasClass("input-false") == false) { $('#password').addClass("input-false"); } if ($('#user').hasClass("input-false") == false) { $('#user').addClass("input-false"); } if ($('#user').hasClass("input-required") == false) { $('#user').addClass("input-required"); } if ($('#password').hasClass("input-required") == false) { $('#password').addClass("input-required"); } } else { //Setto i Cookie sem_setCookie("wc_login",$('#user').val(),null); sem_setCookie("wc_password",json.Response[0].Pwdcookie,null); //lg_setCookie("wc_database",json.Response[0].Dbcookie,10); sem_setCookie("wc_database","dbeutelia",null); sem_setCookie("wc_header",sem_header,null); sem_setCookie("wc_footer",sem_footer,null); window.location.replace("sem_menu.html"); window.open(url, "_self"); } }, error: function(error) {} }); } } If the call is successful, it opens a page which in its turn makes another call to load the buttons function CaricaCluster() { if (sem_readCookie("wc_login") != null && sem_readCookie("wc_password") != null) { if (sem_readCookie("wc_login").replace(/\"/g,"") != '' && sem_readCookie("wc_password").replace(/\"/g,"") != '') { jQuery.ajax({ url: sem_wsurl + 'ws_json_sem_cluster', type: 'GET', data: { ws_login: sem_readCookie("wc_login").replace(/\"/g,""), ws_password_type: 'C', ws_pwd: encodeURI(sem_readCookie("wc_password").replace(/\"/g,"")) }, dataType: 'jsonp', processData: true, success: function(json) { if (json.Response[0].ResultCode != "000") alert("errore"); else { $.each(json, function() { TblPulsanti = json.Response[0].Details; StampaPulsanti(); }); } }, error: function(error) { alert("Errore"); } }); } } }
Select2 - load data once from remote but perform search on client
I am trying to use "query" object to perform what i want. Everythings works except when i select an option nothing happen (placeholder is not replaced). I have followed the instructing from this post Loading remote data only once with Select2 init() { this.$view.select2({ theme: "bootstrap", language: "fr", allowClear: this.options.allowClear, placeholder: this.options.placeholder, query: (query) => { if (this.items) { query.callback({results: this.filterItems(query.term)}); } else { this.loadData(query); } }, templateResult: (state) => { return this.format(state); } }); } loadData(query) { $.ajax({ url: this.options.url, dataType: 'json', type: 'GET', success: (data) => { this.items = []; for (let row of data) { this.items.push({ id: row.id, entity_id: row.entity_id, text: row.label, type: row.type, disabled: !row.enable }); } query.callback({results: this.items}); } }); } filterItems(term) { if (typeof term == "undefined" || term === null) { return this.items; } const _term = $.trim(term.toLowerCase()); if (_term === '') { return this.items; } return this.items.filter((item) => { return item.text.toLowerCase().includes(term); }); } Thanx for help,
I think i have found a solution : var s2data = $view.select2({ ajax: { url: 'https://api.github.com/search/repositories', data: { q: 'select2' }, dataType: 'json', processResults: function(data) { var items = []; for (var row of data.items) { items.push({ id: row.id, text: row.name }); } this.options.set('cacheDataSource', {items: items}); return { results: items }; } }, cacheDataSource: [], allowClear: true, placeholder: 'Select Values ...', width: '100%', }).data('select2'); s2data.dataAdapter.query = function(params, callback) { var cacheDataSource = this.options.get('cacheDataSource'); if (cacheDataSource && cacheDataSource.items) { var term = params.term; if (typeof term == "undefined" || term == null) { callback({results: cacheDataSource.items}); return } term = $.trim(term.toLowerCase()); if (term == "") { callback({results: cacheDataSource.items}); return } callback({ results: cacheDataSource.items.filter(function(item) { return item.text.toLowerCase().includes(term); }) }); } else { // call the original logic var ajaxAdapterFunc = jQuery.fn.select2.amd.require('select2/data/ajax'); var ajaxAdapter = new ajaxAdapterFunc(this.$element, this.options); ajaxAdapter.query(params, callback); } } jsfiddle : https://jsfiddle.net/3kpu4htm/35/
my function entering to infinite loop when call AJAX?
The send_data function Called from createNewTable function(onclick). i dont understand why my function entering to infinite loop when action_id === "new_table_btn"(action_id it's indicator ). Please help me HTML <button type="submit" class="btn btn-default" onclick="createNewTable()">Send</button> JQuery/Ajax function createNewTable() { _table_name = $("#table_name").val(); var data = "Indicator=new_table&table_name=" + _table_name + "&player_email=" + player_email; send_data(data, "new_table_btn"); } function send_data(j_data, action_id) { var results; //var k_data = [{aaaa:"solange"}]; $.ajax({ url: "SrvController", dataType: 'json', type: 'post', //contentType: 'application/json', data: j_data, // "Indicator=world_games&player_email=dana#mmm.com", //"aaaa=lllll&aaa=pppp",//JSON.stringify(k_data), //processData: false, success: function (data, textStatus, jQxhr) { if (action_id === "join_table") { // turn_place = if (data["status"] === "success") { player_place = data["sit"]; $("#playground").hide("slow", arguments.callee); $("#startGame").show("slow"); if (!read_data) { new_round_data(); read_data = true; } } else $("#playground").append("fail"); } if (action_id === "world_games") { read_activ_tables(data); } if (action_id === "new_round_data") { new_round(data); } if (action_id === "get_table_id") { _table_number = data["tableNumber"]; var data = "Indicator=join_table&table_id=" + _table_number + "&player_email=" + player_email; send_data(data, "join_table"); } if (action_id === "new_table_btn") { if (typeof data !== "undefined") _table_number = data["tableId"]; player_place = "1"; $("#playground").hide("fast", arguments.callee); $("#startGame").show("slow"); if (!read_data) { read_data = true; new_round_data(); } } }, error: function (jqXhr, textStatus, errorThrown) { console.log(errorThrown); } }); //results.innerHTML = "processing..."; }
How to solve Uncaught TypeError: Cannot read property 'length' of null
I have installed a wp plugin , When I use default wp theme , it works fine but when I use another theme it does not loads one of the tabs , by inspect element I get this Uncaught TypeError: Cannot read property 'length' of null The code on the page it is mentioning is this function show_submissions(page,search) { if (typeof page=='string') { var data = 'action=formcraft_page&page='+page; } else { var data = 'action=formcraft_page&search='+search; var page = 0; } jQuery('#subs tbody').html('<tr><td colspan="6"><center><div style="margin: 30px auto; width: 30px;font-size: 14px; color: #888">loading...</div></center></td></tr>') jQuery.ajax({ url: ajaxurl, type: "POST", dataType: "json", data: data, success: function (response) { jQuery('.fc_pagination .active').removeClass('active'); jQuery('.fc_pagination .page:nth-child('+page+')').addClass('active'); if (response.length==0) { jQuery('#subs tbody').html('<center style="margin: 20px; font-size: 14px">No Results</center>'); return false; } for (var sub in response) { var read = response[sub]['seen'] == '' || response[sub]['seen'] == null ? 'Unread' : 'Read'; var shade = response[sub]['seen'] == '' || response[sub]['seen'] == null ? 'row_shade' : ''; var id = response[sub]['id']; var name = response[sub]['name'] ? response[sub]['name'] : 'deleted'; var row = '<tr id="sub_'+id+'" class="'+shade+'">'; var row = row + '<td>'+id+'</td>'; var row = row + '<td id="rd_'+id+'">'+read+'</td>'; var row = row + '<td id="rd_'+id+'">'+response[sub]['added']+'</td>'; var row = row + '<td>'+name+'</td>'; var row = row + '<td><a class="fc-btn show-message" id="upd_'+id+'" data-target="#view_modal" data-toggle="fcmodal">View</a><div class="sub-content" id="sub-content-'+id+'">'+response[sub]['content']+'</div></td>'; var row = row + '<td><i class="formcraft-trash sub_upd" id="del_'+id+'" title="Delete message"></i> <i class="formcraft-bookmark-empty sub_upd" id="read_'+id+'" title="Mark as unread"></i></td>'; var row = row + '</tr>'; var html = html + row; } jQuery('#subs tbody').html(''); jQuery('#subs tbody').append(html); }, error: function (response) { jQuery('#save_form_btn').html(jQuery('#save_form_btn').attr('data-error')); window.saving = false; } }); } function drawChart(id, from, to) { jQuery('#chart-cover').addClass('loading') if (id) { var jsonData = jQuery.ajax({ url: ajaxurl, dataType: "json", type: "POST", data: 'id='+id+'&action=formcraft_chart&from='+from+'&to='+to, async: false }).responseText; } else { var jsonData = jQuery.ajax({ url: ajaxurl, dataType: "json", data: 'action=formcraft_chart&from='+from+'&to='+to, async: false }).responseText; } var jsonData = jQuery.parseJSON( jsonData ); var totalViews = 0; for (values in jsonData.views) { totalViews = totalViews + parseInt(jsonData.views[values][1]); } var totalSubmissions = 0; for (values in jsonData.submissions) { totalSubmissions = totalSubmissions + parseInt(jsonData.submissions[values][1]); } jQuery({someValue: parseInt(jQuery('#tvs').text())}).animate({someValue: totalViews}, { duration: 900, easing:'swing', step: function() { jQuery('#tvs').text(Math.ceil(this.someValue)); } }); jQuery({someValue: parseInt(jQuery('#tss').text())}).animate({someValue: totalSubmissions}, { duration: 900, easing:'swing', step: function() { jQuery('#tss').text(Math.ceil(this.someValue)); } }); jQuery({someValue: parseInt(jQuery('#tcs').text())}).animate({someValue: (Math.round((totalSubmissions/totalViews)*10000)/100)}, { duration: 900, easing:'swing', step: function() { jQuery('#tcs').text(Math.ceil(this.someValue)+'%'); } }); setTimeout(function(){ jQuery('#tvs').text(totalViews); jQuery('#tss').text(totalSubmissions); jQuery('#tcs').text((Math.round((totalSubmissions/totalViews)*10000)/100)+'%'); }, 1000); var plot = jQuery.plot("#chart-inner", [{ data: jsonData.views, label: 'views', color: 'rgb(255, 175, 80)', bars: {show:true, align: 'center'} },{ data: jsonData.submissions, label: 'submissions', color: 'rgb(28, 160, 28)', lines: {show:true} }], { series: { points: { show:true } }, grid: { hoverable: true, clickable: true }, xaxis: { mode: "categories" } }); jQuery('#chart-cover').removeClass('loading') jQuery("#chart-inner").bind("plothover", function (event, pos, item) { if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; jQuery("#tooltip").remove(); var x = Object.keys(item.series.xaxis.categories)[item.datapoint[0]], y = item.datapoint[1]; showTooltip(item.pageX, item.pageY, y + ' ' + item.series.label + " on " + x); } } else { jQuery("#tooltip").remove(); previousPoint = null; } }); jQuery("#chart-inner").bind("plotclick", function (event, pos, item) { if (item) { jQuery("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label); plot.highlight(item.series, item.datapoint); } }); } function setupLabel() { if (jQuery('.label_check input').length) { jQuery('.label_check').each(function(){ jQuery(this).removeClass('c_on'); }); jQuery('.label_check input:checked').each(function(){ jQuery(this).parent('label').addClass('c_on'); }); }; if (jQuery('.label_radio input').length) { jQuery('.label_radio').each(function(){ jQuery(this).removeClass('r_on'); }); jQuery('.label_radio input:checked').each(function(){ jQuery(this).parent('label').addClass('r_on'); }); }; }; jQuery(function () { jQuery('#import').fileupload({ dataType: 'json', add: function (e, data) { var type = data.files[0].name; var type = type.split('.'); var type = type[1]; if (type!='txt') { alert('Only .txt files'); return false; } data.submit(); jQuery('#fu-label').text('wait'); jQuery('#import').prop("disabled",true); }, done: function (e, resp) { if(resp.result.failed) { jQuery('#import').prop("disabled",false); jQuery('#fu-label').text(resp.failed); } else { jQuery('#import_form').val(resp.result.files.new_name); jQuery('#import').prop("disabled",true); jQuery('#fu-label').html('<i class="formcraft-ok" style="font-size: 10px"></i> Done'); jQuery('#rand_b').trigger('click'); setupLabel(); jQuery('#import').parent().addClass('green'); } }, fail: function (e, data){ jQuery('.import').prop("disabled",false); jQuery('#import_field_label').text('Failed'); jQuery('#fu-label').text('Rety'); } }); }); jQuery(document).ready(function () { setTimeout(function(){ jQuery('#fc-page-1').trigger('click'); }, 1000); /* Update Submissions */ jQuery('body').on('click','.sub_upd, .show-message',function(){ var id = jQuery(this).attr('id').split('_'); var id2 = jQuery(this).attr('id'); jQuery('#view_modal .modal-body').html(jQuery('#sub-content-'+id[1]).html()); if (id[0]=='upd') { jQuery('#view_modal .modal-body').html(jQuery('#upd_text_'+id[1]).html()); jQuery('#view_modal .myModalLabel').html(jQuery('#upd_name_'+id[1]).html()); jQuery('#rd_'+id[1]).html('Read'); jQuery(this).parent().parent().addClass('row_shade'); jQuery.ajax({ url: ajaxurl, type: "POST", data: 'action=formcraft_sub_upd&type=upd&id='+id[1], success: function (response) { jQuery('#'+id2).parent().parent().removeClass('row_shade'); }, error: function (response) { } }); } else if (id[0]=='del') { jQuery.ajax({ url: ajaxurl, type: "POST", data: 'action=formcraft_sub_upd&type=del&id='+id[1], success: function (response) { if (response=='D') { jQuery('#'+id2).removeClass('formcraft-trash'); jQuery('#'+id2).addClass('formcraft-ok').css('color','green'); } }, error: function (response) { } }); } else if (id[0]=='read') { jQuery.ajax({ url: ajaxurl, type: "POST", data: 'action=formcraft_sub_upd&type=read&id='+id[1], success: function (response) { if (response=='D') { jQuery('#rd_'+id[1]).html('Unread'); jQuery('#'+id2).parent().parent().addClass('row_shade'); } }, error: function (response) { } }); } }); // Set up DataTable if (jQuery('#subs').length) { jQuery('#ext').dataTable({ "sPaginationType": "full_numbers" }); jQuery('#files_manager_table').dataTable({ "sPaginationType": "full_numbers" }); } jQuery('#new_form').submit(function(event){ event.preventDefault(); var data = 'action=formcraft_add&import_form='+jQuery('#import_form').val()+'&name='+jQuery('#new_name').val()+'&desc='+jQuery('#new_desc').val()+'&type_form='+jQuery('[name="type_form"]:checked').val()+'&duplicate='+jQuery('[name="duplicate"]').val(); jQuery('.response_ajax').html('processing ...'); jQuery.ajax({ url: ajaxurl, type: "POST", dataType: 'json', data: data, success: function (response) { if (response.Added) { jQuery('.response_ajax').html('Added'); window.location.href = 'admin.php?page=formcraft_admin&id='+response.Added; } else if (response.Error) { jQuery('.response_ajax').html(response.Error); } }, error: function (response) { jQuery('.response_ajax').html(response); } }); }); jQuery('#subs_search').submit(function(event){ event.preventDefault(); show_submissions(false,jQuery('#search_query').val()); }); drawChart(); jQuery('.datepicker-field').datepicker().on('changeDate', function(ev){ jQuery(this).datepicker('hide'); jQuery(this).trigger('change'); }); jQuery('.datepicker-field').wrap("<div class='datepicker-cover'></div>"); jQuery('body').on('click', '.datepicker-cover', function(){ jQuery(this).find('input').focus(); }); jQuery('body').on('click','.nav-main li', function(event) { event.preventDefault(); var index = jQuery(this).parent().index(); jQuery('.tab-content .tab-pane').removeClass('active'); jQuery('.tab-content .tab-pane:eq('+index+')').addClass('active'); jQuery('.nav-main table td li').removeClass('active'); jQuery('.nav-main table td:eq('+index+') li').addClass('active'); }); jQuery("input.rand2").focus(function(){ event.stopPropagation(); }); jQuery('#rand_a').change(function(){ jQuery('#rand_aa').trigger('click'); setupLabel(); }); jQuery('body').on('submit','#fc-pk',function(event){ event.preventDefault(); jQuery('#fc-pk .response').text('...'); jQuery.ajax({ type: "GET", url: ajaxurl, data: 'key='+jQuery('#fc-pk-input').val()+'&action=formcraft_verifyLicense', dataType: "json", success: function(response) { if (response.message) { jQuery('#fc-pk .response').text(response.message); } else { jQuery('#fc-pk .response').text('Unknown error'); } }, }); }); jQuery('body').on('click','.delete_from_manager',function(){ jQuery(this).html(jQuery(this).attr('data-loading')); if (jQuery(this).attr('data-name')){var data = 'name='+encodeURIComponent(jQuery(this).attr('data-name'));} else if (jQuery(this).attr('data-key')){var data = 'key='+encodeURIComponent(jQuery(this).attr('data-key'));} var id_this = this.id; jQuery.ajax({ url: ajaxurl, type: "POST", data: 'action=formcraft_delete_file&'+data, success: function (response) { if (response=='Deleted') { jQuery('#'+id_this).removeClass('btn-danger'); jQuery('#'+id_this).addClass('btn-success'); jQuery('#'+id_this).html(jQuery('#'+id_this).attr('data-complete')); } }, error: function (response) { } }); }); jQuery('#export').click(function(){ window.open(Url.exporturl,'_blank'); }); jQuery('body').on('click', '.delete-row', function() { if (confirm('Are you sure you want to delete the form? You can\'t undo this action.')) { if(jQuery(this).hasClass('btn-danger')) { var this_id = jQuery(this).attr('id'); jQuery(this).html(jQuery(this).attr('data-loading')); var id = jQuery(this).parent('td').parent('tr').attr('id'); jQuery.ajax({ url: ajaxurl, type: "POST", data: 'action=formcraft_del&id='+id, success: function (response) { if (response=='Deleted') { jQuery('#'+this_id).html(jQuery('#'+this_id).attr('data-complete')); jQuery('#'+this_id).removeClass('btn-danger'); jQuery('#'+this_id).addClass('btn-success'); } else { jQuery('#'+this_id).html(jQuery('#'+this_id).attr('data-reset')); } }, error: function (response) { alert("There was an error."); } }); } } }); jQuery('body').on('click', '.row_click', function() { var id = jQuery(this).parent('tr').attr('id'); window.location.href = 'admin.php?page=formcraft_admin&id='+id; }); // Edit Form Name and Description jQuery("body").on('click', '.edit_btn', function(event){ event.stopPropagation(); jQuery(this).hide(); jQuery(this).parent().children('.rand').hide(); var name = jQuery(this).prev('a').html(); jQuery(this).prev('input.rand2').show(); jQuery(this).prev('input.rand2').focus(); jQuery(this).next('a.save_btn').show(); }); jQuery('body').on('click','.rand2',function(event){ event.stopPropagation(); }); jQuery("body").on('click', '.save_btn', function(event){ event.stopPropagation(); jQuery(this).hide(); var this_id = jQuery(this).attr('id'); var id = jQuery(this).attr('id').split('_'); var val = jQuery(this).parents().children('.rand2').val(); jQuery.ajax({ url: ajaxurl, type: "POST", data: 'action=formcraft_name_update&name='+val+'&id='+id[1], success: function (response) { if (response=='D') { jQuery('#'+this_id).parent().children('.rand').text(val); jQuery('#'+this_id).parent().children('input.rand2').hide(); jQuery('#'+this_id).parent().children('.rand').show(); jQuery('#'+this_id).parent().children('.edit_btn').show(); } else { jQuery('#'+this_id).show(); jQuery('#'+this_id).parent().children('input.rand2').hide(); jQuery('#'+this_id).parent().children('.rand').show(); jQuery('#'+this_id).parent().children('.edit_btn').show(); } }, error: function (response) { jQuery('#'+this_id).show(); } }); }); jQuery('#stats_select, #chart-from, #chart-to').change(function(){ var id = jQuery('#stats_select').val(); var from = jQuery('#chart-from').val(); var to = jQuery('#chart-to').val(); drawChart(id, from, to); }); jQuery('#chart-to').datepicker('remove'); jQuery('#chart-to').datepicker({'endDate': new Date()}); jQuery('#chart-from').change(function(){ var sd = jQuery(this).val().split('/'); sd = new Date( parseInt(sd[0]), parseInt(sd[1])-1, parseInt(sd[2]) ); jQuery('#chart-to').datepicker('remove'); jQuery('#chart-to').datepicker({'startDate': sd}).on('changeDate', function(ev){ jQuery(this).datepicker('hide'); jQuery(this).trigger('change'); }); }); jQuery('#export_select').change(function(){ var val = jQuery(this).val(); if (val=='0') { var href = jQuery('#export_url').attr('href'); var href = href.replace('?id='+href.substring(href.indexOf('?id=')+4, href.length),'?id=0'); } else { var href = jQuery('#export_url').attr('href'); var href = href.replace('?id='+href.substring(href.indexOf('?id=')+4, href.length),'?id='+val); } jQuery('#export_url').attr('href',href); }); setupLabel(); jQuery('body').addClass('has-js'); jQuery('body').on("click",'.label_check, .label_radio' , function(){ setupLabel(); }); jQuery('body').on('click', '.show-message', function(){ var html = jQuery(this).parent().find('.sub-content').html(); jQuery('#print_area').html(html); }); jQuery('body').on('click','.fc_pagination > .page',function(){ show_submissions(jQuery(this).text(),false); }); }); Here is a screenshot on both theme from inspect element and working/non working page http://i.stack.imgur.com/6TkWs.png
says my function is undefined when assigning to a variable
i have a problem. I am trying to add a functions return value to a variable but it says the function is undefined. Here is my code. : var selectedExpenseList = getSelectedExpenseIDs(); here is my function: function getSelectedExpenseIDs() { var selectedExpensesList = new Array; var i = 0; $('.expenseCheckBox:checked').each(function () { if ($(this)[0].id !== "checkAllExpenses") { selectedExpensesList[i] = $(this)[0].id.split('_')[1]; ++i; } }); return selectedExpensesList; } EDIT: here is my entire function: I am trying to delete something from a list if a person has checked it. var selectedExpenseList; function actuallyDeleteTheExpense(canDeleteExpenses) { selectedTasksList = getSelectedTaskIDs(); var deleteTrackers = false, deleteExpenses = false; if (canDeleteExpenses && !canDeleteTrackers) { $.Zebra_Dialog('Do you wish to remove Expenses?', { 'type': 'question', 'title': 'Confirmation', 'buttons': [ { caption: 'Yes', callback: function () { deleteTrackers = false; deleteExpenses = true; doTheDelete(deleteExpenses); } }, { caption: 'No', callback: function () { doTheDelete(deleteExpenses); } } ] }); } } function doTheDelete(doIDeleteExpenses) { if (selectedTasksList.length > 0) { $.ajax({ type: "POST", //url: "/Tasks/ViewTasks.aspx/deleteTasksAndLinkedItems", url: '<%=ResolveUrl("~/Expenses/ViewExpenses.aspx/deleteSelectedExpense")%>', data: "{ 'TaskIDs': [" + selectedTasksList.join(',') + "], DeleteTrackers : " + doIDeleteTrackers + ", DeleteExpenses : " + doIDeleteExpenses + " }", //fix data contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var ss = data.d; if (ss.length > 0) { for (var i = 0; i < ss.length; ++i) { $.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true }); alert(ss[i]); } } $("#viewTasksGrid").flexReload(); }, error: function (data) { $.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true, modal: true }); alert('Error Deleting Tasks'); if (window.console) { console.log(data); } } }); } else { showMessage('No tasks are selected.'); } } //end delete expense function getSelectedExpenseIDs() { var selectedExpensesList = new Array; var i = 0; $('.expenseCheckBox:checked').each(function () { if ($(this)[0].id !== "checkAllExpenses") { selectedExpensesList[i] = $(this)[0].id.split('_')[1]; ++i; } }); return selectedExpensesList; }
I noticed that your function code is tabbed once more than your code that calls it. It's possible that your function is scoped improperly (e.g. it's declared inside another function and you're calling it from outside that function). If your function is coming back as undefined, it's almost certainly a scoping issue. I see nothing wrong with the function itself. For instance: $(document).ready(function () { function myFunction() { return 3; } }); var bob = myFunction(); //Error: myFunction is not defined.