javascript : How to handle chage event handler for multiple checkbox in single function and print whick checkbox clicked

Description

i have multiple checkbox and want handle all checkbox click event in single handler function
and want to know which is checked.i tried below code and not working

document.addEventListener('DOMContentLoaded', function () {
    document.querySelector('#Checkbox1').addEventListener('change', changeHandler("Checkbox1"));
    document.querySelector('#Checkbox2').addEventListener('change', changeHandler("Checkbox2"));
    document.querySelector('#Checkbox3').addEventListener('change', changeHandler("Checkbox3"));
    document.querySelector('#Checkbox4').addEventListener('change', changeHandler("Checkbox4"));
    document.querySelector('#Checkbox5').addEventListener('change', changeHandler("Checkbox5"));
});
function changeHandler(checkboxs) {
    //Do Something...maybe another function showAlert(), for instance
    if (checkboxs.checked) {
        console.log("Checkbox checked");
    }
    else {
        console.log("Checkbox unchecked");
    }
}
<!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
<body>
    <div>
    Checkbox1: <input type="checkbox" id="Checkbox1">
  </div>
    <div>
    Checkbox2: <input type="checkbox" id="Checkbox2">
  </div>
    <div>
    Checkbox3: <input type="checkbox" id="Checkbox3">
  </div>
    <div>
    Checkbox4: <input type="checkbox" id="Checkbox4">
  </div>
  <div>
    Checkbox5: <input type="checkbox" id="Checkbox5">
  </div>
</body>
</html>

WebGL – Drawing 3-D Sphere recursively with triangles

So, my goal is to be able to render a 3-D sphere(sorry for the redundancy) by using recursive subdivision, here is the image the textbook gives as an example:
Sphere approximations using subdivision

The textbook is not very helpful overall, with anything really, I did attempt to ask my professor for help with this and his response was “Google it”. So I did, and I managed to piece together what I thought would work, but sadly I cannot actually get anything to render, and I am completely lost as to why. I don’t know if I have just been staring at this for so long I am missing something completely obvious or what, but I would really appreciate any help anyone could offer.

