Codeigniter 4 call database inside javascript

I am new to codeigniter 4, and i am using javascript to display the error message using keyup function. The user should register unique username. how can i check the database if username is already taken?

note: without pressing the sign up button(I already try “rules”, but it is need to click the button). the error must display as long as he type his username. This is my EXAMPLE in matching password, and it is already done. myproblem now is checking the database username.

**myrepassword.onkeyup = function() {
  if(myrepassword.value.match(myInput.value)) {  
    repassword.classList.remove("invalid");
    repassword.classList.add("valid");
    document.getElementById("message_repsw").style.display = "none";
  } else {
    repassword.classList.remove("valid");
    repassword.classList.add("invalid");
    document.getElementById("message_repsw").style.display = "block";
    document.getElementById("repassword").innerHTML = "Password does'nt match"
  }
  
}**

How to parse React Typescript into jscodeshift code

Given the code snippet, including a simple tsx string of a React component:

// test.ts

    import j from "jscodeshift";

    const code = `
    const words: string[] = ["hello", "world"];
    
    export default function(){
        return <div>{words.map(word => <span>{word}</span>)}</div>;
    }
    `;

    const ast = j(code);

    console.log(ast.toSource());

When that file is executed with node ts-node test.ts it errors like this:

.../jscodeshift/node_modules/@babel/parser/src/parser/error.js:97
    const err: SyntaxError & ErrorContext = new SyntaxError(message);
                                            ^
SyntaxError: Const declarations require an initialization value (1:11)
...

How can I use the j options to use a parser that successfully parses the .tsx code?

I expect something like

const ast = j(code, { parser: something, plugins: [somethingElse]});

But I couldn’t make it work, so far

In Javascript two same looking strings are not equal?

I’m trying to compare two passwords , one from DB and other is user entered. The one from db is hashed and stored in binary format. So I have to conver it to string before comparing.

 console.log(
      user.PasswordHash.toString('base64') ===
        '$2a$10$UZptbo5h4lQFYmK352CPf.jDvPZh1pm3uC3Nb0wEVjF/RUCw2OU2G'
    ); //false

When I look in console user.PasswordHash.toString(‘base64’) evaluates to $2a$10$UZptbo5h4lQFYmK352CPf.jDvPZh1pm3uC3Nb0wEVjF/RUCw2OU2G which is the same value.

What is happening?

bcrypt.compareSync(
      password,
      user.PasswordHash.toString('base64')); //false

Any help is appreciated.

Maintain the odd/even table style after hiding tr from table

So I’ve created a JS function that filters specific rows in the table away, but since It’s only a hide/show filter, the odd/even rows gets mixed up.

This is how my JS filter works.

var hide_info_checkbox = document.getElementById("hide_info");
var hide_debug_checkbox = document.getElementById("hide_debug");

hide_info_checkbox.addEventListener('change', function() {
  var info_td = document.getElementsByClassName("info");
  if (this.checked) {
    for (var i = 0; i < info_td.length; i++) {
      info_td[i].classList.add("ftp_hide_row");
    }
  } else {
    for (var i = 0; i < info_td.length; i++) {
      info_td[i].classList.remove("ftp_hide_row");
    }
  }
});

hide_debug_checkbox.addEventListener('change', function() {
  debug_td = document.getElementsByClassName("debug");
  if (this.checked) {
    for (var i = 0; i < debug_td.length; i++) {
      debug_td[i].classList.add("ftp_hide_row");
    }
  } else {
    for (var i = 0; i < debug_td.length; i++) {
      debug_td[i].classList.remove("ftp_hide_row");
    }
  }
});
/*
    FTP styling
*/

.ftp_table {
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
  overflow-wrap: break-word;
}

.ftp_table tr:nth-child(even) {
  background-color: #d8d8d8;
}

