Index.html keep checking for session storage changes

I have an index.html which contains a script tag. The script only runs if a variable in session storage is found to be true. However I have to refresh the page to detect any changes in the session storage each time. The html doesn’t have a component.ts attached.
So is there a way to keep checking the session storage within the script tag in the html without having to refresh?

Facebook Login – Problem redirecting after confirming permission for user info

I need help for the last step of my Facebook login function.

The problem is that when a new user signs in for the first time, a popup called ‘www.facebook.com/v11.0/dialog/oauth’ appears which prompts the new user to confirm that they allow my page to access their information.

The issue is that once that user accepts the terms and confirms by clicking the ‘continue as name‘ button, instead of being booted to my home page like I wish it did, the users is kept on my login page instead. They then need to click a second time on the ‘Connect by Facebook’ button, which is now able to do its job and redirect my users to the proper page.

Basically I’m looking for a way to tell the Facebook login to prompt the redirect from the inside of the oauth popup and skip the need for a double click.

I have set up my access in JavaScript and my code looks like this:

    $(document).ready(function(){
      $('.login-main').on("click", ".facebook_login_class", function(){
          console.log('FACEBOOK LOGIN OPTION SELECTED');
                FB.getLoginStatus(function(res){
                    if(res.status == "connected" ){
                        console.log('Connected on Facebook');
                        FB.api('/me?fields=email,name,first_name,last_name', function(fbUser) {
                            $.ajax({
                                url:'facebook_login_ajax/',
                                method:'GET',
                                data:{
                                    email:fbUser.email,
                                    code:fbUser.id,
                                },
                                success:function(response){
                                    if (response.Success == true){
                                        window.location.href = '/myhomepage/';
                                    }
                                }
                            });
                        });
                    }else{
                        console.log('NOT CONNECTED!');
                        FB.login();
                    }
                    FB.getLoginStatus(function(response) {
                    });
                });

            });
      });

I figure the magic happens during the FB.login(); part of my function since that is where new users end up before they give me their authorization to use their data. I am still working on my JavaScript skills so I feel like I’m missing something quite simple.

Would any of you have an idea to solve this issue?

Thanks a lot

Jacascript Loop – Skip A Step based on a variable

I have a For loop with steps where I need to be able to skip a step if a value in a variable equals a certain text.

For example – in the below code I would like to skip step 0 if that var airport does not equal JFK:

var airport = 'JFK';

for (let step = 0; step < 2;
step++) {
rec.setCurrentSublistValue
({ sublistId: 'item', fieldId: 'item', value: 1261, forceSyncSourcing: true })
)

Sequelize query with nested array object json

I have data stored in a Postgres 11 table, one of the columns has a json object as it follows:

id data client_id
1 JSON BR_123
{
   "shed": false,
   "transactions": [
      {
         "id": 1,
         "value": 5000,
         "depositDate": "2021-09-20T10:29:05.000Z",
         "expirationDate": "2022-03-29T10:29:05.000Z",
         "requestDate": "2021-09-17T17:04:43.000Z"
      }
   ],
   "applies": false,
   "importValue": null,
   "depositValue": null
}

What I’m trying to do is select all of the entries that have a ‘transactions.value’ greater or equal than a given amount.

Sequelize:

const clients = await ComercialImports.findAll({
  where: {
    status: 'Running'
  },
  attributes: ['id', 'mode', 'importerId'],
  include: [
    {
      model: ComercialImportsTransactions,
      as: 'importTransaction',
      attributes: ['id', 'data', 'clientId'],
      required: true,
      where: {
        data: {
          transactions: {
            value: {
              [Op.gte]: 5000
            }
          }
        }
      }
    }
  ]
});

Unfortunately, for some reason this query won’t work, as it always return 0 results. I can’t seem to access any values stored on the transactions entry. All other entries are accessible (e.g. I can query for all data with ‘shed’ = true)

What am I doing wrong?

.append keeps appending even though if statement is false

Not sure why, but when clicking my button, my code keeps appending even though it appears the if statement is false after the first append?

In line 9, I am checking to see if any .tab class has an attr that does not equal my variable sysId. No matter what I do, it keeps appending. I want it to only append once IF a .tab doesn’t have an attribute of data-sysid= sysid already in place.