<!doctype html>
<html>
   <body>
    <canvas width = "600" height = "600" style="border:1px solid #000000" id="sphere_canvas"></canvas>

    <script>
        var gl1;

        function initgl1(canvas) {
            try {
                gl1 = canvas.getContext("experimental--webgl1");
                gl1.viewportWidth = canvas.width;
                gl1.viewportHeight = canvas.height;
            } catch (e) {
            }
            if (!gl1) {
                alert("we Couldnt initialise Webgl1 , sorry :-(");
            }
        }


        function getShader(gl1, id) {
            var shaderScript = document.getElementById(id);
            if (!shaderScript) {
                return null;
            }

            var str = "";
            var k = shaderScript.firstChild;
            while (k) {
                if (k.nodeType == 3) {
                    str += k.textContent;
                }
                k = k.nextSibling;
            }

            var shader;
            if (shaderScript.type == "x- shader/x-fragment") {
                shader = gl1.createShader(gl1.FRAGMENT_SHADER);
            } else if (shaderScript.type == "x- shader/x-vertex") {
                shader = gl1.createShader(gl1.VERTEX_SHADER);
            } else {
                return null;
            }

            gl1.shaderSource(shader, str);
            gl1.compileShader(shader);

            if (!gl1.getShaderParameter(shader, gl1.COMPILE_STATUS)) {
                alert(gl1.getShaderInfoLog(shader));
                return null;
            }

            return shader;
        }


        var shaderProgram;

        function initShaders() {
            var fragmentShader = getShader(gl1, "shader-fs");
            var vertexShader = getShader(gl1, "shader-vs");

            shaderProgram = gl1.createProgram();
            gl1.attachShader(shaderProgram, vertexShader);
            gl1.attachShader(shaderProgram, fragmentShader);
            gl1.linkProgram(shaderProgram);

            if (!gl1.getProgramParameter(shaderProgram, gl1.LINK_STATUS)) {
                alert("Could not initialise shaders");
            }

            gl1.useProgram(shaderProgram);

            shaderProgram.vertexPositionAttribute = gl1.getAttribLocation(shaderProgram, "aVertexPosition");
            gl1.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

            shaderProgram.vertexColorAttribute = gl1.getAttribLocation(shaderProgram, "aVertexColor");
            gl1.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

            shaderProgram.pMatrixUniform = gl1.getUniformLocation(shaderProgram, "uPMatrix");
            shaderProgram.mvMatrixUniform = gl1.getUniformLocation(shaderProgram, "uMVMatrix");
        }


        var mvMatrix = mat4.create();
        var mvMatrixStack = [];
        var pMatrix = mat4.create();

        function mvPushMatrix() {
            var copy = mat4.create();
            mat4.copy(copy, mvMatrix);
            mvMatrixStack.push(copy);
        }

        function mvPopMatrix() {
            if (mvMatrixStack.length == 0) {
                throw "Invalid popMatrix!";
            }
            mvMatrix = mvMatrixStack.pop();
        }


        function setMatrixUniforms() {
            gl1.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
            gl1.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
        }


        function degToRad(degrees) {
            return degrees * Math.PI / 180;
        }

        var sphereVertexPositionBuffer;
        var sphereVertexColorBuffer;
        var sphereVertexIndexBuffer;

        function initBuffers() {
            var latitudeBands = 10;
            var longitudeBands = 10;
            var radius = 2;

            sphereVertexPositionBuffer = gl1.createBuffer();
            gl1.bindBuffer(gl1.ARRAY_BUFFER, sphereVertexPositionBuffer);
            sphereVertexColorBuffer = gl1.createBuffer();
            gl1.bindBuffer(gl1.ARRAY_BUFFER, sphereVertexColorBuffer);
            sphereVertexIndexBuffer = gl1.createBuffer();
            gl1.bindBuffer(gl1.ELEMENT_ARRAY_BUFFER, sphereVertexIndexBuffer);

            var vertexPositionData = [];
            var colors = [];
            var indexData = [];
            for (var latNumber=0; latNumber < latitudeBands; latNumber++) {
                var theta = latNumber * Math.PI / latitudeBands;
                var sinTheta = Math.sin(theta);
                var cosTheta = Math.cos(theta);

                for (var longNumber=0; longNumber < longitudeBands; longNumber++) {
                    var phi = longNumber * 2 * Math.PI / longitudeBands;
                    var sinPhi = Math.sin(phi);
                    var cosPhi = Math.cos(phi);

                    var x = cosPhi * sinTheta;
                    var y = cosTheta;
                    var z = sinPhi * sinTheta;

                    colors = [[1.0, 1.0, 0.3, 1.0]];
                    vertexPositionData.push(radius * x);
                    vertexPositionData.push(radius * y);
                    vertexPositionData.push(radius * z);

                    var first = (latNumber * (longitudeBands + 1)) + longNumber;
                    var second = first + longitudeBands + 1;
                    indexData.push(first);
                    indexData.push(second);
                    indexData.push(first + 1);

                    indexData.push(second);
                    indexData.push(second + 1);
                    indexData.push(first + 1);
                }
            }

            var unpackedColors = [];
            for (var i in colors) {
                var color = colors[i];
                for (var j=0; j < 4; j++) {
                    unpackedColors = unpackedColors.concat(color);
                }
            }

            gl1.bufferData(gl1.ARRAY_BUFFER, new Float32Array(vertexPositionData), gl1.STATIC_DRAW);
            sphereVertexPositionBuffer.itemSize = 3;
            sphereVertexPositionBuffer.numItems = vertexPositionData.length / 3;

            gl1.bufferData(gl1.ARRAY_BUFFER, new Float32Array(unpackedColors), gl1.STATIC_DRAW);
            sphereVertexColorBuffer.itemSize = 4;
            sphereVertexColorBuffer.numItems = unpackedColors.length / 4;

            gl1.bufferData(gl1.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), gl1.STATIC_DRAW);
            sphereVertexIndexBuffer.itemSize = 1;
            sphereVertexIndexBuffer.numItems = indexData.length;

        }


        var rSphere = 0;

        function drawScene() {
            gl1.viewport(0, 0, gl1.viewportWidth, gl1.viewportHeight);
            gl1.clear(gl1.COLOR_BUFFER_BIT | gl1.DEPTH_BUFFER_BIT);

            mat4.perspective(pMatrix, 60, gl1.viewportWidth / gl1.viewportHeight, 0.1, 100.0);

            mat4.identity(mvMatrix);

            mat4.translate(mvMatrix, mvMatrix, [0.0, 0.0, -5.0]);

            mvPushMatrix();
            mat4.rotate(mvMatrix, mvMatrix, degToRad(rSphere), [1, 1, 1]);

            gl1.bindBuffer(gl1.ARRAY_BUFFER, sphereVertexPositionBuffer);
            gl1.vertexAttribPointer(shaderProgram.vertexPositionAttribute, sphereVertexPositionBuffer.itemSize, gl1.FLOAT, false, 0, 0);

            gl1.bindBuffer(gl1.ARRAY_BUFFER, sphereVertexColorBuffer);
            gl1.vertexAttribPointer(shaderProgram.vertexColorAttribute, sphereVertexColorBuffer.itemSize, gl1.FLOAT, false, 0, 0);

            gl1.bindBuffer(gl1.ELEMENT_ARRAY_BUFFER, sphereVertexIndexBuffer);
            setMatrixUniforms();
            gl1.drawElements(gl1.TRIANgl1ES, sphereVertexIndexBuffer.numItems, gl1.UNSIGNED_SHORT, 0);

            mvPopMatrix();

        }


        var lastTime = 0;

        function animate() {
            var timeNow = new Date().getTime();
            if (lastTime != 0) {
                var elapsed = timeNow - lastTime;

                rSphere -= (75 * elapsed) / 1000.0;
            }
            lastTime = timeNow;
        }


        function tick() {
            requestAnimFrame(tick);
            drawScene();
            animate();
        }


        function webgl1Start() {
            var canvas = document.getElementById("sphere_canvas");
            initgl1(canvas);
            initShaders()
            initBuffers();

            gl1.clearColor(0.0, 0.0, 0.1, 1.0);
            gl1.enable(gl1.DEPTH_TEST);

            tick();
        }
    </script>
   </body>