.ftp_hide_row {
  display: none;
}
<input type="checkbox" id="hide_info" name="hide_info" value="hide_info">
<label for="hide_info"> Hide INFO</label>
<input type="checkbox" id="hide_debug" name="hide_debug" value="hide_debug">
<label for="hide_debug"> Hide DEBUG</label>
<table class="ftp_table" id="ftp_table">
  <tbody>
    <tr>
      <th>Log</th>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:15.946 INFO [conftest:101] -------------- Global Fixture Setup Started --------------</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:16.009 DEBUG [Geni:37] Initializing </td>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:16.059 INFO [ArtifactoryWrapper:21] Downloading</td>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:16.061 INFO [ArtifactHandler:55] Art</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:16.063 DEBUG [SessionManager:84] GET</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:16.070 DEBUG [connectionpool:227] Starting new HTTP connection (1)</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:17.422 DEBUG [connectionpool:452] 200 None</td>
    </tr>
    <tr class="info">
      <td>2021-10-06 12:38:17.561 INFO [SessionManager:52] No application/json Content-Type header in GET response</td>
    </tr>
    <tr class="debug">
      <td>2021-10-06 12:38:17.422 DEBUG [connectionpool:452] 200 None</td>
    </tr>
  </tbody>
</table>

As you can see, the odd/even gets mixed up, since I only add a class which hides the rows, and doesn’t delete them:

enter image description here

Is there a way to fix this, so the odd/even is as expected?

Simplify lambda return value from spreading

If you’ve got something like this:

const someObjectArray = [
  {property: 'foo', property2: 'bar', property3: 'baz'},
  {property: 'fooDiff', property2: 'barDiff', property3: 'bazDiff'}
]

const someOtherObjectArray = someObjectArray
  .map(({property2, property3}) => ({property2, property3}))

Is there a kind of short-form-syntax to express this?

map(({property2, property3}) => ({property2, property3}))

AudioContext was not allowed to start in PlyrJs

I’m using PlyrJS with vimeo and it works just fine on PC but not mobile.

When I change devices in chrome dev tools to phone there is an error “The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page” that I can’t solve.

Important: I’m not trying to autoplay the video, only play on click. My html looks like this:

<div class="plyr__video-embed">
 <iframe src="https://player.vimeo.com/video/148751763" allow=""></iframe>
</div>

and the plyr-part script:

const players = Plyr.setup('.plyr__video-embed', {
    controls: [],
    ratio: '9:16',
    autoplay: false
});

Can someone give me a clue on how to fix this?

Create discord channel with specific roles js

