php shop/checkout system SESSION problems

I would like to ask for help, I am still a beginner in php systems and language. I’m trying to create an online store and I have several subpages, including the “shop” and each product has a separate subpage. The checkout system is also on a separate page. I have no idea how to display several selected products at the same time on the checkout page.I transfer the data of individual products to the checkout page from the individual product subpages as follows:

<a href="cart.php?action=add&product_name=<?php echo urlencode($product_name); ?>&product_price=<?php echo $product_price; ?>&product_picture=<?php echo urlencode($product_picture); ?>&quantity=1&size=<?php echo urlencode($size); ?>" id="addToCartBtn" class="normal">Add To Cart</a>

This is how I get the extracted data on the checkout page:

 <?php

if(isset($_GET['product_name']) && isset($_GET['product_price']) && isset($_GET['quantity']) && isset($_GET['product_picture']) && isset($_GET['size'])) {
    $product_name = $_GET['product_name'];
    $product_price = $_GET['product_price'];
    $quantity = $_GET['quantity'];
    $product_picture = $_GET['product_picture'];
    $size = $_GET['size'];
    ?>

My question would still be how it could be implemented so that the selected products are stored on the checkout page and do not disappear if I go to another subpage.

i tried creating php SESSION but it didn’t work.

The drop-down menu disappears after hovering

Good evening all,

I have tried to create a navigation in which a main category has various subcategories. If you hover over the main category, the subcategories should appear.

So far it works, but the list of subcategories does not disappear afterwards but remains after the hover.

I tried to create a function using MouseOut (In the following code this is commented out) but if I move the Mouse, the Navigation dissapear to soon.

The code is for test purposes only, so the JS is not stored in a separate file.

<body>
<nav role="Navigation">
    <ul id="Hauptnavi">
        <li><a href="#">Start</a></li>
        <li id="Servicehover"><a href="#">Service</a></li>
            <ul id="Unternavi">
                <li><a href="#">Unterseite A</a></li>
                <li><a href="#">Unterseite B</a></li>
                <li><a href="#">Unterseite C</a></li>
            </ul>
        <li><a href="#">Contact</a></li>
    </ul>

</nav>


<script>
document.getElementById("Servicehover").addEventListener("mouseover", MouseOver);
/* document.getElementById("Hauptnavi").addEventListener("mouseout", MouseOut); */

function MouseOver() {
    document.getElementById("Unternavi").style.visibility = "visible";
    document.getElementById("Unternavi").style.opacity = 1;
}

/*
function MouseOut() {
    document.getElementById("Unternavi").style.visibility = "none";
    document.getElementById("Unternavi").style.opacity = 0;
} */

</script>
</body>
</html>

Following the CSS Code

* {
    padding: 0;
    margin: 0;
}

#Hauptnavi {
    background-color: gray
}

nav ul li {
    list-style-type: none;
}

nav ul li a {
    text-decoration: none;
}

#Unternavi {
    opacity: 0;
    visibility: none; 

}

What is the best way to realize this case? I don’t need a ready-made solution, just some advice on how to go about it correctly.

Thanks a lot.

I tried to create a function using MouseOut (In the following code this is commented out) but if I move the Mouse, the Navigation dissapear to soon.

I also tried to use a click event but it only worked with “document.getElementById(“Hauptnavi”)…. if i tried to access the id “Servicehover” it doesn’t work.

JS Consistent Timeouts Between Browsers [duplicate]

I’m trying to make a timer that is consistent between browsers, but some users of my site have reported that the timer ticks down much faster in some browsers than others. Specifically, it seems like Chrome runs real-time, while Safari and Firefox have a much slower countdown. Here is the code that handles the timer:

async function countDown(){
    if(!gameIsRunning)
        return;

    if(timeRemaining <= 0){
        gameOver();
        return;
    }

    // Immediately Set timeout for next countdown step
    setTimeout(() => {
        countDown();
        // console.log(timeRemaining)
    }, COUNTDOWN_STEP);

    // Apply countdown
    timeRemaining -= COUNTDOWN_STEP;
    updateTimeBar();
}

The function sets a timeout to call itself.
Is there a way to make this consistent? Would a loop that sleep(10ms) be more consistent?

esmock with sinon and checking if a function is calledOnce

