Upload blob with AJAX and move file in the server

I started the project to create a social network with my little programming skills, but I’m stuck:
I want to create a posting system like Facebook / Instagram, but the problem is, I want to be able to upload images given by my users to the server directly and not to the database. So I first looked for a way I needed to preview the image, for that I converted the image to Base64 using JS then, I displayed it in my img tag. Then users could submit the form, that’s where it gets complicated, because if I understood correctly, you have to convert the image into a Blob to be sent by AJAX so that’s what I do in JS except that after it arrived in the PHP file I couldn’t find a way to turn it back to Base64 as I realized that PHP doesn’t support Blobs or if it does manage it then I was wrong, and I have not found a way to exploit this technology in PHP. So here I am, sending the data is working, no problem, but I still can’t upload the images to my server directly, so I tried doing a base64_encode(); but it didn’t work, then I tried multiple code from the whole web, but it still didn’t work. I saw that on this site there were multiple questions that demand for the same help, but after reading them all well, but in practice it still didn’t work, so hopefully I could find some help here and my code after will work. I leave you the code below, and thank you for reading everything. πŸ™‚
Sorry I forgot two things, I wouldn’t want to use jQuery in my code, that’s why if you give me jQuery I’ll try to translate to normal JS, but it’s going to be rather difficult so if you don’t mind please do not use jQuery. And for the second thing please forgive my English I am a French in high school passionate about code and given that the whole site is in English I did not allow myself to write in French πŸ™‚
My code :