var recordHtml = '<div class="tab-content-record" data-sysid="">This is a record opened 
from the list.</div>';

// Open Record Tab
$(".tab-content-list-button").click(function () {
  var sysId = $(this).data('sysid');
  var title = $(this).data('title');
  var tabHtml = '<div class="tab record" data-sysid="' + sysId + '"><div class="tab-title">' + title + '</div><div class="close-tab">X</div></div>';

  if ($('.tab').attr('data-sysid') != sysId) {
    $(".tab-list").append(tabHtml);
  }

  //$(".tab-list").append(tabHtml);

})

Here is my fiddle that shows it working with the HTML & CSS: https://jsfiddle.net/fju60bca/1/

Making an HTML5 range slider input calculate in reverse in Javascript

Kind of a newby question, but I am not really. Just haven’t used the HTML5 range slider much.
Probably just some simple math that my brain currently is not triggering.

I have a range slider that goes from 0 – 100 and I am calculating the percentage so I can update the CSS opacity on some elements.

Anyways, I am doing an opacity update on elements on either side of the slider.
On the left side (0 value) I have the element on the left working with the range slider properly. It gets it calculation and properly adjusts its values. On the other side I would like the right side to do the opposite and when the range value is at 100.
I want the opacity of the element on the right to be 0 (CSS opacity: 0) when the range slider is at 100 and when the range slider is at 0, I want the element on the right to be 100% (or in CSS opacity:1.0).

My current code is as follows. I also have a JSFiddle.

AND yes I am still using jQuery so please spare the comments. Vanilla JS is fine to use as well. I appreciate the help.

  <div id="leftElement" class="opacityElement"></div>

<div id="rightElement" class="opacityElement"></div>

 <input type="range" min="0" max="100" value="50" id="slider">


 <script>
  var right = $('#rightElement');
  var left = $('#leftElement');
  var lastNum = 0;

 $(slider).on('input', function() {
  var v = $(this).val();
  onInput(v);
 });


 function onInput(value){
if(lastNum < value) {
    var parsedValue = parseInt(value);
    console.log("increasing");
  $(left).css('opacity', (parsedValue/100));

  console.log("increasing percentage" + (parsedValue/100));
}

if(lastNum > value) {
    var parsedValue = parseInt(value);
    console.log("decreasing");

 $(left).css('opacity', (parsedValue/100));

$(right).css('opacity', (parsedValue/100));

 console.log( "decreasing percentage" + (parsedValue/100));

}

lastNum = value;
console.log("onInput: " + value);
}

</script>




 //css
  <style>
     .opacityElement{width:100px; height:100px;display:inline-block}

   #rightElement{background:red}
   #leftElement{background:blue}
  </style>

Thank you

how i change the display of row from select to type=”checkbox”

i have this javascript code

$(rData.bouquets).each(function(rIndex) {
rTable.row.add([
                rData.bouquets[rIndex].id,
                rData.bouquets[rIndex].bouquet_name,
               ]);
});
<table id="datatable-review" class="table table-borderless mb-0">
<thead class="bg-light">
<tr>
<th class="text-center">ID</th>
<th class="text-center">Bouquet</th>
</tr>
</thead>
</table>

ho display the data in row like this

origianl display
enter image description here

now i need display this row like this with type=”checkbox”

display i want
enter image description here

how i can change this ?

thank you

I wanna let users google account login on a popup window, but it’s redirect

Hi I have a question about how to let users login by selecting their google account on a pop up window. They can login but it’s done by redirecting. I don’t wanna open a new page for logging in.

firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore"
import { getAuth, signOut, signInWithPopup, GoogleAuthProvider, onAuthStateChanged, sendEmailVerification } from "firebase/auth";
import { useState } from "react";


// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
export default getFirestore();
export const auth = getAuth(app);
const provider = new GoogleAuthProvider();
export const signInWithGoogle = () => {
  signInWithPopup(auth, provider)
    .then((res) => {
      console.log(res);
    }).catch((err) => {
      console.log(err);
    })
}

I exported the function for logging in and used it in Header.js

Header.js


import { Link } from 'react-router-dom';

import "../styles/Header.css"
import { signInWithGoogle, handleSignOut } from '../config/firebase';

