My AJAX call keeps failing for unknown reason?

I’ve created simple form inside of modal and to do so I am using AJAX calls + php.
Now, my AJAX call is constantly failing and I don’t know why.
This simple form is for nothing else but for updating password inside of database

Here’s my JS:

function myFunction() {
  var x = document.getElementById("password");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}


 
var password = document.getElementById("password"), 
confirm_password = document.getElementById("confirmPassword");

document.getElementById('signupLogo').src = "https://www.shselektronika.com/v2/wp-content/uploads/2020/09/shs-elektronika-140.png";
enableSubmitButton();

function validatePassword() {
  if(password.value != confirm_password.value) {
    confirm_password.setCustomValidity("Šifre se ne podudaraju");
    return false;
  } else {
    confirm_password.setCustomValidity('');
    return true;
  }
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

function enableSubmitButton() {
  document.getElementById('submitButton').disabled = false;
  document.getElementById('loader').style.display = 'none';
}

function disableSubmitButton() {
  document.getElementById('submitButton').disabled = true;
  document.getElementById('loader').style.display = 'unset';
}

function validateSignupForm() {
  var form = document.getElementById('signupForm');
  
  for(var i=0; i < form.elements.length; i++){
      if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
        console.log('Niste ispunili sva polja!');
        return false;
      }
    }
  
  if (!validatePassword()) {
    return false;
  }
  
  onSignup();
}

function onSignup() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    
    disableSubmitButton();
    
    if (this.readyState == 4 && this.status == 200) {
      enableSubmitButton();
    }
    else {
      console.log('AJAX call failed!');
      setTimeout(function(){
        enableSubmitButton();
      }, 1000);
    }
    
  };
  
  xhttp.open("GET", "changepassword.php", true);
  xhttp.send();
}

I’m constantly getting AJAX call failed! inside of console.

Here’s my HTML:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Promijenite Vašu šifru
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Promjena šifre</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
         <!-- FORM STARTS HERE -->
         <div class="mainDiv">
  <div class="cardStyle">
    <form action="changepassword.php" method="post" name="signupForm" id="signupForm">
      
      <img src="" id="signupLogo"/>
      
      <h2 class="formTitle">
        Promijenite Vašu šifru
      </h2>
      
    <div class="inputDiv">
      <label class="inputLabel" for="password">Nova šifra</label>
      <input type="password" id="password" name="password" placeholder="Vaša nova šifra" required>
    </div>


    <div class="inputDiv checkRemember">
    <input type="checkbox" class="uniform" name="remember" id="chkRememberMe" onclick="myFunction()">
    <label for="chkRememberMe">
        <span>Prikaži šifru</span>
    </label>
    </div> 
    <input type="hidden" id="postId" name="postId" value="<?=$current_userID?>">
    <div class="inputDiv">
      <label class="inputLabel" for="confirmPassword">Potvrdite novu šifru</label>
      <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Ponovo unesite novu šifru">
    </div>
    
    <div class="buttonWrapper">
      <button type="submit" id="submitButton" onclick="validateSignupForm()" class="submitButton pure-button pure-button-primary">
        <span>Promijenite šifru</span>
        <span id="loader"></span>
      </button>
    </div>
      
  </form>
  </div>
</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zatvorite</button>

INCLUDES:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="navbar-handler.js"></script>
<script src="passwordChange.js"></script>

MapboxGL, multiple layers performance issue

here is my problem:

Premise:
I have a set of data (stops on the map)loaded via geoJSON in a clustered source,
each of these stop locations can have a different icon.

I have over 140 variations of icons.
I am iterating through all of them and I generate a “symbol” type layer for each one.

Also, I am loading each stop icon image(png format) via map.loadImage().

The issue that I am facing is that the loading time is very high and the map isn’t smooth until all the layers are loaded and displayed.

Can you please help me with a suggestion on how to reduce the loading time and increase the performance?

How does function within addEventListener gets hoisted?

I found a weird behavior that I couldn’t understand even reading MDN doc about hoisting.
It says that functions and variables gets moved to the top of the scope except variable initialization. So how does below code work?

const element = document.getElementById('#el');

element.addEventListener('click', function() {
   console.log(myVariable); // 'myValue'
});

const myVariable = 'myValue'; // Variable initialization.

As you can see, the myVariable initalization happens after the anonymous function for click event listener.

Lower the variable without impact database variable