let myRole = message.guild.roles.cache.find(role => role.name === "Admin");
  message.guild.channels.create(
                           channelName2, 
                          {
                            type: "GUILD_TEXT",
                            permissionOverwrites: [
                              {
                                id: myRole.id,
                                allow: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
                              },
                              {
                                id: myRole.id,
                                deny: ["VIEW_CHANNEL"]
                              }
                            ]           
                          }

Bot creates the text channel but has no permissions edited and it ignored almost whatever I write in “id: XXXXXX”

Transition-Origin WAS NOT

So was trying to make a cross for my menu but it doesn’t seem to be working. Here is the code and i am also using js to rotate it by 45 deg: Thank You in advance!! even after changing the origin it is not working and refuses to make a perfect cross

JS:

document.addEventListener('DOMContentLoaded', function(){
                let nav = document.getElementById('nav-toogle')
                let bars = document.querySelectorAll(".open")
                let active = false;
                document.querySelector('#nav_menu').addEventListener('click', function(){
                    if(!active){
                        bars[0].style.transform = "rotate(45deg)"
                        bars[1].style.opacity = "0"
                        bars[2].style.transform = "rotate(-45deg)"
                        nav.style.maxHeight = "0vh";
                        nav.style.minHeight = "100vh";
                        active = true;
                    }
                    else{
                        bars[0].style.transform = "rotate(0deg)"
                        bars[1].style.opacity = "1"
                        bars[2].style.transform = "rotate(0deg)"
                        nav.style.minHeight = "0vh";
                        nav.style.maxHeight = "0vh";
                        active = false; 

HTML

<div class="menu" id="nav_menu">
       <span class="open"></span>
       <span class="open"></span>
       <span class="open"></span>
</div>

CSS

.open{
   width: 30px;
   height: 1px;
   background-color: var(--secondary);
   margin-bottom: 5px;
   transform-origin: left;
   }

.menu{
   position: fixed;
   top: 3.5em;
   right: 3.5em;
   width: 30px;
   height: 30px;
   display:none;
   cursor: pointer;
   justify-content: center;
   align-items: center;
}

How to fix insecure content was loaded over HTTPS, but requested an insecure resource” if using the meta method wont fix it

I am doing a Soduko Solver website which i am hosting on github for personal use however i get this error and it wont display the soduko solver which i am integrating/getting from another online source, locally the website displays as it should but on github it doesnt, i tried several methods including putting the

 <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

But it doesnt seem to work and i am stuck with the same error “Mixed content: load all resources via HTTPS to improve the security of your site”
Its blocking the “embed.html” found at http://sudokusolver.net/embed.html

Why does splice method works on const (constant) array in JavaScript? [duplicate]

let selected_user = '11';
const arrayOfUsers = ['11', '12', '13'];
console.log(arrayOfUsers); // ['11', '12', '13']
let indexMainUser = arrayOfUsers.indexOf(selected_user);
arrayOfUsers.splice(indexMainUser, 1);
console.log(arrayOfUsers); //  ['12', '13']

I have the above code in JavaScript and I am wondering why does a constant array gets modified with splice method?

How to add a click event outside an element?

My current code opens up an input via a click by adding a class. I’m having trouble adding a second click that removes the added class when the user clicks off the input. I added a second click event but it just stops my first click event from working.

Is there a different way to approach this using pure JavaScript?

(Commented out failed attempt.)

let searchElement = document.querySelector('#searchElement');
let offCanvas = document.querySelector('#main');

searchElement.addEventListener('click', () => {
  searchElement.classList.add('extendInputSearch');
});


// offCanvas.addEventListener('click', () => {
  // searchElement.classList.remove('extendInputSearch');
// });
* {
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100%;
  width: 100%;
}

main {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #e1e2f1;
}

form {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

input {
  width: 100%;
  height: 32px;
  border: none;
  outline: none;
  font-size: 1rem;
}

.inputSearch {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 15px;
  padding: 8px 20px;
  background-color: #ffffff;
  border: 1px solid transparent;
  border-radius: 6px;
  transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}

.inputSearch:hover {
  border: 1px solid #7e51fa;
}

.inputSearch i {
  color: #7e51fa;
  margin-right: 20px;
}

.extendInputSearch {
  max-width: 400px;
}
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

<main id="main">
    <form>
      <div id="searchElement" class="inputSearch">
        <i class="fas fa-search"></i>
        <input type="text" placeholder="Search">
      </div>
    </form>
  </main>

How to pass a parameter for image transformations

I want to get an image from a blob. And I want to pass the parameter imageToShow in createImageFromBlob , but the function does not see it

Where is the error?

imageToShow: any;
    
...
this.createImageFromBlob(data, this.imageToShow);
...


createImageFromBlob(image: Blob, imageToShow: any) {
  let reader = new FileReader();
  reader.onload = () => {
    imageToShow = reader.result;
  };
  reader.readAsDataURL(image);
}

Live-recorded base64-encoded audio from MediaRecorder is broken

I wrote a simple page on js and php to live record audio from microphone. Logic is simple:

JS

  1. Get chunk of data from mic;
  2. Base64 encode it and urlencode it;
  3. Send it via POST request;

PHP

  1. Base64 decode data;
  2. (re)Write to .ogg file;
  3. Repeat 1 after delay.

The data is successfully written to file, but when I try to play it, player says that file is broken.

The blob solution from Mozilla guide is worked for me, I want exactly PHP solution with saving (rewriting) to file.

The full code below, what am I doing wrong?

<?php
if(isset($_POST["data"]))
{
file_put_contents("r.ogg", base64_decode($_POST["data"]));
exit;   
}
?>

<script>
var mediaRecorder = null;
let chunks = [];

if (navigator.mediaDevices &amp;&amp; navigator.mediaDevices.getUserMedia) {
   console.log('getUserMedia supported.');
   navigator.mediaDevices.getUserMedia (
      {
         audio: true
      })
      .then(function(stream) {
        mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.start(2000);
        
        mediaRecorder.ondataavailable = function(e) {
            chunks.push(e.data);
            const blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
            chunks = [];
            var reader = new FileReader();
            reader.readAsDataURL(blob); 
            reader.onloadend = function() {
            var data = reader.result.split(";base64,")[1]; 
            requestp2("a.php", "data="+encodeURIComponent(data));
            }
}
      })
      .catch(function(err) {
         console.log('The following getUserMedia error occurred: ' + err);
      }
   );
} else {
   console.log('getUserMedia not supported on your browser!');
}

function requestp2(path, data)
{
var http = new XMLHttpRequest();
http.open('POST', path, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.send(data);
}
</script>