Client server api calls

How to determine if the api is firing from client side or server side from the website?
What client side and server side means in browser site?

I want to check whether the api is firing from client side or server side from the website

The @wix/sdk package is not working correctly with reactjs

I’m trying to use wix Oauth in my react app, so i used @wix/sdk-react (that based on @wix/sdk), but where i starts this project, i have this problems.

enter image description here

It seems like one of the modules tries to get another part of code from /src/, but this package have only /build/ directory.

The code sample:
`import { WixProvider, OAuthStrategy } from ‘@wix/sdk-react’;

function App() {
const [examples, setExamples] = useState([]);

return (
<WixProvider
auth={OAuthStrategy({
clientId: ‘%my_id_here’,
})}

)
}`

I updated my node and npm, and tried to use @wix/api-client (their deprecated package), but it didn’t help me.

Has anyone encountered this problem? Thanks in advance for your help

data retrive multipul times from mongodb

i’m trying to retrive data from mongodb with nodejs and when i’m trying to rerive data only one time it gives me data 2 or 3 time with different value or sometimes empty array.
enter image description here

as shown in this pitcher when i’m trying to retrive data first it gives me an empty array and then it gives the correct data but then again it gives an empty array

here is the code

   const fetchdata=async ()=>{
        setload(false)
        await axios.get(`http://localhost:4000/getmessages/:${covid}`).then(response=>{
                  console.log(response.data)
                room.setchat(response.data)
                
            })
         .catch(err=>{
             console.log(err)
        })
    }

backend code


const getmessages=async (req,res)=>{
try{
    const conversationid=req.params['id']
     messagemodel.find({conversation_id:conversationid}).then(
        mssgs=>{
    
            res.send(mssgs)
            mssgs.forEach(element => {
                console.log(element.value)
               
            });
        }
    )
    
}
catch{
    console.log("error on getting mssg")
}

}

how can i solve this problem

how to implement a responsive notification

I’m trying to implement a notification in react. I have somehow managed to implement the desired design but it has a arrow shaped thing, it’s not responsive and changes with content size and the texts are not aligned.please help with me with this. Thanks in advance 🙂

below is my code

export function html() {
const {
    Heading, loading, broadcastMessages
} = this.state;

const CapGrid = withStyles((theme) => ({
    root:{
        "&, &:before": {
            // content:"",
            width:0,
            height:0,
            borderTop: "1.5rem solid transparent",
            borderBottom: "1.5rem solid transparent",
            borderRight:"1.5rem solid white",
        }
    }
}))(Grid);

const ShowNotificationTag = ( props ) => {
    return (
        <>
            <Grid item xs={12} style={props.boxStyle}>

                <Grid container className="broadcast-container">

                    <CapGrid item xs={4}>
                        <Typography padding={1} variant="body1" fontWeight={500} textAlign={'center'}>
                            {props.item.messageSubject}
                        </Typography>
                    </CapGrid>

                    <Grid item xs={7} sx={{background:'white'}}>
                        <Typography padding={1} variant="body2" color="initial">
                            {props.item.messageBody}
                        </Typography>
                    </Grid>

                    <Grid item xs={1}  sx={{background:'white',display:"flex",justifyContent:"end",alignContent:"end",paddingRight:1}}>
                        <IconButton onClick={props.closeBroadcast}>
                            <CloseIcon />
                        </IconButton>
                    </Grid>

                </Grid>

            </Grid>
        </>
    );
}

console.log("broadcastMessages", broadcastMessages)
return (
    <>
        {!broadcastMessages.length == 0 && (
            <Box sx={{ flexGrow: 1, paddingLeft: 2, paddingRight: 20 }}>
                {loading && <div id="semiTransparenDiv"></div>}

                <Card>
                    <CardContent>
                        {
                            broadcastMessages.map((item, index) => {
                                // Define separate style objects for each condition
                                let boxStyle = {};
                                let arrowPointer;
                                if (item.severity === "General") {
                                    arrowPointer = 'arrow-pointer-general';
                                    boxStyle.background = "linear-gradient(270deg, #fbfffb 60%, #6cff5a 100%)";
                                } else if (item.severity === "Warning") {
                                    arrowPointer = 'arrow-pointer-warning';
                                    boxStyle.background = "linear-gradient(270deg, #f7ebd4 60%, #ff9f00 100%)";
                                } else if (item.severity === "Critical") {
                                    boxStyle.color = "white";
                                    arrowPointer = 'arrow-pointer-critical';
                                    boxStyle.background = "linear-gradient(270deg, #ebf1ff 60%, #000785 100%)";
                                }

                                return (
                                    <Box className="messages" key={index} mt={index > 0 ? 2 :0}>
                                        <Grid container spacing={0}>
                                            <ShowNotificationTag boxStyle={boxStyle} item={item} 
                                                closeBroadcast={()=> this.handleBroadcastClose(item.messageId)}/>
                                        </Grid>
                                    </Box>
                                );
                            })
                        }

                    </CardContent>
                </Card>
            </Box>
        )}
    </>
);

}