I would like to know if it is possible to lower the quantity without touching the database because here I would like the quantity variable to decrease but without updating the database. Indeed, the variable remains constant and does not reach zero if I do not update in the database with each click of the button.

Here is my code :

 db.query("SELECT * FROM articles WHERE id_article = ?",
          [[req.articleId]],
          function (err, result) {
              if (err) throw err;

              let quantity = result[0].quantite - 1;
              if (result[0].quantite < 1) {
              } else {
                  db.query("UPDATE articles SET quantite = ? WHERE id_article = ?", [quantity, req.articleId], function (err, result) { // I want to know if it's possible to make that without directly update the database...
                      if (err) throw err;
                  })

                  let token = req.headers['x-access-token'] || req.headers['authorization'] || req.cookies.token;

                  db.query("SELECT quantite FROM panier_item WHERE id_article = ? AND id_user = ?", [req.articleId, parseJwt(token).userId], function (err, result) {
                      if (err) throw err;
                      console.log(result[0])
                      if (result[0] === undefined) {
                          db.query("INSERT INTO panier_item(id_article,id_user,quantite) VALUES (?)", [[req.articleId, parseJwt(token).userId, 1]], function (err, result) {
                              if (err) throw err;
                          })
                      } else {
                          db.query("UPDATE panier_item SET quantite = ? WHERE id_article = ? AND id_user = ?", [result[0].quantite + 1, req.articleId, parseJwt(token).userId], function (err, result) {
                              if (err) throw err;
                          })
                      }
                  })
              }

Thanks you everyone,

How to reorder an API call to a custom order by API ID?

A bit of a niche question but it has challenged me, see if you can solve it.

I have this array of sports leagues ranked from best to worst by their respective API IDs.

const arrOrderedLeague = [1, 2, 3, 4, 5, 6, 7, 9, 10, 29, 30, 31, 32, 33, 
    34, 39, 45, 48, 140, 142, 135, 137, 78, 81, 61, 65, 66, 88,
    94, 96, 253, 203, 262, 179, 185, 144, 188, 169, 40, 41, 42,
    43, 235, 207, 218, 141, 136,333, 307, 197, 62, 79, 80, 128, 
    130, 292, 98, 101, 103, 106, 113, 119, 283, 71, 73, 265, 239, 211, 89 ]

All though the number 89 is lower than 211, 211 is the better league.

The issue is when I call the API it follows a random order. I am considerably weak when it comes to arrays so how would I make it follow the order I want?

Extra Info:

This is a console.log of the API Call, as you can see, league 73 is logged before 262, but since league 262 comes earlier in my array than 73, I want it to be logged ahead, this likely requires making a new array with some function unknown to me but I’m not sure what it is.

2: Object { fixture: {…}, league: {…}, teams: {…}, … }
​​
fixture: Object { id: 854430, referee: "Savio Pereira Sampaio, Brazil", timezone: "UTC", … }
​​
goals: Object { home: 3, away: 0 }
​​
league: Object { **id: 73**, name: "Copa Do Brasil", country: "Brazil", … }
​​
score: Object { halftime: {…}, fulltime: {…}, extratime: {…}, … }
​​
teams: Object { home: {…}, away: {…} }
​​
<prototype>: Object { … } 

3: Object { fixture: {…}, league: {…}, teams: {…}, … }
​​
fixture: Object { id: 861506, referee: "Jorge Antonio Perez Duran, Mexico", timezone: "UTC", … }
​​
goals: Object { home: 1, away: 2 }
​​
league: Object { **id: 262**, name: "Liga MX", country: "Mexico", … }
​​
score: Object { halftime: {…}, fulltime: {…}, extratime: {…}, … }
​​
teams: Object { home: {…}, away: {…} }
​​
<prototype>: Object { … }
​

Less Needed but here is the API Call itself:

const settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://v3.football.api-sports.io/fixtures?date=2022-05-13",
    "method": "GET",
    dataType: 'json',
    "headers": {
        "X-RapidAPI-Host": "v3.football.api-sports.io",
        "X-RapidAPI-Key": "API-KEY"
    }
};
$.ajax(settings).done(function (data) {

    const newArr = data.response.filter(el => arrWant.includes(el.league.id));
    console.log(newArr)
    });

If you need any clarification please leave a comment, thanks for anyone who even tries!

cypress test asserting a filtering operation on array of objects expecting undefined

I have a cypress test over an API. When I do

cy.getUnits(u.email)

I’m expecting a 200 OK response similar to this in the body of the response

{
  “units”: [
 {
      “store: “US_1234567890”,
      “role”: “user”,
      “email”: “[email protected]”
    },
   {
     “store: “CA_865890X”,
      “role”: “admin”,
     “email”: “[email protected]”
   }
  ]
}

I’m expecting that list of units doesn’t contain the unit “u” below

const u =    {
     “store: ” US_56890765",
      “role”: “admin”,
      “email”: “[email protected]”
   }

So in cypress, I did

cy.getUnits(u.email)
 .should(response => expect(response.status).to.equal(200))
 .its(‘body’)
 .should(units => {
  expect(units.length).to.equal(2)
  units.filter(
   unit =>
    unit.email === u.email &&
    unit.role === u.role &&
    unit.store === u.store,
  ).should.be.undefined
 })

That is not working

units.filter(
       unit =>
        unit.email === u.email &&
        unit.role === u.role &&
        unit.store === u.store,
      ).should.be.undefined

I have tried different variations to no avail.

Could someone please help me find a solution to this?

I really appreciate any help you can provide.

Animation to center a div in the window

Hi I need an animation that makes a div go from left to center, but it doesn’t work.
This is my code:

$(document).ready(function () {
        $(log).click(function () {
            var number = $(window).width() / 2;
            $(registrationDiv).animate({ left: number }, 200);
            $(registrationDiv).show();
            $(loginDiv).hide();
        });
    });

this code puts the div slightly to the right and not at center.

Chart.js Uncaught TypeError: Cannot read properties of undefined (reading ‘options’)

I have created a Dashboard on which I have multiple charts this chart is one of those charts and it is giving errors. Visually the chats is displaying perfect but the Buttons are not working.

Please check my code and Run the code Snippet and see by clicking on Today Monthly Yearly Buttons it is giving an error how to resolve the error where I am doing wrong in it.

const days = [{
    x: Date.parse('2022-05-01 00:00:00 UTC+05:00'),
    y: 18
  },
  {
    x: Date.parse('2022-05-02 00:00:00 UTC+05:00'),
    y: 12
  },
  {
    x: Date.parse('2022-05-03 00:00:00 UTC+05:00'),
    y: 6
  },
  {
    x: Date.parse('2022-05-04 00:00:00 UTC+05:00'),
    y: 9
  },
  {
    x: Date.parse('2022-05-05 00:00:00 UTC+05:00'),
    y: 12
  },
  {
    x: Date.parse('2022-05-06 00:00:00 UTC+05:00'),
    y: 3
  },
  {
    x: Date.parse('2022-05-07 00:00:00 UTC+05:00'),
    y: 9
  },
];
const months = [{
    x: Date.parse('2022-01-01 00:00:00 UTC+05:00'),
    y: 20
  },
  {
    x: Date.parse('2022-02-01 00:00:00 UTC+05:00'),
    y: 40
  },
  {
    x: Date.parse('2022-03-01 00:00:00 UTC+05:00'),
    y: 10
  },
  {
    x: Date.parse('2022-04-01 00:00:00 UTC+05:00'),
    y: 30
  },
  {
    x: Date.parse('2022-05-01 00:00:00 UTC+05:00'),
    y: 5
  },
  {
    x: Date.parse('2022-06-01 00:00:00 UTC+05:00'),
    y: 20
  },
  {
    x: Date.parse('2022-07-01 00:00:00 UTC+05:00'),
    y: 15
  },
  {
    x: Date.parse('2022-08-01 00:00:00 UTC+05:00'),
    y: 0
  },
  {
    x: Date.parse('2022-09-01 00:00:00 UTC+05:00'),
    y: 60
  },
  {
    x: Date.parse('2022-10-01 00:00:00 UTC+05:00'),
    y: 55
  },
  {
    x: Date.parse('2022-11-01 00:00:00 UTC+05:00'),
    y: 3
  },
  {
    x: Date.parse('2022-12-01 00:00:00 UTC+05:00'),
    y: 10
  },
];
const years = [{
    x: '2018',
    y: '15'
  },
  {
    x: '2019',
    y: '5'
  },
  {
    x: '2020',
    y: '25'
  },
  {
    x: '2021',
    y: '50'
  },
  {
    x: '2022',
    y: '40'
  },
];
//for Income
const days1 = [{
    x: Date.parse('2022-05-01 00:00:00 UTC+05:00'),
    y: 12
  },
  {
    x: Date.parse('2022-05-02 00:00:00 UTC+05:00'),
    y: 18
  },
  {
    x: Date.parse('2022-05-03 00:00:00 UTC+05:00'),
    y: 9
  },
  {
    x: Date.parse('2022-05-04 00:00:00 UTC+05:00'),
    y: 6
  },
  {
    x: Date.parse('2022-05-05 00:00:00 UTC+05:00'),
    y: 3
  },
  {
    x: Date.parse('2022-05-06 00:00:00 UTC+05:00'),
    y: 12
  },
  {
    x: Date.parse('2022-05-07 00:00:00 UTC+05:00'),
    y: 7
  },
];
const months1 = [{
    x: Date.parse('2022-01-01 00:00:00 UTC+05:00'),
    y: 40
  },
  {
    x: Date.parse('2022-02-01 00:00:00 UTC+05:00'),
    y: 0
  },
  {
    x: Date.parse('2022-03-01 00:00:00 UTC+05:00'),
    y: 13
  },
  {
    x: Date.parse('2022-04-01 00:00:00 UTC+05:00'),
    y: 20
  },
  {
    x: Date.parse('2022-05-01 00:00:00 UTC+05:00'),
    y: 4
  },
  {
    x: Date.parse('2022-06-01 00:00:00 UTC+05:00'),
    y: 30
  },
  {
    x: Date.parse('2022-07-01 00:00:00 UTC+05:00'),
    y: 20
  },
  {
    x: Date.parse('2022-08-01 00:00:00 UTC+05:00'),
    y: 40
  },
  {
    x: Date.parse('2022-09-01 00:00:00 UTC+05:00'),
    y: 20
  },
  {
    x: Date.parse('2022-10-01 00:00:00 UTC+05:00'),
    y: 50
  },
  {
    x: Date.parse('2022-11-01 00:00:00 UTC+05:00'),
    y: 30
  },
  {
    x: Date.parse('2022-12-01 00:00:00 UTC+05:00'),
    y: 20
  },
];
const years1 = [{
    x: '2018',
    y: '40'
  },
  {
    x: '2019',
    y: '50'
  },
  {
    x: '2020',
    y: '25'
  },
  {
    x: '2021',
    y: '5'
  },
  {
    x: '2022',
    y: '15'
  },
];

const chartfour = {
  type: 'bar',
  data: {
    //labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [{
        label: 'Expense',
        data: days,
        backgroundColor: [
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB',
          '#21BADB'
        ],
      },

      {
        label: 'Other Income',
        data: days1,
        backgroundColor: [
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53',
          '#01AF53'
        ],
      }


    ]
  },

  options: {

    plugins: {
      legend: {
        display: true,
        labels: {
          boxWidth: 60,
          boxHeight: 20,
        }
      }
    },

    scales: {
      y: {
        display: true,
        beginAtZero: true
      },
      x: {
        display: true,
        beginAtZero: false,
        type: 'time',
        time: {
          unit: 'day'
        }
      }
    }
  }
};