</html>

Choose dropdown list item in selenium webdriver using javascript

I’ve been struggling to choose dropdown list item in selenium webdriver using javascript.
I’m tasked to open https://pastebin.com/ then choose "10 Minutes" from dropdown list using selenium webdriver javascript.
I’ve achieved to open the dropdown list with the following method:

await driver.findElement(By.id(`postform-expiration`)).click()

Tried to select dropdown list item both li value and id:

await dropdown.findElement(By.css(`li[value="10 Minutes"]`)).click()
// and
await driver.findElement(By.css(`//*[@id="select2-postform-expiration-result-b5nq-10M"]`)).click()

But none of them could choose the dropdown list item.

The structure of the dropdown list is as follows:

<div class="col-sm-9 field-wrapper">
<select id="postform-expiration" class="form-control select2-hidden-accessible" name="PostForm[expiration]" data-s2-options="s2options_7ebc6538" data-krajee-select2="select2_a09a7382" style="width: 1px; height: 1px; visibility: hidden;" data-select2-id="postform-expiration" tabindex="-1" aria-hidden="true">
<option value="N" data-select2-id="4">Never</option>
<option value="B" data-select2-id="11">Burn after read</option>
<option value="10M" data-select2-id="12">10 Minutes</option>
<option value="1H" data-select2-id="13">1 Hour</option>
<option value="1D" data-select2-id="14">1 Day</option>
<option value="1W" data-select2-id="15">1 Week</option>
<option value="2W" data-select2-id="16">2 Weeks</option>
<option value="1M" data-select2-id="17">1 Month</option>
<option value="6M" data-select2-id="18">6 Months</option>
<option value="1Y" data-select2-id="19">1 Year</option>
</select><span class="select2 select2-container select2-container--default select2-container--open select2-container--above select2-container--focus" dir="ltr" data-select2-id="3" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="0" aria-disabled="false" aria-labelledby="select2-postform-expiration-container" aria-owns="select2-postform-expiration-results" aria-activedescendant="select2-postform-expiration-result-e4wf-1D"><span class="select2-selection__rendered" id="select2-postform-expiration-container" role="textbox" aria-readonly="true" title="Never">Never</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