var getHttpRequest = function () {

     var httpRequest = false;

     if (window.XMLHttpRequest) { //Mozilla,Safari,...

          httpRequest = new XMLHttpRequest();

          if (httpRequest.overrideMimeType) {

               httpRequest.overrideMimeType('text/xml');

          }

     }

     else if (window.ActiveXObject) { //IE

          try {
               httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
          }

          catch (e) {
                         
               try{

                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
               }

               catch (e) {}
          }
     }
     if (!httpRequest) {
          alert('Abandon :( Impossible de crΓ©er une instance XMLHTTP');
          return false;
     }

     return httpRequest;
}
function creapubimg(){
    let httpRequest = getHttpRequest();
    let content = document.getElementById('content_text_area_img').value;
    let imgpub = document.getElementById('chosen-image').src;
    let extention = ['jpeg','png','jpg','gif'];
    let base64ImageContent,contentType,hashtxt;
    var contentTypepost
    let idcountforinclude=0;
    extention.forEach(element => {
        if (imgpub.indexOf(element.value) !== -1){
            base64ImageContent = imgpub.replace('data:image/'+element.value+';base64');
            switch (element.value) {
                case 'jpeg':
                case 'jpg':
                    contentTypepost = 2;
                    contentType = 'image/jpeg'
                    break;
                case 'png':
                    contentTypepost = 3;
                    contentType = 'image/png'
                    break;
                case 'gif':
                    contentTypepost = 1;
                    contentType = 'image/gif'
                    break;
                default:
                    break;
            }
        }
    });
    let base64 = imgpub.replace('data:image/jpeg;base64,', "");
    let blob = b64toBlob(base64,contentType);
    let blobUrl = URL.createObjectURL(blob);
    hashtxt = makeid(24);
    httpRequest.onreadystatechange = function (){
        if(httpRequest.readyState === 1){
          hide_img_panel_reverse();
        }
        if(httpRequest.readyState === 2){
          // faire apparaitre truc de chargment
        }
        if(httpRequest.readyState === 4){
            if(httpRequest.responseText != 'veuiller remplir tout les champs'){
                idcountforinclude += 1;
                let docu = document.getElementById('aff_pub');
                // hide truc de chargment
                let replt = document.createElement('div');
                replt.setAttribute('id', idcountforinclude);
                docu.prepend(replt);
                document.getElementById(idcountforinclude).innerHTML = httpRequest.responseText;
            }
        }
    }
    httpRequest.open('POST','includes/createpubimg.php',true);
    httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    httpRequest.send("content_publiction=" + encodeURIComponent(content) + "&img=" + encodeURIComponent(blob) + "&string=" + encodeURIComponent(hashtxt) + "&Content-Type=" + encodeURIComponent(contentTypepost));
}
function b64toBlob(b64Data, contentType='',sliceSize=512){
    let byteCharacters = atob(b64Data);
    let byteArrays = [];
    for(let offset = 0; offset <  byteCharacters.length; offset+=sliceSize){
        
        let slice = byteCharacters.slice(offset,offset + sliceSize);
        let byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        let byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    let blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

And here is the PHP :

<?php
include '../database.php';
        global $db;

if(isset($_POST['img'])){
  if($_POST['Content-Type'] == 1) {
    $hashchemin = crypt($_POST['string'], 'piafou');
    $hashchemin = rtrim($hashchemin, '/\');
    $chemin = 'img_pub/'.$hashchemin.'.gif';  
    if(isset($_POST['content_publication'])){
      if(!empty($_POST['content_publication'])){
        $content = $_POST['content_publication'];
        $Blobimg = $_POST['file'];
        $Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
        move_uploaded_file(base64_decode($Base64img), $chemin);
        $ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
        $ins->execute([
          'content' => $content,
          'img_pub' => $chemin
        ]);
        $publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
        $pub = $publications->fetch();
        ?>
          <div class="aff_pub_div_content" id="<?=$pub['id']?>">
            <div style="height: 52px;">
              <img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
              <label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
              <a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
            </div>
            <div class="nonSelectionnable">
              <?php if(!empty($pub['img_pub'])){ ?>
                <img src="<?=$pub['img_pub']?>" class="img_pub_aff">
              <?php 
                  }
              ?>
            </div>
            <div>
              <p class="text_pub_aff" id="<?="content_".$pub['id']?>">
                <?php 
                  $pub_content = $_POST['content_publication'];
                  $pub_content = htmlspecialchars($pub_content, ENT_HTML5);
                  $pub_content = nl2br($pub_content);
                  echo($pub_content);
                ?>  
              </p>
            </div>
            <div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
            <div style="text-align: left;" class="nonSelectionnable">
              <ul style="margin-top: 6px; margin-left: 20px">
                <?php 
                  $likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
                  $likepub->execute([
                    'user' => 16,
                    'pub' => $pub['id']
                  ]);
                  if($likepub->rowCount() ==1) {
                ?> 
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: red;
                  }
                </style>
                <?php
                  }
                  else{
                ?>
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: white;
                  }
                </style>
                <?php
                  }
                ?>
                <li class="exp_article" style="margin-right: 6px">
                  <div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
                    <a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
                      <img src="IMG/love.png" height="30px" width="30px" id="like">
                    </a>
                  </div>
                </li>
                <li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
                <li class="exp_article">
                  <div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
                </li>
              </ul>
            </div>
          </div>
        <?php
      }
      else{
        echo('Veuiller remplir tout les champs');
      } 
    }
  }
  elseif($_POST['Content-Type'] == 2){
    $hashchemin = crypt($_POST['string'], 'piafou');
    $hashchemin = rtrim($hashchemin, '/\');
    $chemin = 'img_pub/'.$hashchemin.'.jpeg';
    if(isset($_POST['content_publication'])){
      if(!empty($_POST['content_publication'])){
        $content = $_POST['content_publication']; 
        $Blobimg = $_POST['file'];
        $Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
        move_uploaded_file(base64_decode($Base64img), $chemin);
        $ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
        $ins->execute([
          'content' => $content,
          'img_pub' => $chemin
        ]);
        $publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
        $pub = $publications->fetch();
        ?>
          <div class="aff_pub_div_content" id="<?=$pub['id']?>">
            <div style="height: 52px;">
                <img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
                <label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
                <a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
            </div>
            <div class="nonSelectionnable">
              <?php if(!empty($pub['img_pub'])){ ?>
                <img src="<?=$pub['img_pub']?>" class="img_pub_aff">
              <?php 
                  }
              ?>
            </div>
            <div>
              <p class="text_pub_aff" id="<?="content_".$pub['id']?>">
                <?php 
                  $pub_content = $_POST['content_publication'];
                  $pub_content = htmlspecialchars($pub_content, ENT_HTML5);
                  $pub_content = nl2br($pub_content);
                  echo($pub_content);
                ?>  
              </p>
            </div>
            <div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
            <div style="text-align: left;" class="nonSelectionnable">
              <ul style="margin-top: 6px; margin-left: 20px">
                <?php 
                  $likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
                  $likepub->execute([
                    'user' => 16,
                    'pub' => $pub['id']
                  ]);
                  if($likepub->rowCount() ==1) {
                ?> 
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: red;
                  }
                </style>
                <?php
                  }
                  else{
                ?>
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: white;
                  }
                </style>
                <?php
                  }
                ?>
                <li class="exp_article" style="margin-right: 6px">
                  <div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
                    <a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
                      <img src="IMG/love.png" height="30px" width="30px" id="like">
                    </a>
                  </div>
                </li>
                <li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
                <li class="exp_article">
                  <div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
                </li>
              </ul>
            </div>
          </div>
        <?php
      }
      else{
        echo('Veuiller remplir tout les champs');
      } 
    } 
  }
  elseif($_POST['Content-Type'] == 3){
    $hashchemin = crypt($_POST['string'], 'piafou');
    $hashchemin = rtrim($hashchemin, '/\');
    $chemin = 'img_pub/'.$hashchemin.'.png';
    if(isset($_POST['content_publication'])){
      if(!empty($_POST['content_publication'])){
        $content = $_POST['content_publication'];
        $Blobimg = $_POST['file'];
        $Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
        move_uploaded_file(base64_decode($Base64img), $chemin);
        $ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
        $ins->execute([
          'content' => $content,
          'img_pub' => $chemin
        ]);
        $publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
        $pub = $publications->fetch();
        ?>
          <div class="aff_pub_div_content" id="<?=$pub['id']?>">
              <div style="height: 52px;">
                  <img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
                  <label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
                  <a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
              </div>
              <div class="nonSelectionnable">
                <?php if(!empty($pub['img_pub'])){ ?>
                  <img src="<?=$pub['img_pub']?>" class="img_pub_aff">
                <?php 
                    }
                ?>
              </div>
              <div>
                <p class="text_pub_aff" id="<?="content_".$pub['id']?>">
                  <?php 
                    $pub_content = $_POST['content_publication'];
                    $pub_content = htmlspecialchars($pub_content, ENT_HTML5);
                    $pub_content = nl2br($pub_content);
                    echo($pub_content);
                  ?>  
                </p>
              </div>
              <div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
              <div style="text-align: left;" class="nonSelectionnable">
                <ul style="margin-top: 6px; margin-left: 20px">
                  <?php 
                    $likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
                    $likepub->execute([
                      'user' => 16,
                      'pub' => $pub['id']
                    ]);
                    if($likepub->rowCount() ==1) {
                  ?> 
                  <style type="text/css">
                    .phpdecidelikecolordiv-<?=$pub['id']?>{
                      background-color: red;
                    }
                  </style>
                  <?php
                    }
                    else{
                  ?>
                  <style type="text/css">
                    .phpdecidelikecolordiv-<?=$pub['id']?>{
                      background-color: white;
                    }
                  </style>
                  <?php
                    }
                  ?>
                  <li class="exp_article" style="margin-right: 6px">
                    <div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
                      <a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
                        <img src="IMG/love.png" height="30px" width="30px" id="like">
                      </a>
                    </div>
                  </li>
                  <li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
                  <li class="exp_article">
                    <div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
                  </li>
                </ul>
              </div>
          </div>
        <?php
      }
      else{
        echo('Veuiller remplir tout les champs');
      } 
    }
  }
  else{
    // message d'erreur
  }
}
?>

You can see that in my PHP code I put this:

$Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";

It is thanks to this line of code that I believed that I would succeed in converting the blob to Base64
If anyone has the solution to my problem, I thank them in advance.
P.S. = I have already tried with Form Data and I have not succeeded I think this is the solution, but I cannot get it to work.
Thanks to everyone who read πŸ™‚

Puppeteer Calling Browser.close() randomly throws an a error that is not catchable – Error: EPERM: operation not permitted

I have stripped out all of the code in my app to isolate this issue and it can be reproduce by only launching the browser and calling browser.close(). The error thrown is [Error: EPERM: operation not permitted, unlink ‘C:UsersxxxAppDataLocalTemppuppeteer_dev_chrome_profile-vHZSchCrashpadMetrics-active.pma’] and it hangs the process. I need to be able to catch this error so the server can continue to process requests, however this error cannot be caught. How can I catch/prevent this error?

The error is thrown from the browser.close() call as mentioned is possible in the documentation here. I wrapped an additional try catch within the finally around that call and it doesn’t catch but throws the error.

try{
 browser = await puppeteer.launch({
   args: ['--no-sandbox', '--unlimited-storage', '--disable-gpu', '--disable-dev-shm-usage', '--full-memory-crash-report', '--disable-setuid-sandbox'],
   headless: true,
   pipe: true
 }).catch((err) => {
   console.log('could not launch browser', err)
 });
} catch(err) {
   console.error(err);
} finally {
  try{
    if(browser) {
      console.log('closing down browser')
      const pages = await browser.pages();
      console.log(pages.length)
      await Promise.all(pages.map(page => page.close()))
      console.log('closed pages')
      // if (browser && browser.process() !== null){
      //     browser.process().kill('SIGINT');
      // }
      await browser.close().catch((err) => console.log(err));
      console.log('finished closing')
    }
  }
  catch(error){
    console.log('this caught', error)
  }    
}

The commented out lines for killing the process do prevent the error from being thrown, however I am on a windows machine and this does not actually kill the process, although I imagine this method works on linux.

Getting error : “react-dom.production.min.js:216 TypeError: Object(…) is not a function” while deploying react app on github pages

I am trying to deploy my react application and its not rendering the page properly, It is throwing the below error : react-dom.production.min.js:216 TypeError: Object(…) is not a function.

I have linked the screenshot of the error and the file name along with my github link of the repo.[![

Expense.js

import { useState } from "react";
import "../css/Expenses.css";
import Card from "./Card";
import ExpenseItem from "./ExpenseItem";
import Filter from "./Filter";

function Expenses(props){
    let data = props.data;
    let [year,changeYear] = useState("2021");

    let data2 = data.filter(function(item){
      return(new Date(item.dates).getFullYear().toString() === year);
    })
    

    let setFilter = function(yearValue){
      changeYear(yearValue);
    }


    return(
     <Card className = "card">
     <div className="filter-section">
       <h3>Filter By Year</h3>
       <Filter sendData={setFilter} yearVal = {year} className='year-filter-card'/>
     </div>
     <div className="expense-wrap">
          {data2.length?
            data2.map(function(expItem) {
             return <ExpenseItem key={Math.random()*100000} item= {expItem} deleteMe={props.deleteMe}/>  
          }):
          <h2 className="nodata">No Expense Data</h2> 
    }
    </div>
     </Card>
    );
    
}

export default Expenses;

link to my repo: https://github.com/AbhishekTomr/money-tracker

Get Blob Content from bindings and then zip the content and save it in the blob container using azure function

I am using bindings of azure function to get the blob content and to store the file in blob.
Below is the code that I am using but its not passing anything to the output bindings.

const JSZip = require("jszip");
const saveas = require('file-saver')
module.exports = async function (context, myBlob) {
    context.log("Function Triggered. ", context.bindingData.blobTrigger);
        
 var input = context.bindings.myBlob;
     var inputBuffer = Buffer.from(input);
     var zip = new JSZip();
zip.file(inputBuffer);
zip.generateAsync({type:"blob"})
.then(function(content) {

 var j =   content;
  context.bindings.myOutputBlob = j; 
});
 
 
 
 }

Please let me know what I am doing wrong here.

Should I avoid adding arbitrary fields to HTML elements?

I tested adding arbitrary fields to HTML elements in JavaScript and it worked as expected:

const element = document.getElementById('element-id');
element.greet = (message) => { alert(message); };
element.message = 'Hello, world!';
element.greet(element.message);

The alert shows up with the message, but I’m concerned:

  1. Do all the major browsers support this behavior?
  2. Is there a pattern for choosing new field name to make sure it won’t conflict with names that the browsers use as fields for the elements?
  3. Is there any reason I should avoid adding arbitrary fields to HTML elements?

How can I use innerHTML to change the description of an image using a function?

The only thing that works is the else statement the 2 if statements do not work( I also tried else if statements and those do not work either). I need the description to change when the user clicks on the radio button according to the image displayed. The description should match the image. I am new to javascript.

      <div id = "image-text">
      <p>The statue of liberty was built in France and disassembled and transported by a ship 
       to the United States. It was completed in October of 1886 and is a symbol of freedom.
      </p>
    </div>

    <!-- Radio buttons-->
    <div id = "radio-buttons">
    <form>
    <input type="radio" id="statue-button" name="landmark" checked value="statue" onClick="changeImage('statue');changeText('image-text')";">Statue of Liberty<br>

    <input type="radio" id = "bridge-button" name="landmark" value="bridge" onclick="changeImage('bridge');changeText('image-text')" >Golden Gate Bridge<br>

    <input type="radio" id = "rushmore-button" name="landmark" value="rushmore" onclick="changeImage('rushmore');changeText('image-text')">Mount Rushmore<br>
     </form>
    </div>
    <p></p>
    <!-- Function that changes the description of the image-->
<script>
     function changeText(value) {
   let imageText = document.getElementById('image-text'); 
   let changes = document.getElementById('radio-buttons'); 

  if (value = 'statue') {
    imageText.innerHTML = "The statue of liberty was built in France and disassembled and transported by a ship to the United States. It was completed in October of 1886 and is a symbol of freedom."
      } 
  if  (value === 'bridge') {
    imageText.innerHTML = "The Golden Gate Bridge is a suspension bridge spanning the Golden Gate, the one-mile-wide strait connecting San Francisco Bay and the Pacific Ocean";
  }
  else {
      imageText.innerHTML= "Mount Rushmore National Memorial is a massive sculpture carved into Mount Rushmore in the Black Hills region of South Dakota. It was completed in 1941.";
    }
 }
 </script>

Delete Element from the Page

the teacher asked us to design a website to teach children letters, when I click the generate button, it generates letters in a random way, and when I click on a letter, an image of something that starts with this letter is displayed. The problem is when I click on another letter, it displays an image of something that starts with this letter, but The old image of the other letter is still present on the page and is not deleted. What I want is when I click on a letter it displays an image of something that begins with this letter and when I click on another letter I want it to delete the old image and display only the image that begins with this letter
this is my JS code

var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
var generate = document.getElementById("generate");
var input = document.getElementById("input"); 
var letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
// here to add the path of the each img to array to store it becuase we will need it leter 
litterImg = [];
for (let i = 0;i < 26;i++) {
    litterImg[i] = 'img\'+i+'.jpg';
};
var randomLetter = [];
var getRandomLetter = [];
var linkImg = [];
var numberOfLitters;
generate.addEventListener("click",function(e){ 
    numberOfLitters = input.valueAsNumber;
    for (let index = 0; index < numberOfLitters; index++) { 
        let x = randomNumbers();
        randomLetter[index]  = document.createElement("input");
        randomLetter[index].setAttribute("type","button");
        randomLetter[index].setAttribute("value",letters[x]);
        randomLetter[index].setAttribute("id", x);
        randomLetter[index].setAttribute("class",x);
        div2.appendChild(randomLetter[index]);
    }});
// event to add the images when i click on a litter  
div2.addEventListener("click",function(e){
    for (let index = 0; index < 26; index++) {
        if (e.target.id == index) {
            linkImg[index] = document.createElement("img");
            linkImg[index].setAttribute("src",litterImg[index]);
            linkImg[index].setAttribute("width","1080px");
            linkImg[index].setAttribute("height","720px");
            div3.appendChild(linkImg[index]);
        }
    }
});

and this is my html code

<html>
    <head>
        <meta>
        <title>Alphabet Learner</title>
    </head>
    <body>
        <div id="div" class="div"  style="text-align : center;">
            <h1>Learn the English Litters </h1><br>
            <label >Number of Litters: </label>
            <input type="number" class="input" id="input" >
            <input type="button" class="generate" id="generate" value="Generate">
            <br><br>
            <div id="div2" class="div2">
            </div><br>
            <div id="div3" class="div3"></div>
        </div>
        <script src="script.js"></script>
    </body>
</html>

stuck at default page of WordPress

hello and hope you guys have a fantastic time

I have a problem with my WordPress website, it does now show fallowing elements: my theme, my homepage, my WordPress bar at the top

it just show a empty black blank page with big logo of my website

you can see other part of the website by searching it manually (like: yourname.com/blog)

but not the main home page (like: yourname.com)

please assist me

thanks ❤

jQuery text search – how do I show a “No results” div when using an if else conditional?

I’m working on a “live” text search in the html on a page using jQuery.

The function below works as a “live” search, when a minimum of three characters is entered to start the search.

$('#search').keyup(function() {
    var text = $(this).val().trim();
    var minLength = 2;
    $('.record.active').removeClass("active");
    if (!text.length) return;
    if (text.length > minLength)
    $('.record').each(function() {
      if ($(this).text().toLowerCase().includes(text)) {
        $(this).addClass("active");
      }
    });

But what I want to do is show “No results” when there are no results. I’m trying to use an if else statement to determine if there are any records with the active class. But function in the snippet below doesn’t work; it simply shows “No ResultsNo ResultsNo ResultsNo Results….” with no search results.

 $('#search').keyup(function() {
    var text = $(this).val().trim();
    var minLength = 2;
    $('.record.active').removeClass("active");
    if (!text.length) return;
    if (text.length > minLength)
    $('.record').each(function() {
      if ($(this).text().toLowerCase().includes(text))
        $(this).addClass("active");
        else
        $('.record').not("active");
        $(".no-results").append("No Results");
    
    });
  });
.record {
display: none;
}

.record.active {
display: block;
}
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Search <input type='text' id='search' placeholder='Search Text'>

<br />

<div class="no-results"></div>

<br />

<div class="record">Now is the time for all good men to come to the aid of their city</div>
<div class="record">Now is the time for all good women to come to the aid of their country</div>
<div class="record">Now is the time for all droids to come to the aid of their universe</div>
<div class="record">Now is the time for all fluffy bears to come to the aid of their wilderness</div>
<div class="record">Now is the time for all short people to come to the aid of their county</div>

JavaScript Algorithm For Continuous Filtering Data On Most Recent Results

I need to write an algorithm where the user selects an option to filter a particular data and on every click it makes an api request returning the filtered data. As many times the user clicks it needs to continue to filter out the data. My question is, how can the algorithm save the most recent result and run a for/filter loop on the most recent results? And when the user decides to unselect the data that they wanted to filter, it should show the user their previous results. The user should be able to continue to filter until they get the desired data. Please see example below.

***DATA***
let data = [
  {"id":0, "name":"John1", "age":29, "city":"seattle", "score": 95},
  {"id":1, "name":"John2", "age":25, "city":"seattle", "score": 95},
  {"id":2, "name":"John3", "age":29, "city":"seattle", "score": 85},
  {"id":3, "name":"John4", "age":30, "city":"austin", "score": 75},
  {"id":4, "name":"John5", "age":24, "city":"austin", "score": 85},
  {"id":5, "name":"John6", "age":30, "city":"aspen", "score": 84},
  {"id":6, "name":"John7", "age":31, "city":"aspen", "score": 100},
  {"id":7, "name":"John8", "age":31, "city":"aspen", "score": 93},
  {"id":8, "name":"John9", "age":35, "city":"denver", "score": 93},
  {"id":9, "name":"John10", "age":29, "city":"denver", "score": 75},
  {"id":10, "name":"John11", "age":28, "city":"denver", "score": 85},
  {"id":11, "name":"John12", "age":28, "city":"denver", "score": 85},
]
***FIRST USER SELECTED FILTER***
let firstFilter = [{"score":85}]

***FIRST FILTER RESULTS***
let firstFilterdResults = [
  {"id":2, "name":"John3", "age":29, "city":"seattle", "score": 85},
  {"id":4, "name":"John5", "age":24, "city":"austin", "score": 85},
  {"id":10, "name":"John11", "age":28, "city":"denver", "score": 85},
  {"id":11, "name":"John12", "age":28, "city":"denver", "score": 85},
 ]
***SECOND USER SELECTED FILTER***
let secondFilter = [{"age":28}]

***SECOND FILTER RESULTS***
let secondFilterdResults = [
  {"id":10, "name":"John11", "age":28, "city":"denver", "score": 85},
  {"id":11, "name":"John12", "age":28, "city":"denver", "score": 85},
 ]
***CURRENT ALGORITHM***

function filterDataList(data, firstFilter) {
  let firstFilteredResults = [];

  firstFilteredResults = data.filter((dataItem) => {
    var throwVar = 0 
    for (let item of firstFilter) {
      for (let key in item) {
        if (dataItem[key] === undefined || dataItem[key] !== item[key]) {
          throwVar = 0
        } else {
          return true
        }
      }



    }
    if (throwVar == 0) {
      return false
    }
  })

  return firstFilteredData

}

store and read firebase serviceAccountKey from dotenv (.env) file in node js

I’m using firebase in my project and I want to store its serviceAccountKey.json file in .env file like this

SERVICE_ACCOUNT_KEY={
  "type": "service_account",
  "project_id": "abc-123",
  "private_key_id": "123",
  "private_key": "-----BEGIN PRIVATE KEY-----n**some string**n-----END PRIVATE KEY-----n",
  "client_email": "firebase-adminsdk-whatever.gserviceaccount.com",
  "client_id": "123",
  "auth_uri": "https://something",
  "token_uri": "https://something",
  "auth_provider_x509_cert_url": "https://something",
  "client_x509_cert_url": "https://something.com"
}

And I’m reading this in my firebase-config file like this

const admin = require("firebase-admin");
const serviceAccount = process.env.SERVICE_ACCOUNT_KEY;

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: process.env.DATABASE_URL,
});

It says

Failed to parse service account json file: Error: ENOENT: no such file or directory

And then I tried to parse this file like this

const serviceAccount = JSON.parse(process.env.SERVICE_ACCOUNT_KEY)

And now it’s saying

Failed to parse private key: Error: Invalid PEM formatted message.

Please help me storing this json file in .env file

How to create new array from existing array with different structure

I want to reformat the existing array, how can i do it using Javascript or typescript

first array

pdfData: [
         { 
           Id: 1, 
           path:'https//path/pdf1'
         },
         { 
           Id: 1, 
           path:'https//path/pdf2'
         },
         { 
           Id: 2, 
           path:'https//path/pdf1'
         },
         { 
           Id: 2, 
           path:'https//path/pdf2'
         },
        ]

I want to convert this array to following one

data: [
        { 
           Id: 1, 
           links:['https//path/pdf1','https//path/pdf2']
         },
         { 
           Id: 2, 
           links:['https//path/pdf1','https//path/pdf2']
         },

  ]