const ctxFour = document.getElementById('myChart2').getContext('2d');
new Chart(ctxFour, chartfour);

function timeFrame2(period) {
  console.log(period.value);
  if (period.value == "days") {
    myChart2.chartfour.options.scales.x.time.unit = period.value;
    myChart2.chartfour.data.datasets[4].data = days;
    myChart2.chartfour.data.datasets[5].data = days1;
  }
  if (period.value == 'months') {
    myChart2.chartfour.options.scales.x.time.unit = period.value;
    myChart2.chartfour.data.datasets[0].data = months;
    myChart2.chartfour.data.datasets[1].data = months1;
  }
  if (period.value == 'years') {
    myChart2.chartfour.options.scales.x.time.unit = period.value;
    myChart2.chartfour.data.datasets[0].data = years;
    myChart2.chartfour.data.datasets[1].data = years1;
  }
  myChart2.update();
};
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0-beta1/css/bootstrap.min.css" />
</head>

<body>
  <div class="col-5 d-flex justify-content-end">
    <button class="active btn btn-outline-primary btn-sm ps-4 pe-4 fw-bold me-2" onclick="timeFrame2(this)" value="days">Today</button>
    <button class="btn btn-outline-primary btn-sm ps-4 pe-4 fw-bold me-2" onclick="timeFrame2(this)" value="months">Monthly</button>
    <button class="btn btn-outline-primary btn-sm ps-4 pe-4 fw-bold" onclick="timeFrame2(this)" value="years">Yearly</button>
  </div>

  <div class="col-12" style="display: block; box-sizing: border-box; height: 211px">
    <canvas id="myChart2" width="825" height="211" style="display: block; box-sizing: border-box; height: 211px; width: 250.5px;"></canvas>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0-beta1/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

  <script>
    $(document).on('click', 'button', function() {
      $(this).addClass('active').siblings().removeClass('active')
    })
  </script>