</div>

I appreciate your help. Thanks in advance!

change text input value based on check box, multiple fields with same class name

I have many checkboxes and below each there is a hidden date field.
I need to show the div with the date field and select different date.
in the begging I need to add 30 days from today when the checkbox is checked by deafutl, then the user can change the date.
When I click to first choice and change the date is ok….but when I click to another the first date field takes the default value. Any sggestions?

$('.chkPages').change(function () {
        
        if (this.checked)
        {
            var dateStr = new Date();
            dateStr.setDate(dateStr.getDate() + 30)
            dateStr = dateStr.getDate() + "/" + (dateStr.getMonth() + 1) + "/" + 
            dateStr.getFullYear();
           
            $(this).closest('div').next('.extrafields').fadeIn('slow');
           
            $(".DurationDate").val(dateStr);
        }

        else {
            dateStr = "";
            $(this).closest('div').next('.extrafields').fadeOut('slow');
            $(".DurationDate").val(dateStr);
        }

Why function is not returning the value [closed]

var y=0;
var x=0;
function randomNumber1(){
  x=Math.floor((Math.random())*6)+1;
  console.log(x);
  return x;
}
function randomNumber2(){
  y=Math.floor((Math.random())*6)+1;
console.log(y);
  return y;
}
randomNumber1();
randomNumber2();
console.log(randomNumber1);
console.log(randomNumber2);

Im not getting the returned value in the function. the function is displaying all the codes as its value.

function randomNumber1() and randomNumber2() are not being returned.

Dynamic PageNumbers for Flipbook using turn.js

So, I was given a task of creating a Custom Flipbook, where using images in div tags, I was successful in creating one. Users could turn pages using prev/next buttons or flipping through them by the corners like shown for other Flipbooks.

My concern is Displaying PageNumbers. Changing pages through the buttons, pages change dynamically but when flipping through turn.js the page number does not update.

I am providing the snippet of the code that I have used. Any kind of help and guidance is appreciated !!

<!DOCTYPE html>

<head>
  <title>Flipbook Demo</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script type="text/javascript" src="turn.min.js"></script>
</head>
<style>
  body{
    background-color: #313131;
  }

  #flipbook {
    margin-top: 1.5%;
    margin-left: 6%;
    width: 1130px;
    height: 800px;
    position: relative;
    overflow: hidden;
  }

  #nav_controls{
      margin: 1.5%;
      margin-left: 44%;
  }
  