This is the desired result :

enter image description here

this my implementation so far:

enter image description here

Open menu with two different buttons

I have a very simple dropdown menu. By clicking on the icon NewIcon in DropdownMenu.Trigger, the user sees a drop-down menu. Everything is simple here. To implement the dropdown menu, I use the radix library (https://www.radix-ui.com/primitives/docs/components/dropdown-menu)

 <DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen}>
  <DropdownMenu.Trigger>
      <NewIcon/>
  </DropdownMenu.Trigger>

  <DropdownMenu.Portal forceMount>
          <DropdownMenu.Content>
         ........here some components
          </DropdownMenu.Content>
  </DropdownMenu.Portal>
</DropdownMenu.Root>

However, I would like to also call this dropdown menu with another button (which is located in another component) on the same page.
For example, below is another component that renders the “Edit information” button. Tell me how to click on this button to open the dropdown menu

  <div>           
    <Button>
       Edit information
    </Button>
  <div>

Cookie is set in Response Header but not in browser

I am working on hyrbid angular application using angularja and angular 8. I am trying to implement cookie which needs to get set after login using POST request but the problem is that after login, cookie POST request is getting successfully called and cookie is visible in response header in the network tab but not in response header and also on navigating to cookies in application tab, cookie is not getting stored. I have tried all the possible solution but to no avail. Any possible solution

logic for cookie implementation after successful login

                  fetch(glAccountsUrl+`/api/oauth/v3/cookie`, {
                    'method': 'POST',
                    'credentials': 'include',                    
                    'headers': { 'Authorization': `Bearer ${JSON.parse(localStorage.getItem('jwt.token'))}`,'Content-Type': 'application/json','Access-Control-Allow-Credentials': true },
                    'body': JSON.stringify(cookieObj)
                  })
                      .then((response) => {
                          return response.json();
                      })
                      .then((data)=>{
                        console.log(data.message);
                      })
                }

screenshots

cookies in response header

no cookie in response header

cookie not stored

Run function only on specific pages

I want an IIFE to run only on specific pages like so

(function(){
  if (!window.location.pathname.includes("index.html")) return
  // ... other code to execute if the page is index.html
})()

The above code works like a charm. The problem is, whenever I insert multiple conditions the IIFE never runs regardless of the current HTML page in the browser, for example

if (!window.location.pathname.includes("index.html") || !window.location.pathname.includes("other.html")) return

The issue is relevant when I want to ensure that a function only runs on index.html or “/” if the HTML page is omitted from the URI – or if I want the IIFE to run only on a set of specific pages as the example above.

How do I create this complex Javascript variable

I would like to create a complex Javascript variable like this:

var e = {record: {role: {individual: {tag: value}}}};

where record, role, individual, and value are variables which come from an array.
The array was derived from data as shown below, where the first number is record, second is role, and third is individual, the tag is name and age and the value is after the space:

name_1_2_1 Joseph Jones
name_1_2_2 Mary Poppins
name_1_2_3 Sebastian Quincy
age_1_2_1 20
age_1_2_2 40
age_1_2_3 60

I have all these objects created but I don’t know how to write to the final variable “e”.
I have the code below that figure out the different values. I write one line at a time so the record may exist already from a previous entry.

if (r_r_i_ary.length == 3) {
        var tag = tag_rri_ary[0];
        console.log("TAG", tag);
        var value = key_value_ary[1];
        console.log("VALUE", value);
        const a = {};
        a[tag] = value; // tag value
        console.log("AAA", a);
        const b = {};
        var individual = r_r_i_ary[2]; // individual
        b[individual] = a;
        console.log("BBB", b);
        const c = {};
        var role = r_r_i_ary[1]; // role
        c[role] = b;
        console.log("CCC", c);
        const d = {};
        var record = r_r_i_ary[0]; // record
        d[record] = c;
        console.log("DDD", d);
        e=????? 
      }

How do I do that?

Thanks!

Several identical java scripts on one page

I have a script from the echarts library, with which I build charts on my html page. I’m trying to call it several times for different tabs of my tabbable regions (nav-tabs).
I include the echarts library itself at the end of the body block

<script src="{% static 'js/echarts.min.js' %}"></script>

The code of the script executed several times on the page is as follows:

document.addEventListener("DOMContentLoaded", () => {
echarts.init(document.querySelector("#trafficChart1")).setOption({
tooltip: {
    //tooltip settings
},
legend: {
    //legend settings
},
series:[{
    //diagramm settings
data: [
   {value: 50,  name: 'Region_100'},
   {value: 150, name: 'Region_200'},
   {value: 250, name: 'Region_300'}
      ]
}]
});
});

For each of the tabs I tried using a different selector:

<div id="trafficChart1" style="min-height: 300px;" class="echart"></div>   
<script> 
    //here is the code of the above script
</script> 

Accordingly, for the other two tabs the code will be the same, but the selectors (#trafficChart2, #trafficChart3) and data for the charts will change.

In the end, it all looks something like this (the first tab of the nav-tabs block)

the first tab of the nav-tabs block 2021

But in the 2022 and 2023 tabs the charts are not displayed, although they are marked with identifiers (‘trafficChart2‘ and ‘trafficChart3‘ respectively).

2022 and 2023 tabs where charts are not displayed

Help me understand how to implement the construction of diagrams in different tabs of a nav-tabs block, that is, in essence, call the javascript several times on one page.

How to replace this with a single click download in table itself

Curently i have to right click to download. I want a simple button in table to download.

Download

$(‘.file-item’).bind(“contextmenu”, function(event) {
event.preventDefault();

$('.file-item').removeClass('active')
$(this).addClass('active')
$("div.custom-menu").hide();
var custom =$("<div class='custom-menu file'></div>")
    custom.append($('#menu-file-clone').html())
    custom.find('.download').attr('data-id',$(this).attr('data-id'))
custom.appendTo("body")
custom.css({top: event.pageY + "px", left: event.pageX + "px"});


$("div.file.custom-menu .download").click(function(e){
    e.preventDefault()
    window.open('download.php?id='+$(this).attr('data-id'))
})

})

I tried but its not working when i am shifting the div inside the td block.

Puppeteer/Typescript Node is either not clickable or not an element/Property ‘click’ does not exist on type ‘Element’

When trying to use the click() method on any iteration of makeElements, the error handler throws me the error “Node is either not clickable or not an Element”, to circumvent it I attempt to evaluate the element and use click() on it then as suggested in many stackoverflow questions, however this does not solve the problem and fires the TypeScript “property click does not exist on type Element” error.

export interface DataScraperProps {
  page: Page;
}

export const getModels = async ({ page }: DataScraperProps) => {
  //makeElements here returns a large list and seems to work fine
  const makeElements = await page.$$(getMakeClasses({ dataSite }));

  const modelData = [];
  try {
    for (let i = 0; i < makeElements.length; i++) {
      //the element that needs to be clicked to open the dropdown
      const dropdown = await page.$(".input-select.js-make .display-input");
      await dropdown?.click();

      await makeElements[i].click();

      const models = await page.$$eval(
        ".input-select.js-model .dropdown-options.js-options",
        (elements) =>
          elements.map((e) => ({ test: e.getAttribute("data-title") }))
      );
      modelData.push(models);
    }
  } catch (error) {
    console.error("Error clicking make element:", error);
  }

  return modelData;
};

The part below is specifically responsible for throwing me the error “Node is either not clickable or not an Element”:

    await makeElements[i].click();

I’ve tested my selectors using the devtools by combining querySelector() and then the click() method which seems to work fine in both cases where I desire for the click to happen, the dropdown opens and the option gets selected, however when it comes to replicating it in the puppeteer function it does not achieve the same result.

I’ve scoured stack overflow and noticed that a lot of people suggest evaluating the element beforehand and then firing an HTML Click event as such:

      await makeElements[i].evaluate((el) => el.click());

However TypeScript throws the error “property click does not exist on type Element”.

How do I make a shopping cart to be able to interact with a server using node.js?

I am confused on how do I make a shopping cart to be able to interact with a server in the back end using node.js. This is what I got so far using JS. I have it as local storage, but I do not know how to make it to the actual server using node.js.

let productsInCart = JSON.parse(localStorage.getItem('ShoppingCart'));
if(!productsInCart){
  productsInCart = [];
}
const parentElement =  document.querySelector('#buyItems');
const cartSumPrice = document.querySelector ('#sum-prices');
const products = document.querySelectorAll ('.product-under');


const countTheSumPrice = function(){
  let sumPrice = 0;
  productsInCart.forEach(product => {
    sumPrice += product.price;
  });
  return sumPrice;
}

const updateShoppingCartHTML = function(){
  localStorage.setItem('ShoppingCart',JSON.stringify(productsInCart));
      if (productsInCart.length > 0){
         let result = productsInCart.map(product => {
            return 'fill in the blank'
            
        
          });
          parentElement.innerHTML = result.join('')
          document.querySelector('.checkout').classList.remove('hidden');
          cartSumPrice.innerHTML = "$" + countTheSumPrice();

      }
      else{
        document.querySelector('.checkout').classList.add('hidden');
        parentElement.innerHTML = '<h4 class="empty">Your shopping cart is empty</h4>';
        cartSumPrice.innerHTML = "";
      }
}

function updateProdcutsInCart(product){
  for(let i=0; i < productsInCart.length; i++){
    if(productsInCart[i].id == product.id){
      productsInCart[i].count += 1;
      productsInCart[i].price = productsInCart[i].basePrice * productsInCart[i].count;
      return;
    }
  }
  productsInCart.push(product);
}





products.forEach(product => {
  product.addEventListener('click', (e) =>{
    if (e.target.classList.contains('addToCart')){
         const productID = e.target.dataset.prodcutID;
         const productName = product.querySelector('.productName').innerHTML;
         const productPrice = product.querySelector('.priceValue').innerHTML;
         const productImage = product.querySelector ('img').src;
         let productToCart = {
             name: productName,
             image: productImage,
             id: prodcutID,
             count: 1,
             price: +productPrice,
             basePrice : +productPrice
         }
        updateProdcutsInCart(productToCart);
        updateShoppingCartHTML(); 

    }
  });
});

parentElement.addEventListener('click', (e) =>{
  const isPlusButton = e.target.classList.contains('button-plus');
  const isMinusButton = e.target.classList.contains('button-minus');
  if (isPlusButton || isMinusButton){
    for(let i=0; i < productsInCart.length; i++){
      if (productsInCart[i].id === e.target.dataset.id){
        if(isPlusButton){
            productsInCart[i].count += 1;
        }
        else if(isMinusButton){
          productsInCart[i].count -= 1;
        }
        productsInCart[i].price = productsInCart[i].basePrice * productsInCart[i].count;
      }
      if(productsInCart[i].count <=0){
        productsInCart.splice(i,1);
      }
    }
    updateShoppingCartHTML();
  }
});

updateShoppingCartHTML()

I tried finding a solution online but got lost in the process.

displaying countdown in different time zones

I’m running a countdown timer for use in 3 timezones (GMT,PT,EST) and i need it to sync so the timer ends at the same time for each timezone. This is my code below. This is time sensitive (no pun) so thanks in advance!

     <p id="demo"></p>

<script>
// Set the date we're counting down to
var countDownDate = new Date("Nov 17, 2023 20:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();
    
  // Find the distance between now and the count down date
  var distance = countDownDate - now;
    
  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

Chartjs Zoom Plugin – Default scroll behaviour not working

In my project, I have implemented a bar chart using Chart.js. The chart allows users to scroll to view the amounts for the previous months over the last two years. To enable panning on the x-axis and achieve this functionality, I incorporated the Chart.js zoom plugin. However, I am encountering an issue where the default scroll on the y-axis is not functioning as expected. The problem arises from the addition of a CSS property, ‘touch-action: none,’ by the zoom plugin for the canvas. This property prevents the default scroll behavior.

To address this, I experimented with changing the ‘touch-action‘ property to ‘auto,’ which enables the default scroll behavior. However, this adjustment disrupts the panning functionality on the x-axis in the bar chart.

I am facing a challenge in my project where I need to distinguish between user scrolls on the x-axis and y-axis in a bar chart implemented using Chart.js. Specifically, when the user scrolls along the x-axis, I want to display the data for previous months, leveraging the panning functionality provided by the Chart.js zoom plugin. On the other hand, when the user scrolls along the y-axis, I intend for the default scroll behavior to take effect, allowing them to navigate other content.

I am currently seeking guidance on how to implement a solution that accurately detects whether the user is scrolling along the x-axis or y-axis and subsequently triggers the appropriate actions, such as displaying previous months or enabling the default y-axis scroll behavior. Any insights or suggestions on how to achieve this nuanced functionality would be highly appreciated.

for the canvas for bar chart if applied zoom plugin and enabled the pan. touch-action : none is added automatically it prevents the default scroll behaviour

display: block;
box-sizing: border-box;
height: 300px;
width: 343px;
touch-action: none;
user-select: none;
-webkit-user-drag: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);

In ts file chartjs option

plugins: {
zoom: {
          pan: {
            sensitivity: 6,
            enabled: true,
            mode: 'x',
            speed: 0.2,
            threshold: 8,
          },
        },
}

enter image description here