</body>

</html>

API JSON Request Value Undefined

This is my code:

for(let i = 1; i <= 10; i++) {
  fetch(`https://pokeapi.co/api/v2/pokemon/${i}`)
  .then(res => res.json())
  .then(res => {
    console.log(res.types.forEach(element => element.type.name))})}

For some reason it keeps returning an undefined value whereas if I do

console.log(res.types[0].type.name)

It works just fine.

I’m fairly certain my error is probably in how I’m building my forEach but that hits the point of where I have no clue what I’m doing wrong. Probably a silly question so I’d appreciate some enlightment! Thanks in advance 😉

How can I get the indexes of a filtered array items

I have this situation, I have an array and I need to filter it and get the indexes of the filtered items, like this example:

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];

I’m using this filter:

var filter = arr.filter(e => e.split("-")[0] == '2022'); //To get the values from 2022

And I get this result:

filter = ['2022-05', '2022-04', '2022-02'];

What I need to do now is to get also the index of these items, so it would be this:

filter = ['2022-05', '2022-04', '2022-02'];
index = [0,2,3]

How can I do that? Thanks.

JS table sorting fail on Chrome

I am working on a website that allow people to participate in an online race on erg rowers.

I display a large table (600+ rows) containing rank, name and other fields, and I want to allow visitors to sort it on the fly (client-side JS).
I set up a function that works really well on Firefox, but it doesn’t work at all on Chrome browsers.