</style>
    <body> 
        <h1 style="color: white; margin-left: 43%">FITI5 WHITEPAPER</h1>
        <div id="flipbook">
            <!-- Include Pages into div that you want to include -->
        </div>
        
        <div id="nav_controls">
            <button id="startdoc"><-</button>
            <button id="prev_page"> PREV </button>
            <span id="pgnos" style="margin-left: 2%; color: white;">1</span>   
            <button id="next_page" style="margin-left: 2%;"> NEXT </button>
            <button id="enddoc">-></button>
            <!--
            <button id="zoom-in">+</button>
            <buton id="zoom-out">-</button>-->
        </div>

        <script type="text/javascript">
            const startButton = document.querySelector("#startdoc");
            const endButton = document.querySelector("#enddoc");
            const prevButton = document.querySelector("#prev_page");
            const nextButton = document.querySelector("#next_page");
            const showPG = document.querySelector("#pgnos");
            
            //magnify = document.querySelector("#zoom-in");
            //minify = document.querySelector("#zoom-out");

            /*
            magnify.addEventListener('click', function() {
                $("#flipbook").turn("zoom", 1.1, 1);
            });
            minify.addEventListener('click', function() {
                $("#flipbook").turn("zoom", 1, 1.1);
            })  
            */
            
            $("#flipbook").turn({
                gradients: true,
                page: 1,
                duration: 2000
            });


            const first_page = $("#flipbook").turn("page");
            const last_page = $("#flipbook").turn("pages");    
            
            
            startButton.addEventListener('click', function() {
                $("#flipbook").turn("page", first_page);
                showPG.innerHTML = first_page;
            });

            endButton.addEventListener('click', function() {
                $('#flipbook').turn("page", last_page);
                showPG.innerHTML = last_page;
            });

            nextButton.addEventListener('click', function() {
                $("#flipbook").turn("next");
                showPG.innerHTML = $("#flipbook").turn("page");
            });

            prevButton.addEventListener('click', function() {
                $("#flipbook").turn("previous");
                showPG.innerHTML = $("#flipbook").turn("page");             
            });


            if ( (($("#flipbook").turn("page") == first_page)) ) {
                $(nextButton).click(function() {
                    $("#flipbook").animate({left: "275"});
                });

                $(endButton).click(function() {
                    $("#flipbook").animate({left: "565"});
                });

                $(prevButton).click(function() {
                    $("#flipbook").animate({left: "275"});
                });

                $(startButton).click(function() {
                    $("#flipbook").animate({left: "0"});
                });
            } 


            if ( (($("#flipbook").turn("page") == last_page)) ) {
                $(prevButton).click(function() {
                    $("#flipbook").animate({left: "300"});
                });   
            }

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

What is a fast sort algorithm for a very, very long array of objects in JavaScript?

I have been trying to sort an array with 2000 elements in ReactJS using JavaScript. The array looks like this:

data = [

         {
    index: 0,
    id: "404449",
    product_name: "ette",
    brand_name: "Dyrberg/Kern",
    base_price: "55.000",
    actual_price: "55.000",
    filename:
      "http://images.booztx.com/dyrbergkern/400x523/329679_ette_sg_crystal.jpg",
  },
  {
    index: 1,
    id: "414661",
    product_name: "braided mobile chain",
    brand_name: "Octopus",
    base_price: "44.900",
    actual_price: "44.900",
    filename: "http://images.booztx.com/octopus/400x523/SC09-750MU.jpg",
  },

       ]

I tried sorting it by base_price with Array.sort( ) of JavaScript, like this:

 data.sort((a, b) => {
     
      return parseFloat(a.base_price) - parseFloat(b.base_price);
    });

but since the array is very long, it has 2000 elements it takes a very long time to sort. It takes about 4 minutes. Does anyone have any solutions?

Treemap chart.js text wrap

In my code below, I am able to draw a Treemap and also display the tag in each tree cell. But the text is overflowing the tile if it’s a long word

I need to ensure the word stays in the tile even If it means putting …. after certain characters. How can I achieve them? Please have a look at the version of chart.js and Treemap I am using before providing the solution. Thanks a lot 🙂


  var topTags = [
  {tag:'android',num:42657},{tag:'reactjs',num:38844},{tag:'php',num:34381},{tag:'sql',num:29996},
];

