Catching body data in PHP

foodData = []

for ( i = 0 ; i < allCartBox.length ; i++){
    
    aCardBox = document.getElementsByClassName('cart-box')[i];
    title = aCardBox.getElementsByClassName("cart-product-title")[0].innerText;
    money = aCardBox.getElementsByClassName("cart-price")[0].innerText;
    qty = aCardBox.getElementsByClassName("cart-number")[0].value;

    var foodFormData = {
        'name' : title,
        'money' : money ,   
        'qty' : qty,
    }

    foodData.push(foodFormData)
}

var url = 'addCart.php'

fetch(url, {
    method : 'POST',
    body : foodData 
}).then(response => response.text()).then(response => {
    console.log(response);
}).catch(error => console.log(error));

I have this in my javascript file. I sent data using fetch api.

Now how to catch the body being sent from fetch in PHP.

How do I group data that is nested in an array?

I have a array of objects and then inside each of the object I have another array, I want to group the data inside the object array according to their category name. I tried doing it with a reduce function but it is basically giving me the same data(it is not even transformed), It’s like it is not even calling.

My Data

data = [
    {
        name: "listName",
        id:434343,
        data: [
            {
                id:434343,
                categoryName: school, 

            }, 
            {
                id:234343,
                categoryName: house, 
                
            },
            {
                id:2000,
                categoryName: school, 
                
            },
            {
                id:2333,
                categoryName: house, 
                
            }
        ]
    }, 
    {
        name: "anotherListName",
        id:434343,
        data: [
            {
                id:434343,
                categoryName: school, 

            }, 
            {
                id:234343,
                categoryName: house, 
                
            },
            {
                id:2000,
                categoryName: school, 
                
            },
            {
                id:2333,
                categoryName: house, 
                
            }
        ]
    }
]

my code

list.forEach(d =>
    d.data.reduce((acc, currrent) => {
      (acc[currrent.categoryName] = acc[currrent.categoryName] || []).push(
        currrent
      )
      return acc
    }, {})
  )

How I want the data to be transformed

transformed = [
    {
        name: "listName",
        id:43453,
        data: {
            school: [
               {
                id:434343,
                categoryName:school   
               }, 
               {
                id:2000,
                categoryName:school   
               }, 
            ],
            house: [
               {
                id:234343,
                categoryName:house   
               }, 
               {
                id:2333,
                categoryName:house   
               }, 
            ],
        } 
    },
    {
        name: "listName",
        id:43453,
        data: {
            school: [
               {
                id:434343,
                categoryName:school   
               }, 
               {
                id:2000,
                categoryName:school   
               }, 
            ],
            house: [
               {
                id:234343,
                categoryName:house   
               }, 
               {
                id:2333,
                categoryName:house   
               }, 
            ],
        } 
    },
]

JavaScript is a high-level, prototype-based, object-oriented, multi-paradigm, interpreted or just-in-time compiled, dynamic, single-threaded

JavaScript is a high-level, prototype-based, object-oriented, multi-paradigm, interpreted or just-in-time compiled, dynamic, single-threaded, garbage-collected programming language with first-class functions and a non-blocking event loop concurrency model.
After seeing this javascript definition eventually, it blew my mind.
What does all of these mean, I googled it. but I am not understanding the words in bold. please help me to understand these topics in your own words.

Toggle Visibility of an Uncontrollable Element in React

I have Hubspot chat script embedded in my React App using the <script/> tag for user communication.

Now, when a button is clicked I want the hubspot container to be hidden and then when another button is clicked I want it to be displayed again.

I do not have control over the behaviour of the chat icon because it was added to the page via a <script/> tag.

But after some digging I was able to get the id of the element so here is how I’ve tried toggling the visibility of the chat but it’s not working for me.

const toggleHubspotContainer = (turnOn) => {
        let hubSpotContainer = document.getElementById("hubspot-messages-iframe-container");
        if (turnOn) {
            hubSpotContainer.style.display = 'block';
            return;
        }
        hubSpotContainer.style.display = 'none'; //The chat icon is not hiding even after this
    }

Is there a way to do this properly?

Thank you.

How to execute TipTap commands from script tag in Vue 3?

I’m having following component:

<button @click="$refs.image.click(); editor.chain().focus().setImage({ src: state.image }).run()"></button>

<input type="file" ref="image" style="display: none" @change="getImageUrl">

The button uses the file input to access its upload image ui. Problem is that getImageUrl is an async function and:

editor.chain().focus().setImage({ src: state.image }).run()

gets executed before state.image is set resulting in an undefined img src.

My approach is to put:

editor.chain().focus().setImage({ src: state.image }).run()

inside its own async function but how do I call the chain command from vue 3's script tag? The docs do not seem to explain how to call it from outside of vue directives.

getImageUrl:

const getImageUrl = (event) => {
    const files = event.target.files;
    if (!files.length)
        return;
    const reader = new FileReader();
    reader.onload = (event) => {
        state.image = event.target.result;
    };
    reader.readAsDataURL(files[0]);
}

Javacript [ document.write (“___”); ] Shortcut to not start each line with document.write (“

In this code I want to insert some HTML and normal text in JavaScript and don’t want it to always enter document.write(" in starting of each line like:

document.write("some text
some text
some text");

Instead of this:

document.write("Hello World!");
document.write("Have a nice day!");
document.write("<br>");
document.write("<p>some random paragraph");

document.write("Hello World!");
document.write("Have a nice day!");
document.write("<br>");
document.write("<p>some random paragraph");

Session Management | How does Netflix detect the number of active users in a Netflix account?

Netflix limits the number of active users / sessions in the app to 4 concurrent user sessions per account. I am curious as to what kind of session management strategy do they use?

To prevent an additional user session post 4 concurrent ones, do they use pure Javascript based checks or is there a layer of backend based session management in place as well ?

value in input is undefined

I’m making AP calculator but the answer value is undefined in the input field of answer having id “An”
please help;
here’s my code:

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>JavaScript Example</title>
</head>

<body>
    <!-- first term -->
    <input type="text" value="1" name="" id="a1" onkeyup="ap()">
    <!-- number of term -->
    <input type="text" value="2" name="" id="n" onkeyup="ap()">
    <!-- difference -->
    <input type="text" name="" value="3" id="d" onkeyup="ap()">
    <input type="text" name="" id="An">

    <script>
        ap()

        function ap() {
            let a1 = document.getElementById("a1").value;

            let n = document.getElementById("n").value;
            let d = document.getElementById("d").value;
            var An = Number(a1) + ((Number(n) - 1) * Number(d));
            console.log(An)
            document.getElementById("An").value = An.value
        }
    </script>
</body>

</html>

please help in solving the issue.

How to make line breaks when displaying the content of a textarea?

I’m trying to do a forum in php.
I have a problem. I have a publish form with a textarea. Let’s imagine that I fill it all.

When I make a line break (when I press space bar), with nl2br, in my database there are <br> tags added. But when I just type and there is an auto line break, there is no <br>.

How can I do to, for example, at the end of 100 chars, there is an auto line break (that adds a <br> in the database. I’ve tried in Javascript but I didn’t found a correct answer.

With

with <br>

In the database

Without

auto line break in textarea (no <br>)

in the database

Problem:

in the forum (text outside of the div

Crop a rectangle with coordinates relative to a rotated image in HTML Canvas

I have the following crop coordinates of an image:

crop information relative to the rotated image

The coordinates are relative to the rotated image’s height and width. The rotation origin is the centre of the crop rectangle.

My goal here is to use the drawImage call and the crop information above and render the following image:

enter image description here

My approach so far is:

  1. Rotate the image first.

  2. Translate the coordinates shown above to be relative to the container.

  3. Call drawImage with the canvas containing the rotated image as the source and the translated coordinates.

    drawImage(rotatedCanvas, rotatedX, rotatedY, cropWidth, cropHeight, 0, 0, width, height)

Issues:

  • I’m not sure how to find the centre point of the crop rectangle given the
    crop information above. Without this, I cannot set the correct
    origin for the rotation of the image

  • Without finding this centre point, I cannot use the following code to rotate the coordinates correctly.

// cx origin x, cy origin y
const rotate = (cx: number, cy: number, x: number, y: number, angle: number) => {
  const radians = (Math.PI / 180) * angle;
  const cos = Math.cos(radians);
  const sin = Math.sin(radians);
  const nx = cos * (x - cx) + sin * (y - cy) + cx;
  const ny = cos * (y - cy) - sin * (x - cx) + cy;
  return { nx, ny };
};

To be honest, I’m not sure if I’m going about this the wrong way completely.

Any advice would be greatly appreciated! Many thanks.

For loop does not appear to be executing with the slightest sign, does anyone have any solutions?

Strangely the for loop doesn’t appear to be called. The alert will say 1 but 2 will not show. There aren’t any errors in the console, and online code checkers (Specifically JShint.com) say nothing is wrong at all.

window.onLoad = function() {
    var l = 1;
    const S = "Spawn";
    const N = "Next";
    const K = "Kill";
    const LEVEL = [
        [
            [5, 5],
            [1, 1, 1, 1, 1],
            [1, 0, 0, 0, 1],
            [1, S, K, N, 1],
            [1, 0, 0, 0, 1],
            [1, 1, 1, 1, 1]
        ]
    ]
    const PSIZE = 54;
    var SCR = document.getElementById("SCR");
    const context = SCR.getContext("2d");
    drawMap();
}

function drawMap() {
    let w = LEVEL[l - 1][0][0];
    let h = LEVEL[l - 1][0][1];
    alert("1")
    for(let lx = 0; lx == w - 1; lx += 1) {
        for(let ly = 1; ly == h; ly += 1) {
            let tile = LEVEL[l - 1][ly][lx];
            switch(tile) {
                case 1:
                    context.fillColor = "grey";
                    break;
                case 0:
                    context.fillColor = "white";
                    break;
                default:
                    context.fillColor = "red";
                    break;
                    
            }
            alert(2)
            context.fillRect(((lx + 1) * PSIZE), ((ly + 1) * PSIZE), PSIZE, PSIZE);
        }
    }
}

ERROR #98123 WEBPACK when running `npm run develop`

I would like to create a new Gatsby site using the instructions on https://www.gatsbyjs.com/docs/quick-start , so I ran:

npm init gatsby  # see note below
cd my-gatsby-site
npm run develop

Note: I didn’t change any configuration, so I’m using JavaScript (instead of TypeScript), not using a CMS, not using a styling system, and installed no additional features.

During running npm run develop, I’m getting the following error:

> [email protected] develop
> gatsby develop

success compile gatsby files - 0.812s
success load gatsby config - 0.020s
success load plugins - 0.198s
success onPreInit - 0.001s
success initialize cache - 0.121s
success copy gatsby files - 0.113s
success Compiling Gatsby Functions - 0.277s
success onPreBootstrap - 0.294s
success createSchemaCustomization - 0.001s
success Checking for changed pages - 0.001s
success source and transform nodes - 0.065s
success building schema - 0.143s
success createPages - 0.008s
success createPagesStatefully - 0.044s
info Total nodes: 24, SitePage nodes: 4 (use --verbose for breakdown)
success Checking for changed pages - 0.001s
success write out redirect data - 0.041s
success onPostBootstrap - 0.002s
info bootstrap finished - 5.190s
success onPreExtractQueries - 0.002s
success extract queries from components - 0.082s
success write out requires - 0.005s
success run page queries - 0.017s - 3/3 174.40/s

 ERROR #98123  WEBPACK

Generating development JavaScript bundle failed

You must provide the URL of lib/mappings.wasm by calling SourceMapConsumer.initialize({
'lib/mappings.wasm': ... }) before using SourceMapConsumer

File: .cache/app.js


 ERROR #98123  WEBPACK

Generating development JavaScript bundle failed

You must provide the URL of lib/mappings.wasm by calling SourceMapConsumer.initialize({
'lib/mappings.wasm': ... }) before using SourceMapConsumer

File: .cache/polyfill-entry.js

failed Building development bundle - 8.585s
ERROR in ./.cache/app.js
Module build failed (from 
./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js):
Error: You must provide the URL of lib/mappings.wasm by calling 
SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer
    at readWasm
(/Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/source-map/lib/read-wasm.js:8:13)
    at wasm
(/Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/source-map/lib/wasm.js:25:16)
    at /Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/source-map/lib/source-map-co
nsumer.js:264:14
    at Object._loader (/Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/@pmmmwh/reac
t-refresh-webpack-plugin/loader/index.js:81:9)

ERROR in ./.cache/polyfill-entry.js
Module build failed (from 
./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js):
Error: You must provide the URL of lib/mappings.wasm by calling 
SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer
    at readWasm
(/Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/source-map/lib/read-wasm.js:8:13)
    at wasm
(/Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/source-map/lib/wasm.js:25:16)
    at /Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/source-map/lib/source-map-co
nsumer.js:264:14
    at Object._loader (/Users/xfq/test/gatsby-test/my-gatsby-site/node_modules/@pmmmwh/reac
t-refresh-webpack-plugin/loader/index.js:81:9)

develop compiled with 2 errors
success Writing page-data.json files to public directory - 0.099s - 3/4 40.45/s

Environment:

node 18.3.0
npm 8.11.0
OS: macOS 12.4

I’m not sure how to debug this problem. Can anyone point me in the right direction?

Trying to display “trade options” to a user based on the games they have in their library. Is there a faster way to do this?

I’m trying to build a platform where each user is able to add games to their library, under either the “owned” or “wanted” categories, and then it is the platform’s responsibility to find possible trade options.

For example, if user A has game A in their owned list, and user B wants game A, and owns games C and D, then user A will see games C and D under their possible trade options, in return for game A.

Currently, I’ve implemented this somewhat crudely using too many nested DB queries and I feel like there’s a faster way to do this.

The following is what happens every time a user wants to see all of their trade options.

let foundUser = await User.findById({_id: req.session.user_id})

let gamesList = []
    //for each game in the users have library, search it up in the game DB and add wantedBy users to an array
    for (let i = 0; i < foundUser.library.have.length; i++){
        let foundGame = await Game.findById({_id: foundUser.library.have[i].gameID})
        //for this game, add each user in the WantedBy List to a local array
        for (let j = 0; j < foundGame.wantedBy.length; j++){
            //for each of these users, use their have list to build the trade object
            let newFoundUser = await User.findById({_id: foundGame.wantedBy[j]})

            //check if the other user wants the game for the same platform as foundUser.library.have[i].platform
            console.log(newFoundUser)
            console.log(foundGame.wantedBy)
            let platformMatch = newFoundUser.library.want.find(game => (game.platform === foundUser.library.have[i].platform) && (game.gameID == foundUser.library.have[i].gameID))
            
            if (platformMatch){

                for (let k = 0; k < newFoundUser.library.have.length; k++){
                    //for each of these games in the other users have list, make a trade object
                    let newFoundGame = await Game.findById({_id: newFoundUser.library.have[k].gameID})
                    let tradeObject = {
                        gameOffered: newFoundUser.library.have[k].gameID,
                        gameOfferedBackImg: newFoundGame.backImg,
                        gameOfferedPlatform: newFoundUser.library.have[k].platform,
                        gameOfferedTitle: newFoundGame.title,
                        inReturnForTitle: foundGame.title,
                        inReturnForPlatform: foundUser.library.have[i].platform,
                        inReturnFor: foundGame._id,
                        otherUserID: newFoundUser._id
                    }
                    gamesList.push(tradeObject)
                }
            }
        }
        
    }


res.render('trade', {gamesList: gamesList, mainUser: foundUser._id})

The nested loops and DB queries make this really slow, especially if the no. of users and the no. games in their library increases.

The following are the DB schemas:

The User Schema:

username: {
    type: String,
    required: ['true', 'Username cannot be blank'],
},
email: {
    type: String,
    required: ['true', 'Email cannot be blank']
},
password: {
    type: String,
    required: ['true', 'Password cannot be blank'],
},
phoneNum: {
    type: String,
    required: true,
    unique: true
},
isVerified: false,
address: {
    city: String,
    area: String,
    street: String,
    nearestLandmark: String
},
verificationCode: String,
library: {
    have: [{
        gameID: String,
        platform: String
    }],
    want: [{
        gameID: String,
        platform: String
    }]
},
notifications: [
    {
        dateTime: Date,
        message: String
    }
]

})

The Game Schema:

const gameSchema = new mongoose.Schema({
title: String,
backImg: String,
wantedBy: [String]

})

Any help optimising this would be greatly appreciated. Thank you!