const Header = ({user}) => {
  return (
    <div id='appHeader'>
      <div id="logo">
        <Link to="/">K!nN!ku Hub</Link>
      </div>
      <nav id="appNav">
        {/* instead of <a href="/"> */}
        {/* <Link to="/">Home</Link> */}
        <Link to="/kinniku-quiz/new">Create</Link>
        <Link to="/kinniku-quiz/">Home</Link>

        {/* <span onClick={signInWithGoogle}>Sign in</span> */}
        {user.username ? (
          <span className="imgLink">
            <Link to={{ pathname: `/profile/${user.uid}` }}>
              <img src={user.photoURL} alt="Your Profile Picture" />
            </Link>
          </span>
        ) : (
          <button id="signInBtn" onClick={signInWithGoogle}>Login</button>
        )}

      </nav>
    </div>
  )
};

export default Header;

Thanks for your effort here in advance. It still works, but I just don’t like redirecting:(

How To Generate A Full Sports League Schedule From A List Of All Possible Matchups

I have spent some time in JavaScript trying to develop a dynamic system that can take any even number of teams, generate all possible matches and create a full season schedule where there are no repeating teams or matches in a week or season.

I begin by setting some variables and functions getting all possible matches.

// Function to generate random round number 
function roundNumber(n) { 
    return Math.floor(Math.random() * n)
}

let teams = [];
let teamAmount = 6;
for (let i = 0; i < teamAmount; i ++){
  teams[i] = i
}
let gamesPlayed = [];
let home;
let away;
let possibleGames = [];
teamAmount = teams.length;
let totalMatches = (teamAmount/2)*(teamAmount-1);
//Genreate All Possible Matches
for (let i = 0; i < teamAmount; i++)
{
  for (let j = i + 1; j < teamAmount ; j++)
  {
    possibleGames.push([i, j]);
  }
}

Then I build the schedule with a for loop set to iterate for as many teams-1. There are as many games each week as number of teams/2. It finds a random round number from 0 to the length of possible matches and gets the matchup of teams. If that match has not occured yet the current week it passes and gets added to the schedule. The matchup is removed from all possible games. If the random match it gets includes a team that has already played that week then it keeps getting another matchup until not.

//Generate Weekly Schedule For Entire League
for (let w = 0; w < teamAmount-1; w ++){
  let g = 0;
  let teamsPlayed = [];
  console.log("Week " + (w+1) + "-----------------")
  while (g < (teamAmount/2)) {
    let r = roundNumber(possibleGames.length);
    let clear = false;
    //Check if teams have played this week, if not then clear them to be added
    if (!teamsPlayed.includes(possibleGames[r][0]) && 
        !teamsPlayed.includes(possibleGames[r][1])) {
      clear = true;
    }
    while (teamsPlayed.includes(possibleGames[r][0] &&
           teamsPlayed.includes(possibleGames[r][1]))){
      r = roundNumber(possibleGames.length);
    }
    //Get Random Game 'r' From Possible Games Left If It Includes Team 0-Length In Accending Order
    if (clear == true){
      for (let t = 0; t < teamAmount; t++){
        if (possibleGames[r].includes(t)){
          home = possibleGames[r][0];
          away = possibleGames[r][1];
        }
      }
    //Add To Played Games, Subtract From Games Left And Increment g
      gamesPlayed.push(possibleGames[r])
      teamsPlayed.push(possibleGames[r][0]);
      teamsPlayed.push(possibleGames[r][1]);
      possibleGames.splice(r, 1);
      console.log(home+"  vs  "+away)
      clear = false;
      g++
    } 
  }   console.log("Teams Played This Week: "+teamsPlayed);
}
console.log(gamesPlayed.length+" Unique Games Played of "+(totalMatches)+" Expected");
console.log(possibleGames.length+" Possible Games Left")

This method works only if the computer happens to put together a solvable schedule. In the following screenshot the problem is as follows:

Week1---
1v4
2v5
0v3
Week2---
1v3
0v2
4v5
Week3---
3v5
2v4
0v1
Week4---
3v4
1v5
--ERROR--
/*To satisfy the conditions placed, the only possible game that could be next 
is 0v2 but that has already been played in week 2. 

output screenshot

The computer can run into this problem at any point in the schedule building process. Sometimes it succeeds because it never creates a condition that cannot be solved. I guess the problem is that my conditions are unsolvable most of the time if done by random. Is this method over kill or am I missing something that could prevent an unsolvable schedule?

Normalize numbers for stats

I’m trying to make a simple daily stats like the screenshot below.

enter image description here

And here’s the code I’m using.

const normalize = ({ min, max, number }) => {
  return parseFloat((((number - min) / (max - min)) * 100).toFixed(2))
}

const activities = {
  '03-23-22': 2115,
  '03-24-22': 2128,
  '03-25-22': 2175,
  '03-26-22': 2195,
  '03-27-22': 2215,
  '03-28-22': 2206,
  '03-29-22': 2258
}

const numbers = []
for (const day in activities) {
  const stats = activities[day]
  numbers.push(stats)
}
const min = Math.min.apply(null, numbers)
const max = Math.max.apply(null, numbers)

for (const day in activities) {
  const activity = activities[day]
  const percent = normalize({ min, max, number: activity })
  console.log({ day, activity, percent })
}

As you can see on the console log the normalize function returns 0 for the minimum number and that’s why nothing is visible on the site.

What I’d like to do is I want to get some meaningful numbers from the normalize function to be able to show the stats in a more readable style. How do I do that?

Antd radio circle falls outside

I using radio button in React js App.
And lately i noticed that in radio button cicrle falls outside the button.
I thought maybe there are something wrong with margins, paddings.
But when i removed all margins, styles, classNames and so on.
Issue still didn’t dissapear.
When i tried to use the same ANTD component in another page, it was the same problem.
I didn’t use any specific styles in index.css
Did anyone had this issue before with ANTD Radio
Sorry i didn’t provide any code.
But i don’t even have anything to provide.
I literelly deleted everything that was possible

enter image description here

Remove node from vuetify v-treeview

I have a problem with code which remove selected node from the treeview component from Vuetify.

Component specification: here

Let’s say that I have deeply nested nodes and user can delete any of them. If clicks on parent then children also should be deleted.

const items = ref([
      {
        id: 1,
        name: 'A',
        slug: 'a',
        idp: '',
        children: [
          { id: 2, name: 'A 1', slug: 'a-1', idp: '1' },
          { id: 3, name: 'A 2', slug: 'a-2', idp: '1' },
          { 
            id: 4, 
            name: 'A 3', 
            slug: 'a-3', 
            idp: '1', 
            children: [
              { id: 5, name: 'B 1', slug: 'b-1', idp: '4' },
              { id: 6, name: 'B 2', slug: 'b-2', idp: '4' },
          ]},
        ],
       }

What I tried is to find out recursively the selected node.

const path = ref([])

function deleteNode(item, array) {
  for (let i = 0; i < array.length; i++) {
    if (array[i].id === item.id) {
      removeItem(i, items)
      break
    }
    if (array[i].children) {
      if (array[i].idp === '') {
        path.value = []
      }
      path.value.push(i)
      deleteNode(item, array[i].children)
    }
    if (array.length === 1 + i) {
      path.value.pop()
    }
  }
}

Then I tried to build the function to remove such item but my idea is wrong as it is eval which is not recommended so I try to figure out how to solve it differently. Could you help me, please? I am new in JS, I tried to find out solution but I didn’t found anything what could work for me.

function removeItem(index, array) {
  let executeRemoveFunction = ''
  for (let i = 0; i < path.value.length; i++) {
    if (i === 0) {
      executeRemoveFunction = `array.value[${path.value[i]}]`
    } else {
      executeRemoveFunction = `${executeRemoveFunction}.children[${path.value[i]}]`
    }
  }
  executeRemoveFunction = `${executeRemoveFunction
  }.children`
    + `.splice(${
      index
    }, 1)`
  const F = new Function(executeRemoveFunction)
  F()
}

Datatable jquery exceeds max stack size range error

I am developing a .net core 3.1 web application with mvc.
Currently I have DashboardController.cs, Index.cshtml and PublisherTable.cshtml.

I am trying to post an AJAX request with jquery, and the response should be the html string of GetTable.cshtml view.

My jquery request in index.cshtml :

 let dataArr = {
                startDate: ("start", $("#reportrange").data('daterangepicker').startDate.format('DD.MM.YYYY')),
                endDate: ("end", $("#reportrange").data('daterangepicker').endDate.format('DD.MM.YYYY')),
                apps: appFilterValue,
                countries: countryFilterValue,
                publishers: publisherFilterValue,
                dayBreakdown: dayBreakdown,
                weekBreakdown: weekBreakdown,
                monthBreakdown: monthBreakdown,
                yearBreakdown: yearBreakdown,
                publisherAppBreakdown: publisherAppBreakdown,
                adunitBreakdown: adunitBreakdown,
                countryBreakdown: countryBreakdown,
                publisherBreakdown: publisherBreakdown
            }

            $(".tableResult").html("");
            $(".tableResult").LoadingOverlay("show", { fade: [10, 10] });

            $.ajax({
                url: ajaxUrl,
                type: "POST",
                data: dataArr,
                success: function (data) {
                    var response = data;
                    if (response.error) {
                        $(".tableResult").LoadingOverlay("hide");
                        Swal.fire({ icon: 'error', title: response.message })
                        return;
                    } else {
                        $(".tableResult").LoadingOverlay("hide");
                        $(".tableResult").append(data);
                    }
                },
                error: function (data) {
                    $(".tableResult").LoadingOverlay("hide");
                    $(".tableResult").html("Internal server error " + data.status);
                }
            });
        }

Here is my controller which directs requests :

 [HttpPost("/Dashboard/GetTable")]
        public ViewResult GetTable(ReportCriteriaInputModel crit)
        {
            
            //Query criteria
            ReportCriteria Criteria = new ReportCriteria
            {
                StartDate = DateTime.ParseExact(crit.startDate, "dd.MM.yyyy", CultureInfo.InvariantCulture),
                EndDate = DateTime.ParseExact(crit.endDate, "dd.MM.yyyy", CultureInfo.InvariantCulture),
                Apps = crit.apps == null ? null : String.Join(",",crit.apps),
                Countries = crit.countries == null ? null : String.Join(",", crit.countries),
                PublisherList = crit.publishers == null ? null : String.Join(",", crit.publishers),
                Publisher = RedirectAction.user.Publisher,
                BreakdownByPublisherApp = crit.publisherAppBreakdown.ToString().Trim() == "1",
                BreakdownByAdunit = crit.adunitBreakdown.ToString().Trim() == "1",
                BreakdownByCountry = crit.countryBreakdown.ToString().Trim() == "1",
                BreakdownByPublisher = crit.publisherBreakdown.ToString().Trim() == "1",
                BreakdownByDay = crit.dayBreakdown.ToString().Trim() == "1",
                BreakdownByWeek = crit.weekBreakdown.ToString().Trim() == "1",
                BreakdownByMonth = crit.monthBreakdown.ToString().Trim() == "1",
                BreakdownByYear = crit.yearBreakdown.ToString().Trim() == "1"
            };


            //REPORT QUERIEZZ
            
            
            Report = FinderService.Instance.GetReport(Criteria);
            ReportTotal = FinderService.Instance.GetReportTotal(Criteria);

            //REport View Model
            ReportTableModel tableViewModel = new ReportTableModel
            {
                ReportTotal = ReportTotal,
                Report = Report,
                BreakdownByPublisherApp = Criteria.BreakdownByPublisherApp,
                BreakdownByPublisher = Criteria.BreakdownByPublisher,
                BreakdownByCountry = Criteria.BreakdownByCountry,
                BreakdownByDay = Criteria.BreakdownByDay,
                BreakdownByMonth = Criteria.BreakdownByMonth,
                BreakdownByWeek = Criteria.BreakdownByWeek,  
                BreakdownByYear = Criteria.BreakdownByYear,
                BreakdownByAdunit = Criteria.BreakdownByAdunit,
            };

            return View("~/Views/Dashboard/PublisherTable.cshtml",tableViewModel);

And this is my table to be added into to Index.cstmhl :

@{

    Hashtable total = (Hashtable)Model.ReportTotal[0];
    var cul = CultureInfo.InvariantCulture;
}


<style>
     td, th {
        padding: .50rem !important;
        padding-right: 20px !important;
    }

    .totalrow td {
        padding-right: 0px;
        padding: .75rem !important;
        text-align: right;
        font-weight: bold;
    }

    .dataTable {
        width: 100% !important;
    }
    .dtButtons{
        margin-left: 8%;
    }
    .btnTable {
        color: black;
        background-color: white;
    }
</style>

@*DÜZELT*@

<div class="table-wrapper table-responsive">
    <table class="table table-hover table-condensed" id="dTable">
        <thead>
            <tr class="real-th-tr">

                @if (Model.BreakdownByDate)
                {
                    <th class="bd" data-sort-dir="desc">Date</th>
                }
                @if (Model.BreakdownByPublisherApp)
                {
                    <th class="bd">Publisher App</th>
                }
                @if (Model.BreakdownByPublisher)
                {
                    <th class="bd">Publisher</th>
                }
                @if (Model.BreakdownByAdunit)
                {
                    <th class="bd" style="width:200px">Adunit Name</th>
                    <th class="bd">Adunit ID</th>
                }
                @if (Model.BreakdownByCountry)
                {
                    <th class="bd">Country</th>
                }
                
                <th class="text-right bd">Impression</th>
                <th class="text-right bd">Revenue</th>
            </tr>

            <tr class="total-row totalrow" style="background-color:#f4f6f9">

                @if (Model.BreakdownByDate)
                {
                    <td></td>
                }
                @if (Model.BreakdownByPublisherApp)
                {
                    <td></td>
                }
                @if (Model.BreakdownByPublisher)
                {
                    <td></td>
                }
                @if (Model.BreakdownByAdunit)
                {
                    <td></td>
                    <td></td>
                }
                @if (Model.BreakdownByCountry)
                {
                    <td></td>
                }

                <td data-col="impression">@(Convert.ToDouble(total["total_impression"]).ToString("N0",cul))</td>
                <td data-order="@((Convert.ToDouble(total["total_revenue"])).ToString("F2"))" data-col="revenue">$ @((Convert.ToDouble(total["total_revenue"])).ToString("N2", cul))</td>
            </tr>

        </thead>
        <tbody>


            @foreach (Hashtable h in Model.Report)
            {

            <tr>
                @if (Model.BreakdownByDate)
                {
                    <td style="text-align: left" data-order="@(((DateTime)h["date_trunc"]).ToString("yyyyMMdd"))">@(((DateTime)h["date_trunc"]).ToString("dd.MM.yyyy")) </td>
                }

                @if (Model.BreakdownByPublisherApp)
                {
                    <td style="text-align: left">@h["app_name"]</td>
                }
                @if (Model.BreakdownByPublisher)
                {
                    <td style="text-align: left">@h["publisher_name"]</td>
                }
                @if (Model.BreakdownByAdunit)
                {
                    <td style="text-align: left">@h["adunit_name"]</td>
                    <td style="text-align: left">@h["adunit_id"]</td>
                }
                @if (Model.BreakdownByCountry)
                {
                    <td style="text-align: left">@h["country"]</td>
                }
                <td style="text-align: right" data-col="impression">@(Convert.ToDouble(h["total_impression"]).ToString("N0",cul))</td>
                <td style="text-align: right" data-col="revenue" data-order="@((Convert.ToDouble(h["total_revenue"])).ToString("F2"))">$ @((Convert.ToDouble(h["total_revenue"])).ToString("N2", cul))</td>
            </tr>
            }
        </tbody>
    </table>
</div>

<script>
    @{
        double tempDouble = 1.1;
    }

    function whatDecimalSeparator() {
        var n = "@tempDouble.ToString("N1",cul)";
        n = n.substring(1, 2);
        return n;
    }
    var decimalsep = whatDecimalSeparator();
    var thousandsep = decimalsep == "," ? "." : ",";

    $('.select2bs4:not(.ajax-select)').select2({
        theme: 'bootstrap4'
    });

    $(document).ready(function () {
        var bdCount = @Model.TotalBreakdownCount;
        var orderColNo = 0;
        var aoColumnsList = [];
      
        for (var i = 0; i < bdCount; i++) {
            if ($($("th.bd")[i]).attr("data-sort-dir") == "desc") {
                aoColumnsList.push({ "orderSequence": ["desc", "asc"] });
            }
            else {
                aoColumnsList.push(null);
            }            
        }
        for (var i = 0; i < $(".real-th-tr th").length - bdCount; i++) {
            aoColumnsList.push({ "orderSequence": ["desc", "asc"] });
        }
        aaSorting = [];
        aaSorting = [[orderColNo, 'desc']];

        // DataTable
        //<"col dtButtons"B>
       
        var table = $('#dTable').DataTable({
        
        dom: '<"row"<"col"l><"col dtButtons"B><"col"f>>rt<"row"<"col-6"i><"col-6"p>>',
        //buttons: [
        //    {
        //        //text : "CSV",
        //        className: "btnTable"
        //    },
        //    {
        //        //extend: 'excelHtml5',
        //        text: 'Excel',
        //        className: 'btnTable',
        //        action: function (data) {
        //            debugger;
        //            var currencySign = "@Reklamup.Admin.Helpers.PresentationHelper.PrintCurrency(Model.Currency)";
        //            for (var i = 0; i < data.body.length; i++) {
        //                for (var j = 0; j < data.body[i].length; j++) {
        //                    if (j < bdCount) continue;                                
        //                    var dataCell = data.body[i][j];
        //                    data.body[i][j] = dataCell.replace(currencySign, "").split(thousandsep).join("_thousand_").split(decimalsep).join("_decimal_").split("_thousand_").join(",").split("_decimal_").join(".").trim();
        //                }                            
        //            }                        
        //        }
        //    },
        //    {
        //        //text: "PDF",
        //        className: "btnTable"
        //    },
        //    {
        //        //text: "Print",
        //        className: "btnTable"
        //    },
        //],
        
        buttons: [
            {
                extend: 'excelHtml5', className: 'btnTable', text: '<i class="fa fa-file-excel-o" aria-hidden="true"></i> Excel',
                exportOptions:
                {
                    columns: ':visible'
                },
                title: '',
                customizeData: function (data) {
                    debugger;
                    var currencySign = "@Reklamup.Admin.Helpers.PresentationHelper.PrintCurrency(Model.Currency)";
                    for (var i = 0; i < data.body.length; i++) {
                        for (var j = 0; j < data.body[i].length; j++) {
                            if (j < bdCount) continue;                                
                            var dataCell = data.body[i][j];
                            data.body[i][j] = dataCell.replace(currencySign, "").split(thousandsep).join("_thousand_").split(decimalsep).join("_decimal_").split("_thousand_").join(",").split("_decimal_").join(".").trim();
                        }                            
                    }                        
                }
            },
            { 
                extend: 'pdfHtml5', 
                className: 'btnTable', 
                exportOptions:
                {
                    columns: ':visible'
                },                    
                pageSize: 'A2',
                text: 'PDF'
            },

            { extend: 'csv', className: 'btnTable', text: '<i class="fa fa-file-o" aria-hidden="true"></i> CSV' },
            { extend: 'print', className: 'btnTable', text: '<i class="fa fa-print" aria-hidden="true"></i> Print' }
        ],
            
        order: aaSorting,
        "orderCellsTop": true,
        iDisplayLength: 25,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "search": {
            "caseInsensitive": true
        },
        "language": {
            "decimal": ".",
            "thousands": ","
        },
        "aoColumns": aoColumnsList
            
    });
        


    });

I achieve that, but when I try to load the table, it says this for over 50k records :

jquery.min.js:2 jQuery.Deferred exception: Maximum call stack size exceeded RangeError: Maximum call stack size exceeded
at Function.se [as find] (http://localhost:34150/plugins/jquery/jquery.min.js:2:6529)
at S.fn.init.find (http://localhost:34150/plugins/jquery/jquery.min.js:2:25047)
at HTMLTableElement. (http://localhost:34150/plugins/datatables/jquery.dataTables.min.js:104:264)
at Function.each (http://localhost:34150/plugins/jquery/jquery.min.js:2:3003)
at S.fn.init.each (http://localhost:34150/plugins/jquery/jquery.min.js:2:1481)
at S.fn.init.u [as dataTable] (http://localhost:34150/plugins/datatables/jquery.dataTables.min.js:98:199)
at S.fn.init.l.fn.DataTable (http://localhost:34150/plugins/datatables/jquery.dataTables.min.js:187:371)
at HTMLDocument. (:37:34)
at e (http://localhost:34150/plugins/jquery/jquery.min.js:2:30038)
at t (http://localhost:34150/plugins/jquery/jquery.min.js:2:30340) undefined

I tried almost everything that I saw on the internet but I could not solve this problem. Has anyone encountered a problem like this?

Any help would be great.

Best regards

How to add script in package.json for deploying multiple localhosts servers in single app in nodejs heroku?

How to add script in package.json for deploying multiple localhosts servers in single app in nodejs heroku ?
Suppose in my main project folder I have 2 game folders ( game1 (running on localhost:3000) and game2 (running on localhost:5000) ) and my main website ( running on localhost:8080).
So for running my complete project I perform 1) node server.js 2) node ./game1/server.js
3) node ./game2/server.js . But while deploying project on heroku we add "start" : "node server.js" in scripts in package.json . So my question is how to add "node ./game1/server.js " this also in package.json ?

Jquery code does not run inside an async function

I’m sure I’m doing something wrong that’s super simple, but I can’t figure out what.

Goal: I’m showing a loading modal while processing a card payment with stripe. But if the user enters in something incorrect such as no expiration date or something similar, I’d like the loading modal to close and allow the user to fix their problem.

Issue: The loading modal is just staying open indefinitely, when I tell it to hide the modal, it does nothing.

I have a feeling maybe because it’s calling it from an async function it doesn’t wanna do what it’s told? I am a novice to Javascript and JQuery so if it’s simple, could you explain why?

enter image description here

Here is the Pay with card method:

// Submit payment
// Calls stripe.confirmCardPayment
// If the card requires authentication Stripe shows a pop-up modal to
// prompt the user to enter authentication details without leaving your page.
var payWithCard = async function (stripe, card, clientSecret) {
    stripe
        .confirmCardPayment(clientSecret, {
            payment_method: {
                card: card,
                billing_details: {
                    name: billingAddressStuff.strName,
                    address: {
                        line1: billingAddressStuff.strStreet1,
                        line2: billingAddressStuff.strStreet2,
                        postal_code: billingAddressStuff.strZip,
                        state: billingAddressStuff.strStateName,
                    },
                    email: billingAddressStuff.strEmail
                }
            }
        })
        .then(function (result) {
            if (result.error) {
                $("#loadMe").modal("hide");        // This is what is not doing anything when it's called
                // Show error to your customer
                showError(result.error.message);
                return false;
            } else {
                // The payment succeeded! now process the order
                document.getElementById("TheSubmitButton").disabled = true;
                PlaceOrder();
                return true;
            }
        });
};

Here is what calls the pay with card:

// On submit, pay with card!
        var form = document.getElementById("payment-form");
        form.addEventListener("submit", function (event) {
            event.preventDefault();

            // Show loader
            $("#loadMe").modal({
                backdrop: "static", //remove ability to close modal with click
                keyboard: false, //remove option to close with keyboard
                show: true //Display loader!
            });

            // Complete payment when the submit button is clicked
            
            // get billing info                 
            billingAddressStuff.strName = document.getElementById("strBillName").value;
            billingAddressStuff.strCompanyName = document.getElementById("strBillCompanyName").value;
            billingAddressStuff.strStreet1 = document.getElementById("strBillAddress").value;
            billingAddressStuff.strStreet2 = document.getElementById("strBillAddress2").value;
            billingAddressStuff.strCity = document.getElementById("strBillCity").value;
            billingAddressStuff.strStateName = document.getElementById("strBillState").value;
            billingAddressStuff.strZip = document.getElementById("strBillZip").value;
            billingAddressStuff.strPhone = document.getElementById("strBillPhone").value;
            billingAddressStuff.strEmail = document.getElementById("strBillingEmail").value;

            // else, save locally
            document.getElementById("TotalsModel").PI.value = data.clientSecret;

            // check stock and prices before charging the card
            var StockIsGood = false;
            var PriceIsGood = false;
            var AllItemsActive = false;

            StockIsGood = CheckStock();
            PriceIsGood = CheckPrice();
            AllItemsActive = CheckActiveItems();

            // if all good, then continue and process the payment at the given price.
            if (StockIsGood && PriceIsGood && AllItemsActive) {

                payWithCard(stripe, card, data.clientSecret);

            }
            else {
                $("#loadMe").modal("hide");
            }
            
        });