var canvas = document.getElementById("treemap");
var ctx = canvas.getContext("2d");
var chart = window.chart = new Chart(ctx, {
  type: "treemap",
  data: {
    datasets: [{
      tree: topTags,
      key: "num",
      groups: ['tag'],
      spacing: 0.5,
      borderWidth: 1.5,
      fontColor: "black",
      borderColor: "grey"
    }]
  },
  options: {
    maintainAspectRatio: false,
    legend: { display: false },
    tooltips: { enabled: false }
  }
});

CHART.JS AND TREEMAP VERSION :

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

nativescript-firebase issue to get push token

I implemented the nativescript-firebase (https://github.com/EddyVerbruggen/nativescript-plugin-firebase) plugin in my mobile app. It used to work fine but since I updated to the 11.1.3 version I cannot get the push token. I tried to get back to the 10.6.3 version but it says it is not available anymore when I execute npm install.

Here is what I do in my main.js

import { messaging } from "@nativescript/firebase/messaging";
import { firebase } from "@nativescript/firebase"
firebase.init({
    onMessageReceivedCallback: function(message) {
      //do stuff
    }
}).then(function () {
    messaging.getCurrentPushToken().then(token => {
        console.log(token)
    }).catch(e => {
    console.log(e);
  })
},function (error) {
  console.log("firebase.init error: " + error);
});

This does not log the token but goes into the catch and logs this
Uncomment firebase-messaging in the plugin's include.gradle first

Here is my package.json

{
  "name": "*****",
  "main": "./src/main.js",
  "version": "4.4.0",
  "description": "A native application built with NativeScript-Vue",
  "author": "*****",
  "license": "Propriétaire",
  "dependencies": {
    "@carployee/openapp": "^1.0.1",
    "@nativescript-community/ui-material-bottomnavigationbar": "^6.2.4",
    "@nativescript/appavailability": "^2.0.0",
    "@nativescript/appversion": "^2.0.0",
    "@nativescript/camera": "^5.0.10",
    "@nativescript/core": "~8.1.5",
    "@nativescript/datetimepicker": "^2.1.9",
    "@nativescript/firebase": "^11.1.3",
    "@nativescript/imagepicker": "^1.0.6",
    "@nativescript/ios": "^8.1.0",
    "@nativescript/iqkeyboardmanager": "^2.0.0",
    "@nativescript/theme": "^3.0.2",
    "@nstudio/nativescript-cardview": "^2.0.1",
    "@nstudio/nativescript-loading-indicator": "^4.1.0",
    "@nstudio/nativescript-pulltorefresh": "^3.0.1",
    "@proplugins/nativescript-purchase": "git+https://gitlab.******",
    "@vue/devtools": "^5.3.4",
    "nativescript-dna-deviceinfo": "^3.7.3",
    "nativescript-feedback": "^2.0.0",
    "nativescript-google-maps-sdk": "^3.0.2",
    "nativescript-inappbrowser": "^3.1.2",
    "nativescript-open-app": "^0.3.0",
    "nativescript-phone": "^3.0.2",
    "nativescript-socketio": "^3.3.1",
    "nativescript-toasty": "^3.0.0-alpha.2",
    "nativescript-ui-dataform": "^8.0.1",
    "nativescript-ui-listview": "^10.0.2",
    "nativescript-ui-sidedrawer": "^10.0.2",
    "nativescript-vue": "^2.9.0",
    "nativescript-vue-devtools": "^1.5.1",
    "nativescript-vue-fonticon": "^1.0.3",
    "nativescript-websockets": "^2.0.0",
    "npm-check": "^5.9.2",
    "npm-check-updates": "^12.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.16.0",
    "@babel/preset-env": "^7.16.4",
    "@nativescript/android": "~8.1.1",
    "@nativescript/webpack": "~5.0.1",
    "babel-loader": "^8.2.3",
    "nativescript-vue-template-compiler": "^2.9.0",
    "nativescript-worker-loader": "~0.12.1",
    "sass": "^1.44.0",
    "vue-loader": "^15.9.8"
  }
}

How in JS to compare from an array of objects from all the results 2 keys are equal to 2 other variables

I’m trying to understand how to get from an array of objects 2 specific keys and compare them with 2 other values for a boolean statement.

What I need to achieve is that for all results from an array of objects I have to check if
ownerId or ownerType are equal to example this.ownerId or this.ownerType.

To give an example I have a result Obj as

const results = [
    {
        ownerId: '1'
        ownerType: SOME_TYPE,
        id: 1
        ...
        <other key_values>
        ...
    },
    {
        ownerId: '1'
        ownerType: SOME_TYPE,
        id: 2
        ...
        <other key_values>
        ...
    },
    ... more ...
];

From the results, I have to extract all ownerId and ownerType and check if all are equal to another value as example

(ownerType === 'USER' && ownerId === userId) ||
(ownerType === 'PARTICIPANT' && ownerId === participantId)

So that means where all ownerType === 'USER' && all ownerId === to this userId then is true.

like all ownerId in my examples are 1 and we suppose ‘USER’ as a type then that is true.

but

If the result doesn’t have all the same ownerId that is false.

I’m not sure what kind of function I need to write for it.

If any comments I’ll try to explain better m issue

Why ‘Get’ request is returning blank object for particular request?

This is the code in which the problem is occurring:
router.get("/", async(req, res) => {
    const username = req.query.user;
    const catName = req.query.cat;

    try {
        let posts;
        if (username) {
            posts = await Post.find({ username: username });
        } else if (catName) {
            posts = await Post.find({ categories: { $in: [catName], }, });
        } else {
            posts = await Post.find();
        }
        res.status.json(posts);
    } catch (err) {
        res.status(500).json(err)
    }
});
if I am using this its working fine
   router.get("/", async(req, res) => {
         try {
             const post = await Post.find()
    
             res.status(200).json(post)
    
         } catch (err) {
             res.status(500).json(err)
         }
     })
I want to use the first request with queries but that is returning a empty object I can’t find error!

Every other requests are working just fine in this route expect the first one!

Can’t pass JSON from PHP to Javascript in Laravel component

We have a Laravel 8 project.

In it, we have a Blade template, and from this Blade template we are including a Laravel component like this:

<x-key-figure-graph
    measure="IQ_TOTAL_REV"
    dividend-history="{{ json_encode($dividend_history) }}"
    show-last="10">
</x-key-figure-graph>

The $dividend_history is an associative array that looks like this:

['2002' => ['date' => '2002-06-30', 'IQ_CLOSEPRICE' => 27.35]],
['2003' => ['date' => '2003-06-30', 'IQ_CLOSEPRICE' => 33.81]],
...

I am doing json_encode on the array to transform it into a string so I can pass it as a prop to the x-key-figure-graph component.

Within the component is where problems arise. If I print out the passed prop:

{{ $dividendHistory }}

I get:

{&quot;2002&quot;:{&quot;date&quot;:&quot;2002-06-30&quot;,&quot;IQ_CLOSEPRICE&quot;:27.35 [...]

So this is a string with the quotes turned into their ASCII equivalents (&quot;). The thing is, now we need to pass this to a Javascript script inside this component. I have not found a way to convert this string back into a working JSON for Javascript.

Attempt 1:

let stock = JSON.parse({!! $dividendHistory !!});

Result:

Uncaught SyntaxError: Unexpected token '&'

Attempt 2:

let stock = JSON.parse("{!! $dividendHistory !!}");

Result:

Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse (<anonymous>)

Attempt 3:

let stock = JSON.parse({!! json_decode($dividendHistory) !!});

Result:

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

I don’t know what else to try. Surely it should be possible to convert the string, which was encoded from JSON, back into JSON so it can be used by Javascript. How?