I’m trying to update a project to use import / export and that’s lead me to using esmock for mocking responses in my unit tests. I used to have this code which I could then check with calledOnce & this worked when using require and sinon.stub().

mapCountAllTeams = sinon.stub(adminJS, 'mapCountAllTeams').returns(false);

Now I’ve updated it to esmock like this because of issues stubbing ES modules:

const adminJS = await esmock('../adminFunctions.js', {
     '../adminFunctions.js': {
        mapCountAllTeams: false
     }
});

But I don’t seem to be able to call adminJS.mapCountAllTeams() from within the test, it keeps returning undefined or the below error. However when logging the actual functions output it is returning the correctly mocked value.

Promise {
  <rejected> TypeError: Cannot convert undefined or null to object
      at Function.values (<anonymous>)
      at Module.mapCountAllTeams (file:///C:/functions/adminFunctions.js?esmk=1?esmk=1:285:29)
      at Context.<anonymous> (file:///C:/functions/test/fklProdAdmin.test.js:103:36)

what is the best practice to be able to use esmock with calledOnce?

Why is .map function returning undefined objects in an array?

I’m trying to fetch JSON data from my API to import to Google Sheets using Google Apps Script. Everything is working as expected, except for when I’m trying to map the object, the result array returns undefined objects.

Here’s my script:

function GETMYJSONDATA() {

var options = {
"method" : "get",
"headers" : {
"Authorization": "Bearer REDACTED"
}
};

const url = "REDACTED"
const res = UrlFetchApp.fetch(url, options)
const dataAsText = res.getContentText()
const data = JSON.parse(dataAsText)

const results = data.response.users.map (user => {
return
[user["department_text"]]
})

return results
}

​Below is the JSON response from my API (raw) and the Apps Script debugger result:

enter image description here

enter image description here

Why is my Tic-Tac-toe giving two wins to X win they win?

<html>
  <body>
    <style>
      td {
        border: 1px solid black;
        height: 50px;
        width: 50px;
      }
    </style>
    <script>
      let O1 = false;
      let X1 = false;
      let O2 = false;
      let X2 = false;
      let O3 = false;
      let X3 = false;
      let O4 = false;
      let X4 = false;
      let O5 = false;
      let X5 = false;
      let O6 = false;
      let X6 = false;
      let O7 = false;
      let X7 = false;
      let O8 = false;
      let X8 = false;
      let O9 = false;
      let X9 = false;
      let turn = 0;
      let XWinNum = 0
      let OWinNum = 0
      function Xon1() {
        if (O1 === false && X1 === false && turn === 0) {
          document.getElementById("1").innerHTML = 'X';
          X1 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon2() {
        if (O2 === false && X2 === false && turn === 0) {
          document.getElementById("2").innerHTML = 'X';
          X2 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon3() {
        if (O3 === false && X3 === false && turn === 0) {
          document.getElementById("3").innerHTML = 'X';
          X3 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon4() {
        if (O4 === false && X4 === false && turn === 0) {
          document.getElementById("4").innerHTML = 'X';
          X4 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon5() {
        if (O5 === false && X5 === false && turn === 0) {
          document.getElementById("5").innerHTML = 'X';
          X5 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon6() {
        if (O6 === false && X6 === false && turn === 0) {
          document.getElementById("6").innerHTML = 'X';
          X6 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon7() {
        if (O7 === false && X7 === false && turn === 0) {
          document.getElementById("7").innerHTML = 'X';
          X7 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon8() {
        if (O8 === false && X8 === false && turn === 0) {
          document.getElementById("8").innerHTML = 'X';
          X8 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon9() {
        if (O9 === false && X9 === false && turn === 0) {
          document.getElementById("9").innerHTML = 'X';
          X9 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function compMove() {
        checkForWin()
        if (turn === 1) {
          if(X1 === true && X2 === true && X3 === false && O3 === false && turn === 1) {
            document.getElementById("3").innerHTML = 'O';
          O3 = true
          turn--
          }
          if(X1 === true && X3 === true && X2 === false && O2 === false && turn === 1) {
            document.getElementById("2").innerHTML = 'O';
          O2 = true
          turn--
          }
          if(X2 === true && X3 === true && X1 === false && O1 === false && turn === 1) {
            document.getElementById("1").innerHTML = 'O';
          O1 = true
          turn--
          }
          if(X3 === true && X4 === true && X5 === false && O5 === false && turn === 1) {
            document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X3 === true && X5 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X4 === true && X5 === true && X6 === false && O6 === false && turn === 1) {
            document.getElementById("6").innerHTML = 'O';
          O6 = true
          turn--
          }
          if(X7 === true && X8 === true && X9 === false && O9 === false && turn === 1) {
            document.getElementById("9").innerHTML = 'O';
          O9 = true
          turn--
          }
          if(X7 === true && X9 === true && X8 === false && O8 === false && turn === 1) {
            document.getElementById("8").innerHTML = 'O';
          O8 = true
          turn--
          }
          if(X8 === true && X9 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X1 === true && X4 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X1 === true && X7 === true && X4 === false && O4 === false && turn === 1) {
            document.getElementById("4").innerHTML = 'O';
          O4 = true
          turn--
          }
          if(X7 === true && X4 === true && X1 === false && O1 === false && turn === 1) {
            document.getElementById("1").innerHTML = 'O';
          O1 = true
          turn--
          }
          if(X2 === true && X5 === true && X8 === false && O8 === false && turn === 1) {
            document.getElementById("8").innerHTML = 'O';
          O8 = true
          turn--
          }
          if(X2 === true && X8 === true && X5 === false && O5 === false && turn === 1) {
            document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X5 === true && X8 === true && X2 === false && O2 === false && turn === 1) {
            document.getElementById("2").innerHTML = 'O';
          O2 = true
          turn--
          }
          if(X3 === true && X6 === true && X9 === false && O9 === false && turn === 1) {
            document.getElementById("9").innerHTML = 'O';
          O9 = true
          turn--
          }
          if(X3 === true && X9 === true && X6 === false && O6 === false && turn === 1) {
            document.getElementById("6").innerHTML = 'O';
          O6 = true
          turn-- 
          }
          if(X9 === true && X6 === true && X3 === false && O3 === false && turn === 1) {
            document.getElementById("3").innerHTML = 'O';
          O3  = true
          turn--
          }
          if(X5 === true && X7 === true && X3 === false && O3 === false && turn === 1) {
            document.getElementById("3").innerHTML = 'O';
          O3 = true
          turn--
          }
          if(X5 === true && X3 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X7 === true && X3 === true && X5 === false && O5 === false && turn === 1) {
            document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X1 === true || X2 === true || X3 === true || X4 === true || X5 === true || X6 === true || X7 === true || X8 === true || X9 === true && turn === 1) {
            if(O5 === false && X5 === false){
          document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--} else {
          if(X1 === false && O1 === false && turn === 1){
              document.getElementById("1").innerHTML = 'O';
          O1 = true
          turn--
          }
          if(X2 === false && O2 === false && turn === 1){
              document.getElementById("2").innerHTML = 'O';
          O2 = true
          turn--
          }
          if(X3 === false && O3 === false && turn === 1){
              document.getElementById("3").innerHTML = 'O';
          O3 = true
          turn--
          }
          if(X4 === false && O4 === false && turn === 1){
              document.getElementById("4").innerHTML = 'O';
          O4 = true
          turn--
          }
          if(X5 === false && O5 === false && turn === 1){
              document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X6 === false && O6 === false && turn === 1){
              document.getElementById("6").innerHTML = 'O';
          O6 = true
          turn--
          }
          if(X7 === false && O7 === false && turn === 1){
              document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X8 === false && O8 === false && turn === 1){
              document.getElementById("8").innerHTML = 'O';
          O8 = true
          turn--
          }
          if(X9 === false && O9 === false && turn === 1){
              document.getElementById("9").innerHTML = 'O';
          O9 = true
          turn--
          }
         
          }
          
          }
       
          }
          checkForWin()
          }
          function checkForWin() {
          if(X1 === true && X2 === true && X3 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X4 === true && X5 === true && X6 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X7 === true && X8 === true && X9 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X1 === true && X4 === true && X7 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X2 === true && X5 === true && X8 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X3 === true && X6 === true && X9 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X1 === true && X5 === true && X9 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X3 === true && X5 === true && X7 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(O1 === true && O2 === true && O3 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O4 === true && O5 === true && O6 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O7 === true && O8 === true && O9 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O1 === true && O4 === true && O7 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O2 === true && O5 === true && O8 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O3 === true && O6 === true && O9 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O1 === true && O5 === true && O9 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O3 === true && O5 === true && O7 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          }
          function OWins() {
            alert("O Wins")
            OWinNum+=1
            document.getElementById("win").innerHTML = 'X:' + XWinNum + '-' + 'O:' + OWinNum
          }
          function XWins() {
            alert("X Wins")
            XWinNum+=1
            document.getElementById("win").innerHTML = 'X:' + XWinNum + '-' + 'O:' + OWinNum
          }
          function Restart() {
            document.getElementById("1").innerHTML = '-'
            document.getElementById("2").innerHTML = '-'
            document.getElementById("3").innerHTML = '-'
            document.getElementById("4").innerHTML = '-'
            document.getElementById("5").innerHTML = '-'
            document.getElementById("6").innerHTML = '-'
            document.getElementById("7").innerHTML = '-'
            document.getElementById("8").innerHTML = '-'
            document.getElementById("9").innerHTML = '-'
            turn = 0
            X1 = false
            X2 = false
            X3 = false
            X4 = false
            X5 = false
            X6 = false
            X7 = false
            X8 = false
            X9 = false
            O1 = false
            O2 = false
            O3 = false
            O4 = false
            O5 = false
            O6 = false
            O7 = false
            O8 = false
            O9 = false
          }
    </script>
  <table>
    <tr>
      <td align="center"><button id="1" onclick="Xon1()">-</button></td>
      <td align="center"><button id="2" onclick="Xon2()">-</button></td>
      <td align="center"><button id="3" onclick="Xon3()">-</button></td>
    </tr>
    <tr>
      <td align="center"><button id="4" onclick="Xon4()">-</button></td>
      <td align="center"><button id="5" onclick="Xon5()">-</button></td> 
      <td align="center"><button id="6" onclick="Xon6()">-</button></td>
    </tr>
    <tr>
      <td align="center"><button id="7" onclick="Xon7()">-</button></td>
      <td align="center"><button id="8" onclick="Xon8()">-</button></td>
      <td align="center"><button id="9" onclick="Xon9()">-</button></td>
    </tr>
  </table>
  <button onclick="Restart()">Restart</button>
  <h4 id="win"></h4>
  </body>
</html>

Hey I am new to stack overflow and yes I know it’s a lot of code but I’m working on learning loops and arrays to shorten it. Back to the point. Can anybody tell me why X gets two wins whenever they win. (To win go to the middle right, then bottom left, then bottom right, then top right.) It would be much appreciated if anybody could tell me why it is doing this. It would also be nice if anybody could give me a good link to learn loops and arrays that isn’t too confusing.

I need it to stop giving X two wins when they win. I have tried to copy and paste the O win and rename the variables so it applies to X and I also did the same for the function Xwins().

JavaScrript transform object array to specific date category array

I have a plain array of objects with a date as an attribute and want to transform that array based on that date with a specific date category.

const orders = [
  {
    "order_id": "1",
    "description": "Description 1",
    "date": "2024-02-03T19:00:57.744Z",
  },
  {
    "order_id": "2",
    "description": "Description 2",
    "date": "2024-02-04T19:00:57.744Z",
  },
  {
    "order_id": "3",
    "description": "Description 3",
    "date": "2024-02-06T19:00:57.744Z",
  },
]

Along with this, I have a date categories as below:

const category = [
  'Overdue',
  'Today',
  'Tomorrow',
  'This Week',
  'Next Week',
  'This Month',
  'Next Month',
  'Later',
  'No Date',
];

I need to transform a new array with specific date categories and categories should be sorted in this manner only (increasing date).

Expected output:

[
  {
    "category": "Today",
    "data": [
      {
        "order_id": "1",
        "description": "Description 1",
        "date": "2024-02-03T19:00:57.744Z"
      }
    ]
  },
  {
    "category": "Tomorrow",
    "data": [
      {
        "order_id": "2",
        "description": "Description 2",
        "date": "2024-02-04T19:00:57.744Z"
      }
    ]
  },
  {
    "category": "This Week",
    "data": [
      {
        "order_id": "3",
        "description": "Description 3",
        "date": "2024-02-06T19:00:57.744Z"
      }
    ]
  }
]

I’m using dayjs for date manipulations, and using the below function to check the date for a specific category

const getCategoryByDate = date => {

    if (date === null || date === undefined) {
      return 'No Date';
    }

    const isToday = dayjs(date).isToday();
    const isTomorrow = dayjs(date).isTomorrow();
    const overdue = dayjs().isAfter(date, 'day');
    const isThisYear = dayjs().year() === dayjs(date).year();
    const isThisWeek = isThisYear && dayjs().isoWeek() === dayjs(date).isoWeek();
    const isNextWeek = isThisYear && dayjs().isoWeek() + 1 === dayjs(date).isoWeek();
    const isThisMonth = isThisYear && dayjs().month() === dayjs(date).month();
    const isNextMonth = isThisYear && dayjs().month() + 1 === dayjs(date).month();

    if (overdue) {
      return 'Overdue';
    } else if (isToday) {
      return 'Today';
    } else if (isTomorrow) {
      return 'Tomorrow';
    } else if (isThisWeek) {
      return 'This Week';
    } else if (isNextWeek) {
      return 'Next Week';
    } else if (isThisMonth) {
      return 'This Month';
    } else if (isNextMonth) {
      return 'Next Month';
    }
    return 'Later';
  };

and finally using the array.reduce function to transform new desired array

const output = orders.reduce((acc, curr) => {
    const {date} = curr;
    const category = getCategoryByDate(date);
    const found = acc.find((item) => item.category === category);
    if (found) {
      found.data.push(curr);
    } else {
      const obj = {category: category, data: [curr]};
      acc = [obj];
    }
    return acc;
  }, []);

With this, I’m getting the result, but it’s not sorted order according to category if the order array is not sorted.

Razor Views and Javascript : Append to multiSelect not working

I am trying to append options to multiSelect. But the data is not reflected on UI.
However, I can see the change in DOM through chrome dev tools.

@Html.DropDownListFor(model => model.ProductAndServices,
 Model.ProductsAndServices.Select(item => new SelectListItem
 {
     Value = item.Key.ToString(),
     Text = item.Value,
     Selected = item.Key == Model.ProductId,
 }), htmlAttributes: new { @class = "form-control input-fields-normal dropdown-ie multiSelect", @id = "productAndServicesDDL", @multiple = "multiple", @placeHolder = "Select Products and Services", style = "width:300px; height:300px;" })


  $(function () {
       $('#productAndServicesDDL').change(function () {
       
       }).multipleSelect({
           width: '100%'
       });
   });

What I am trying to do is:

var option = $('<option></option>')
    .attr('value', 199)
    .text('Any Service XYZ')
    .prop('selected', true);

Trying to append the options

$('#productAndServicesDDL').append(option).change()
      

When I try to use the following, the multiSelect element gets allignment issues

$('#productAndServicesDDL').multiselect('refresh');

DiscordAPIError[10062]: Unknown interaction, When I want to get user points from database

     content: "You are already verified!",
            ephemeral: true,
          });
        }
      } else if (interaction.customId === "giverole") {

        const userPoints = await findUser(interaction.member.id);

        await interaction.reply({
          content: "Give role!",
          ephemeral: true,
        });
      };

But I get DiscordAPIError[10062]: Unknown interaction error. I want to get user points.

I want to get user point and print to consol.

localeCompare yields different results in different Node.js versions

localeCompare yields different results in different Node.js versions, and I am trying to find out exactly why this is happening.

Specifically, Node 12.22.12 vs 13.0.0

$ nvm use 12.22.12
Welcome to Node.js v12.22.12.
Type ".help" for more information.
> "topic".localeCompare("топик", "ru")
-1

$ nvm use 13.0.0
Welcome to Node.js v13.0.0.
Type ".help" for more information.
> "topic".localeCompare("топик", "ru")
1

Didn’t find anything in the Nodejs changelogs from 12 and 13

Only thing I could find was maybe this change in v8 engine on version 7.6, however, when I check the v8 version in the node 12.17.0 console, i get:

> console.log(process.versions.v8)
7.8.279.23-node.37

Which is higher than 7.6, so it can’t be that v8 change.

So, what’s causing Node 12.22.12 and Node 13.0.0 to yield different results when running

"topic".localeCompare("топик", "ru")

?

Note: running these locally on a Mac, but seeing same results in our Linux CI

Show alert on clicking image

I am trying to make it so that an alert pops up when you click the image but for some reason it doesn’t work and tells me I need to put a “)” even though one is already there. Someone pls help.

 <img src="descarga (3).png" height="20">
        <button 
        onclick=(alert('yay you clicked'))
        >
            click me!! </button>

Import error with pdfjs-dist. SyntaxError: import declarations may only appear at top level of a module

I am trying to extract text from a pdf using a js library called pdfjs-dist. It is giving me numerous errors no matter what method I try which seem to stem from the import.

I tried using Next.js and also a vanilla html/css/js project. It only works on the dev server with the vanilla method, but in deployment it gets blocked.

tried searching for answers for hours nothing works, chatGPT, google, the github repo.

Configuration:

  • Web browser and its version: Chrome or Firefox
  • Operating system and its version: MacOS12.6 and Windows11
  • PDF.js version:
    “pdfjs”: “^2.5.3”,
    “pdfjs-dist”: “^4.0.379”,

Issue was persistent whether I did it in a Next.js project , or with just plain HTML/CSS/JS.

importing in Next.js:

import pdfjsLib from "pdfjs-dist"; <- this doesn't cause the issue yet but when I do this: 
pdfjsLib.GlobalWorkerOptions.workerSrc  = '../../node_modules/pdfjs-dist/build/pdf.worker.mjs';

This causes:

Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of StaticGenerationSearchParamsBailoutProvider.

Importing in .js file in vanilla project:

I have this code in a .js file and it causes the error:

SyntaxError: import declarations may only appear at top level of a module`

import * as pdfjsLib from 'pdfjs-dist/build'

pdfjsLib.GlobalWorkerOptions.workerSrc =
  "../../node_modules/pdfjs-dist/build/pdf.worker.mjs";

async function extractText() {
  const fileInput = document.getElementById("fileInput");
  const file = fileInput.files[0];

  if (!file) {
    console.error("No file selected.");
    return;
  }

  const pdfData = await file.arrayBuffer();
  const loadingTask = pdfjsLib.getDocument(pdfData);

  loadingTask.promise.then(async function (pdf) {
    const page = await pdf.getPage(5);

    // Extract text from the PDF
    const textContent = await page.getTextContent();
    // const textItems = textContent.items.map((item) => item.str);
    // const extractedText = textItems.join(" ");

    // // Log the extracted text to the console
    // console.log("Extracted Text:", extractedText);
    let extractedNumber = 0;
    textContent.items.forEach((item) => {
      if (
        item.str.toLowerCase().includes("watt") ||
        item.str.includes("wh") ||
        item.str.includes("rating")
      ) {
        const numbers = item.str.match(/d+/g);
        if (numbers) {
          extractedNumber = parseInt(numbers[0]);
          console.log(extractedNumber); // Output: 123
        } else {
          console.log("No numbers found in the string");
        }
      }
    });

    const inputElement = document.getElementById("wattHours");

    // Check if the input element exists
    if (inputElement) {
      // Set the value of the input element
      inputElement.value = extractedNumber;
    } else {
      console.error("Input element not found.");
    }
  });
}

// Define the function in the global scope
window.extractText = extractText;

Importing in directly in HTML:

This actually works in development, i’m able to successfully take a pdf input and parse and extract data from it. But when I deploy it on netlify or vercel, it gets blocked due to some TextMIME error about websniffing?

<script src="../node_modules/pdfjs-dist/build/pdf.mjs" type="module"></script>

<script id="script" type="module">
      pdfjsLib.GlobalWorkerOptions.workerSrc =
        "../../node_modules/pdfjs-dist/build/pdf.worker.mjs";

      async function extractText() {
        const fileInput = document.getElementById("fileInput");
        const file = fileInput.files[0];

        if (!file) {
          console.error("No file selected.");
          return;
        }

        const pdfData = await file.arrayBuffer();
        const loadingTask = pdfjsLib.getDocument(pdfData);

        loadingTask.promise.then(async function (pdf) {
          const page = await pdf.getPage(5);

          // Extract text from the PDF
          const textContent = await page.getTextContent();
          // const textItems = textContent.items.map((item) => item.str);
          // const extractedText = textItems.join(" ");

          // // Log the extracted text to the console
          // console.log("Extracted Text:", extractedText);
          let extractedNumber = 0;
          textContent.items.forEach((item) => {
            if (
              item.str.toLowerCase().includes("watt") ||
              item.str.includes("wh") ||
              item.str.includes("rating")
            ) {
              const numbers = item.str.match(/d+/g);
              if (numbers) {
                extractedNumber = parseInt(numbers[0]);
                console.log(extractedNumber); // Output: 123
              } else {
                console.log("No numbers found in the string");
              }
            }
          });

          const inputElement = document.getElementById("wattHours");

          // Check if the input element exists
          if (inputElement) {
            // Set the value of the input element
            inputElement.value = extractedNumber;
          } else {
            console.error("Input element not found.");
          }
        });
      }
      // Define the function in the global scope
      window.extractText = extractText;
    </script>

can’t find answers anywhere. nothing’s working

I tried saving my .js file as a .mjs file, that just ends up getting blocked again.
i tried putting type: module in my package.json file
I tried downloading the files and importing from there

Can not import and require js-cookie package to my api

I used too many ways to use this package in order to get the JWT from the server and set it to the browser but still not able to that. I share all my codes here also my git repo.

https://github.com/acupoflie/sirbookstore

I checked all the documents in stack also in github which wrote by who have encountered this problem, and did all the things which commented as a answer. But still does not work.

authLogin.js

// import Cookies from '../../../node_modules/js-cookie';
// import * as Cookies from 'js-cookie';

const jsCookie = require('js-cookie');


document.getElementById('loginForm').addEventListener('submit', function(event) {
    event.preventDefault();

    fetch('http://localhost:3355/auth/login', {
        method: 'POST',
        headers: {
            'Content-type': 'application/json'
        },
        body: {
            email: document.getElementById('email').value,
            password: document.getElementById('password').value
        }
    })
    .then(res => res.json())
    .then(data => {
        const jwtToken = data.token;

        console.log('JWT token has received', jwtToken);

        jsCookie.set('jwtTokens', jwtToken, {expires: 1});

        windows.location.href = '/index.html'
    })

})

login.html

    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/jquery.scrolly.min.js"></script>
    <script src="assets/js/jquery.scrollex.min.js"></script>
    <script src="assets/js/main.js"></script>
    <script src="scripts/accountNavBar.js"></script>
    <script type="module" src="scripts/authLogin.js"></script>
    <script type="module" src="scripts/js-cookie.js"></script>
    <script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>

trying to set the jwt to the browser which comes from the server

MathJax tex2svg doesn’t render directly to SVG

This will probably come across as a fast question without research, but I’ve been off-track for hours trying to figure it out.

I lately tried MathJax for the first time and I made a textarea that converted the text to an svg dynamically. Then I would save the svg and use it in other places. I used tex2svg. I remember it well. Now I tried to reuse it to render the svg to a canvas, which itself is easy, but now all I can get is a weird <mjx-container> element instead of paths. Documentation is much less than enough to cover this library and I can’t find any way to get back a pure <svg> element. Please help me.

I know that you can still render the image from the <math> element under <mjx-container>><mjx-assistive-mml>, but in my case, loading into an HTMLImageElement with data:image/svg+xml will put the image in a broken state, so that’s a last resort.

HTML video tag sends range header as bytes=0- in the first request and then doesn’t request for the next required chunks of the file

I am trying to build a video streaming platform, from the frontend via <video> tag streaming request are sent, but the browser embeds range header for the first request as bytes=0-, inside the backend part I send a partial request (206) with chunked data and set all the required headers like

const headers = {
  "Content-Range": "bytes " + start + "-" + end + "/" + file.length,
  "Content-Length": contentLength,
  "Accept-Ranges": "bytes",
  "Content-Type": `video/mp4`,
};

Now the subsequent request should be for the next chunk from the browser, but the browser sends the request with header for the last chunk, skipping the parts of the response. This is demonstrated in the below image:
enter image description here

I have tried manipulating the range headers coming from the frontend in the middleware functions in the backend but whatever I do, the next subsequent request is of the nearly max length – so the browser skips the parts in between.

For side note, i am creating a openDownloadStream from GridFS of the mongoDB for reading the data.