I really don’t see what part of my code can bring this problem, this is why I reach to you for some help !

My html code looks like:

<table>
  <thead>
    <tr>
      <th>Rank</th>
      <th>Name</th>
      <th>...</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>USER 1</td>
      <td>...</td>
    </tr>
  </tbody>
</table>

And my JavaScript:

for (const table of document.getElementsByTagName('table')) {
  const headers = table.querySelectorAll('thead tr th');
  for (let i = 0; i < headers.length-1; i++) {
    headers[i].addEventListener('click', sortTable(i, table.id));
  }
}

function sortTable(n, tableId) {
  return () => {
    const table = document.getElementById(tableId);

    const newTable = document.createElement('table');
    newTable.className = table.className;
    newTable.id = table.id;

    const tbody = document.createElement('tbody');
    const thead = document.createElement('thead');

    const rows = Array.from(table.rows);
    thead.appendChild(rows.shift());
    const th = thead.getElementsByTagName('th');

    const dir = th[n].className == 'asc' ? 'desc' : 'asc';

    rows.sort((a, b) => {
      let x = a.getElementsByTagName('td')[n].innerText.toLowerCase();
      let y = b.getElementsByTagName('td')[n].innerText.toLowerCase();

      const compare = x.localeCompare(y, 'fr', { sensitivity: 'base', numeric: true });

      return ((dir == 'asc' && compare > 0) || (dir == 'desc' && compare < 0));
    })
      .forEach(row => tbody.appendChild(row));

    for (const header of th) {
      header.className = '';
    }

    th[n].className = dir;

    newTable.appendChild(thead);
    newTable.appendChild(tbody);

    table.parentNode.replaceChild(newTable, table);
  };
}

Thanks for your help !

New url is not opened in a new tab

I have this code :

<b-btn
   variant="primary"
   class="btn-sm"
   :disabled="updatePending || !row.enabled"
   @click="changeState(row, row.dt ? 'activate' : 'start')">
   Activate
 </b-btn>

 ...........
 methods: {
    async changeState(channel, newMode) {
      const { id, type } = channel;
      const data = await this.cultBaySsoToken();
      window.open("https://en.wikipedia.org/", "_blank");
      return;
 }

When click on button, a new tab is not opened; Please help me what can be the problem