React19:Un return que no funciona? [closed]

Llevo todo el dia, y no puedo entender que es lo que esta pasando, pero parece que hay un return que me lleva al principio!!!!
He unido todo el codigo en la App

import { use } from "react";
import ErrorBoundary from "./error/ErrorBoundary";


function App() {
  return (
    <>
      <ErrorBoundary>
        {/* <Suspense fallback={<div>Cargando...</div>}> */}
        <DataDisplay />
        {/* </Suspense> */}
      </ErrorBoundary>
    </>
  );
}

function DataDisplay() {
  // Usamos 'use' para "esperar" la promesa de fetchData()

  console.log("iniciando:");
  const data = use(fetchData());
  console.log("data:", data);
  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.completed ? "Completado" : "Pendiente"}</p>
    </div>
  );
}

const fetchData = async () =>   {
    try {
        const response =  await fetch('https://jsonplaceholder.typicode.com/todos/1',{mode: 'cors' });
        console.log('Response received:', response);
        const data = await response.json();
        console.log('Data fetched successfully', data);
        
        **return data;**
    } catch (error) {
        console.error(error);
        throw error;
    }
     console.log('This will not run');
}
export default App;``` 

y esto es un trozo de los consoles; el return lo ha de ejecutar despues de *'Data fetched successfully'*. Por favor, darme alguna pista!!!!

App.tsx:36 Response received: Response {type: ‘cors’, url: ‘https://jsonplaceholder.typicode.com/todos/1’, redirected: false, status: 200, ok: true, …}
App.tsx:36 Response received: Response {type: ‘cors’, url: ‘https://jsonplaceholder.typicode.com/todos/1’, redirected: false, status: 200, ok: true, …}
App.tsx:38 Data fetched successfully {userId: 1, id: 1, title: ‘delectus aut autem’, completed: false}
App.tsx:38 Data fetched successfully {userId: 1, id: 1, title: ‘delectus aut autem’, completed: false}
App.tsx:22 iniciando:“`

Mixpanel JavaScript SDK cookies missing SameSite attribute – how to add SameSite=Lax?

A pen tester called out that my Mixpanel cookies (mp_*) are missing the SameSite attribute.

Current Setup

I’m using the Mixpanel JavaScript SDK with this configuration:

mixpanel.init(token, {
track_pageview: false,
debug: process.env.NODE_ENV !== “production”,
secure_cookie: true,
cross_subdomain_cookie: false,
cross_site_cookie: false
});

Problem

Despite trying various configuration options, the Mixpanel cookies are still being set without the SameSite attribute. Browser dev tools show:

  • ✅ Secure flag is present (due to secure_cookie: true)
  • ❌ SameSite attribute is missing
  • ❌ HttpOnly flag is missing

What I’ve Tried

  1. Configuration options – I’ve tried cross_site_cookie: false and cross_subdomain_cookie: false but these don’t seem to add SameSite attributes. I found cross_site_cookie on https://classic.yarnpkg.com/en/package/mixpanel-browser from a 2.35.0 (17 Mar 2020) release, but it’s not mentioned anywhere else and doesn’t seem to work.
  2. Custom cookie interceptor – I overrode document.cookie to intercept Mixpanel cookies and add SameSite, but this feels hacky and I’m not sure if it’s reliable.
//interceptor approach
const originalCookieDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
Object.defineProperty(document, 'cookie', {
  set: function(cookieString) {
    if (cookieString && cookieString.includes('mp_')) {
      if (!/samesites*=/i.test(cookieString)) {
        cookieString += '; SameSite=Lax';
      }
    }
    originalCookieDescriptor.set.call(this, cookieString);
  }
});

Questions

  1. Does Mixpanel JavaScript SDK have native support for SameSite cookie attributes? I can’t find this in their official documentation.
  2. What’s the recommended way to ensure Mixpanel cookies comply with modern browser security requirements?
  3. Is there a reliable way to add SameSite attributes to third-party library cookies like Mixpanel’s?

Environment

  • Mixpanel JavaScript SDK (latest version via CDN)

Plasma UI Causes Blank Screen

Environment

  • React 18
  • Vite 7.1.5
  • Plasma UI (latest via npm)
  • macOS (local dev)
  • Fresh project scaffolded with
npm create vite@latest

What I Expected

I expected Plasma UI’s <Input /> component to render inside a simple form, styled and functional, as long as I wrapped the app with DeviceThemeProvider and used GlobalStyle and a valid theme.

What Actually Happened

As soon as I include <Input /> from @salutejs/plasma-ui, the entire UI goes blank. Nothing is visible in the browser — not even the surrounding JSX like <h1> and <div>. There’s no error in the browser console, no crash logs, and no failed network requests.

What Renders to the DOM

When <Input /> is present:

  • The root <div id="root"> is empty — no children are rendered

  • No HTML elements appear in the DOM inspector

  • No styles or layout are applied

  • Console logs inside the component do not appear

When I remove <Input /> and use a native <input> instead:

  • Everything renders correctly

  • JSX elements appear in the DOM

  • Console logs work

  • Form behaves as expected

Is It a Crash or a Visibility Issue?

It seems like a silent crash during render, not a CSS issue. The DOM is completely empty, and even fallback JSX like <h1> disappears. It’s not just that the input is invisible — the entire component tree fails to render.

Minimal Repro

.jsx code

import { Input } from '@salutejs/plasma-ui';
import { DeviceThemeProvider } from '@salutejs/plasma-ui/components/Device';
import { GlobalStyle } from '@salutejs/plasma-ui';
import { light } from '@salutejs/plasma-tokens/themes';

function App() {
  const [name, setName] = useState('');

  return (
    <DeviceThemeProvider theme={light}>
      <GlobalStyle />
      <Input
        placeholder="Your name"
        value={name}
        onChange={({ value }) => setName(value)}
      />
    </DeviceThemeProvider>
  );
}

What I’ve Tried

  • Wrapped the app in DeviceThemeProvider with light theme from @salutejs/plasma-tokens/themes
  • Added <GlobalStyle /> inside the provider
  • Imported @salutejs/plasma-core in main.jsx
  • Verified that onChange={({ value }) => setName(value)} is used correctly
  • Removed deprecated lightEva theme
  • Removed invalid import @salutejs/plasma-ui/styles (caused Vite build error)
  • Downgraded Plasma UI to 3.0.0 — same result
  • Replaced Plasma <Input /> with native <input> — works fine
  • No console errors, no crash logs, just a blank screen

Is there a way for JSDoc comments to be visible in HTML files?

I’m not sure how to get the code snippet for this question as I don’t know how to specify the filename of the JavaScript file, but here goes.

I have a JavaScript file, “scripts.js” that includes // @ts-check at the top of the file. JSDoc comments are included to indicate parameters for functions, variables and classes. This has been most helpful for development of scripts.js, ensuring that I have proper typing in JavaScript. However, when I use the scripts.js file in an HTML file, those JSDoc type hints are not visible. For example, in Visual Studio Code, the calling of footer(1); does not give me the following problem of:

Argument of type 'number' is not assignable to parameter of type 'string'.

I’ve added // @ts-check to the HTML file and imported footer but still no luck.

Is there any way to get those ts-check type hints show up in the HTML file?

// @ts-check
"use strict";

/**
 * @param {string} [email] - Email address. (optional)
 */
function footer(email = "")
{
    // main function

    {
        let html = "";

        html += `<footer>`;
        html += `<hr>`;
        html += `<address><a href="mailto:${email}">${email}</a></address>`;
        html += `</footer>`;

        document.body.insertAdjacentHTML("beforeend", html);
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script src="scripts.js">
        // @ts-check
        import
        {
            footer
        } from "";
    </script>
    <title>JSDoc Test</title>
</head>

<body>

<h1>JSDoc Test</h1>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    Maecenas porttitor congue massa. Fusce posuere, magna sed
    pulvinar ultricies, purus lectus malesuada libero, sit amet
    commodo magna eros quis urna.</p>

<script>
    footer("[email protected]");
    footer(1); // no error here but ts-check should complain because the param is not a string
</script>

</body>
</html>

Holberton checker fails “thumbnailElement is declared and assigned by ID” even though code uses document.getElementById

I’m working through a Holberton School web project.
In behavior.js I need to toggle a thumbnail’s size when it’s clicked.
The task says:

Modify the click event in behavior.js to include an if…else statement.

My HTML contains the image:

<img src="https://via.placeholder.com/800"
     id="smart_thumbnail"
     class="small"
     alt="Thumbnail">

My behavior.js currently looks like this:

    // I first wrote this (step 1):
thumbnailElement.addEventListener("click", function() {
    thumbnailElement.className =
        (thumbnailElement.className === "small") ? "" : "small";
});

// Then I added the required if...else (step 2):
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
    if (thumbnailElement.className === "small") {
        thumbnailElement.className = "";
    } else {
        thumbnailElement.className = "small";
    }
});

But when I run the automated checker I keep failing Test #1: “thumbnailElement is declared and assigned by ID.”
Tests #2 and #3 (toggle logic and class switching) pass.

I’ve confirmed:

The HTML ID is smart_thumbnail and matches getElementById.

behavior.js is loaded at the bottom of the HTML before .

Why does the checker still think thumbnailElement is not “declared and assigned by ID”?
Is it because I have two event listeners or because of the order of the code?
What’s the correct way to satisfy this test?

(Holberton project context, but the underlying issue is JavaScript DOM usage and linter/checker expectations.)

How to reset lasso selection across multiple plots to avoid accumulation?

Ah, and is there any hack or workaround on the latest version to reset the selection? Maybe simulating the double click event on an empty area of the plot. This is what I want to achieve:

plot images

I cannot find a way to do it with scattergl

This is what I’m trying, even in the version 2.12.0 with no luck

  await Plotly.relayout(plotDiv, {selections: []});
  await Plotly.restyle(plotDiv, {selectedpoints: [null]}, [lastSelectionSource]);

In this script I am using this instruction to trigger the repainting. But I get the same resulta than with relayout and restyle.

await Plotly.react(plotDiv, traces, layout);

The first time I use the lasso tool to make a selection, the drawn lasso remains visible, and the next selection in other plot doesn’t work properly. It gets added to the selectedIndices instead of replacing the current selection.

After that, if I select points in another plot, the selection works as expected.

However, when I make a new selection in the same plot, the lasso drawing appears again (which is normal behavior), but this causes the next selection in another plot to be aggregated with the previous selectedIndices, instead of overriding them.

I’ve attached a GIF that illustrates this behavior.

Do you know a more reliable way to implement this so that selections always replace the previous ones rather than accumulate?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Plotly 3.1.0 Grid Plot - ScatterGL</title>
    <script src="https://cdn.plot.ly/plotly-3.1.0.min.js"></script>
    <style>
      body {margin:0; font-family:'Inter', sans-serif; background-color:#f5f5f5; height:100vh;}
      .plot-container {width:100vw; height:100vh; background:white; overflow:hidden;}
    </style>
  </head>
  <body>
    <div id="plotly-plot" class="plot-container"></div>
    <script>
      function generateRandom(count){
          return Array.from({length:count},()=>Math.floor(Math.random()*100)+1);
      }

      const data = {
          x: generateRandom(100),
          y: generateRandom(100),
          x2: generateRandom(100),
          y2: generateRandom(100),
          x3: generateRandom(100),
          y3: generateRandom(100),
          x4: generateRandom(100),
          y4: generateRandom(100)
      };

      let traces = [
          {x:data.x, y:data.y, mode:'markers', type:'scattergl', marker:{size:7,color:'blue',opacity:0.7}, selected:{marker:{size:10,color:'red',opacity:1}}, unselected:{marker:{opacity:0.2}}, xaxis:'x1', yaxis:'y1'},
          {x:data.x2, y:data.y2, mode:'markers', type:'scattergl', marker:{size:7,color:'green',opacity:0.7}, selected:{marker:{size:10,color:'red',opacity:1}}, unselected:{marker:{opacity:0.2}}, xaxis:'x2', yaxis:'y2'},
          {x:data.x3, y:data.y3, mode:'markers', type:'scattergl', marker:{size:7,color:'red',opacity:0.7}, selected:{marker:{size:10,color:'red',opacity:1}}, unselected:{marker:{opacity:0.2}}, xaxis:'x3', yaxis:'y3'},
          {x:data.x4, y:data.y4, mode:'markers', type:'scattergl', marker:{size:7,color:'purple',opacity:0.7}, selected:{marker:{size:10,color:'red',opacity:1}}, unselected:{marker:{opacity:0.2}}, xaxis:'x4', yaxis:'y4'}
      ];

      const plotDiv = document.getElementById('plotly-plot');

      let layout = {
          title:'Plotly 3.1.0 Grid Plot - ScatterGL',
          autosize:true,
          showlegend:false,
          grid:{rows:2, columns:2, pattern:'independent'},
          xaxis1:{title:'X1'}, yaxis1:{title:'Y1'},
          xaxis2:{title:'X2'}, yaxis2:{title:'Y2'},
          xaxis3:{title:'X3'}, yaxis3:{title:'Y3'},
          xaxis4:{title:'X4'}, yaxis4:{title:'Y4'},
          plot_bgcolor:'white',
          paper_bgcolor:'white',
          hovermode:'closest',
          margin:{t:40,b:40,l:30,r:30},
          selectdirection:'any',
          selectionrevision:0,
          dragmode:'select'
      };

      Plotly.newPlot(plotDiv, traces, layout, {displayModeBar:true, responsive:true, scrollZoom:true, displaylogo:false});

      let lastSelectionSource = null;

      plotDiv.on('plotly_selected', async function(eventData){
          if(!eventData || !eventData.points || eventData.points.length===0) return;

          const sourceTrace = eventData.points[0].curveNumber;
          const selectedIndices = Array.from(new Set(eventData.points.map(p=>p.pointIndex)));
          console.log(selectedIndices);

          if(lastSelectionSource !== null && lastSelectionSource !== sourceTrace){
              layout.selectionrevision++;
              traces[lastSelectionSource].selectedpoints = null;
              await Plotly.react(plotDiv, traces, layout);
          }

          traces.forEach(t => t.selectedpoints = selectedIndices);
          layout.selectionrevision++;
          await Plotly.react(plotDiv, traces, layout);

          lastSelectionSource = sourceTrace;
      });
    </script>
  </body>
</html>

Image

I have seen that there are some issues related to selected points in the latest versions of Plotly.js

This SO question is also related. Triggering a double click on an empty area would reset the selection. But I don’t know how to trigger that programmatically

Getting YouTube Channel ID via web extension

My problem is that I can get the ID of the channel that the extension user is on, but when the user switches to another channel, the YouTube HTML doesn’t update and leaves the old channel ID there. This breaks my extension because I always need the ID of the channel that the user is currently viewing.

How to get distinct values from an array of array in JavaScript? [duplicate]

I have the following array of array

const employees = [
    ["001","DDDDD"],
    ["002","EEEEE"],
    ["001","DDDDD"],
    ["002","EEEEE"],
    ["003","WWWWW"],
    ["001","DDDDD"],
];

I want to create another array which will contain only Unique values based on the first array element, e.g.

let uniqueArray = [
    ["001","DDDDD"],
    ["002","EEEEE"],
    ["003","WWWWW"],
]

What will be the best approach to achieve this? I can do a for loop on the original array, but there has to be a better way to do this.

Thanks

Problem with notification when adding product to cart

I am working on a project using JavaScript, without frameworks. I have a code for adding a product to the cart. The code works well. The product is added as I need it. But, with the notification about adding, something is wrong. I need, if the product is not yet in the cart, when adding, the notification Product in the cart (type success) appeared, and if the product is in the cart, it was not added and there was a notification This product is in the cart (type info). As I said, the product is added correctly, one product only once. But every time when clicking on the add to cart button, the notification Product in cart(type success) appears.

export class HomePage extends Component {
constructor() {
super();
this.template = template();
this.state = {
  links: [
   {
     label: "Sign In",
     href: ROUTES.singIn,
   },
   {
    label: "My Cart",
    href: ROUTES.singIn,
  },
  ],

  products: [],
  orderCart: [],
  user: null,
};
}

 setLinks = () => {
  const { getUser } = useUserStore();
  if (getUser()) {
    this.setState({
      links: [
        {
          label: "My Cart",
          href: ROUTES.cart,
        },
        {
          label: "LogOut",
          href: ROUTES.logOut,
        },
      ],
    });
  }
};

getProducts = () => {
apiService
.get("/products")
.then(({ data }) => {
  this.setState({
    ...this.state,
    products: mapResponseApiData(data),
  });
})
};

addToCard = async ({ target }) => {

const btn = target.closest('.add-to-cart');
if (!btn) return;

const { id, price, name, img } = btn.dataset;

if (this.state.orderCart?.some(item => item.id === id)) {
  useToastNotification({ 
    message: 'This product is already in the cart :)', 
    type: TOAST_TYPE.info });
  return;
}

await apiService.patch(`/order/${id}`, { id, price, name, img }).then(() => {
   this.setState({
   ...this.state,
   orderCart: this.state.orderCart?.concat({ id, price, name, img }),
    });
  })
  useToastNotification({ message: 'Product in the cart!', type: TOAST_TYPE.success });
};

 componentDidMount() {
this.setLinks();
this.getProducts();
this.addEventListener("click", this.addToCard);
 }

 componentWillUnmount() {
this.removeEventListener("click", this.addToCard);
 }
}

customElements.define('home-page', HomePage);

When I try to add a product without logging in, the notification works correctly. When I first click, the notification is type success, when I click again, type info. Maybe the problem is in the user state?

Store.js:

export class Store {
constructor(initialState) {
this._state = initialState;
 }

 getState() {
   return this._state;
 }

setState(state) {
this._state = Object.assign(this._state, state);
 eventEmitter.emit(EVENT_TYPES.store, { state: this._state });
} 

 subscribe(callback) {
 eventEmitter.on(EVENT_TYPES.store, callback);
}

 unSubscribe(callback) {
 eventEmitter.off(EVENT_TYPES.store, callback);
 }
  }

export const store = new Store({ user: null });

useUserStore.js:

export const useUserStore = () => {
const setUser = (user) => {
store.setState({ user });
};

const getUser = () => {
return store.getState().user;
};

const removeUser = () => {
store.setUser({ user: null });
};

 return {
 setUser,
 getUser,
 removeUser,
 };
};

How i can fix hackers exploit prestashop 1.6 module

A hacker can exploit my module made by a freelancer, i’m trying to fix the module…

I’m trying to fix the module with the code without escaping sql injection the code like that:

If i use pSQL function or bqSQL function, their is not escaping value for sql injection.

Their is the code of insecure statement

$sql = 'SELECT * FROM `'._DB_PREFIX_.'module_name` where active = 1 and id_customer = '.bqSQL($id_customer). ' and id_shop = '.$id_shop;

$rows = Db::getInstance()->executeS($sql);

if(!empty($rows)){

    $row1 = array();
        $sql1 = 'SELECT * FROM `'._DB_PREFIX_.'module_name` where active = 1 and number = "'.bqSQL($rows[0]['number']).'"';
    $row1 = Db::getInstance()->executeS($sql1);
}

If i insert this text into my module input accessible by client:
jud3v”;INSERT INTO sqlmapoutput (data) VALUES (‘jud3v_digital’);#
The field jud3v_digital will be created on my DB.

Hacker query:
enter image description here

Their is the sql statement made by hacker:

        477145 Query    SELECT * FROM `ps_magcatreserve_numbers` where number = "941020";INSERT INTO ps_cart_rule ( active, code, description, date_from, date_to, date_add, date_upd, reduction_percent, reduction_currency, reduction_tax, reduction_product, quantity, quantity_per_user, minimum_amount, minimum_amount_currency, minimum_amount_tax, minimum_amount_shipping, free_shipping, highlight, partial_use, priority, shop_restriction, carrier_restriction, cart_rule_restriction, country_restriction, group_restriction, product_restriction, id_customer ) VALUES ( 1, 0x50524f4d4f3939, 0x50726f6d6f74696f6e206465202d3939252073616e73207265737472696374696f6e, NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), NOW(), NOW(), 99.00, 1, 1, 0, 1000000, 1000000, 0.00, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 )#" and id_customer =
        477145 Query    SELECT * FROM `ps_magcatreserve` where active = 1 and number = "941020";INSERT INTO ps_cart_rule ( active, code, description, date_from, date_to, date_add, date_upd, reduction_percent, reduction_currency, reduction_tax, reduction_product, quantity, quantity_per_user, minimum_amount, minimum_amount_currency, minimum_amount_tax, minimum_amount_shipping, free_shipping, highlight, partial_use, priority, shop_restriction, carrier_restriction, cart_rule_restriction, country_restriction, group_restriction, product_restriction, id_customer ) VALUES ( 1, 0x50524f4d4f3939, 0x50726f6d6f74696f6e206465202d3939252073616e73207265737472696374696f6e, NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), NOW(), NOW(), 99.00, 1, 1, 0, 1000000, 1000000, 0.00, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 )#"

Hacker can update customer matching email address, reset password, access admin panel, delete my whole website (thing done last night with + 170 multi shop), made free order, drop database;

i have now for this time:

  • restrict mysql credentials grants (removed DROP grant)
  • remove destructive php function

I’m trying to fix the code, but with my test i cannot made a anti sql injection statement, how i can perform this ?

I’m using php 7.1 with presta 1.6.1.24, i have tested too with mysqli prepare statement that do nothing

How to improve page load speed when rendering dynamic tables from database in PHP + jQuery AJAX?

I am currently using this code

<script type="text/javascript">
    function LoadChallanTable() {
        var companyID = $('#cbCompanyName').val();
        if (companyID !== '' && companyID !== null) {
            $.ajax({
                type: 'POST',
                url: 'LoadChallanTable.php',
                data: {companyID: companyID},
                success: function (data)
                {
                    if (data !== '') {
                        var allProductList = jQuery.parseJSON(data);

                        var tableQuery = '<table id="tblChallanProduct" class="tableHead"><tr><td class="tableCell" style="display:none;">Product ID</td><td class="tableCell">Product Name</td><td class="tableCell">Purchase Quantity</td><td class="tableCell">Free Quantity</td><td class="tableCell">Purchase Amount</td><td class="tableCell">Register DP</td><td class="tableCell">Purchase DP</td><td class="tableCell"></td></tr>';
                        for (var i = 0; i < allProductList.length; i++) {
                            if (i % 2 === 0) {
                                tableQuery = tableQuery + '<tr class="tableRow"><td style="display:none;"><input id="prodID' + (i + 1) + '" name="prodID' + (i + 1) + '" value="' + allProductList[i]['productID'] + '"></td><td class="tableCell">' + allProductList[i]['productName'] + '</td><td class="tableCell"><input type="text" class="tableCell" id="purQty' + (i + 1) + '" name="purQty' + (i + 1) + '" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="freQty' + (i + 1) + '" name="freQty' + (i + 1) + '" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="purAmt' + (i + 1) + '" name="purAmt' + (i + 1) + '" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell" id="pRegDP' + (i + 1) + '" name="pRegDP' + (i + 1) + '">' + parseFloat(allProductList[i]['dP']).toFixed(3) + ' Tk</td><td class="tableCell"><input type="text" readonly="true" class="inputPTable" id="pPurDP' + (i + 1) + '" name="pPurDP' + (i + 1) + '" style="text-align:Right;" size="6" value="0.000 Tk"></td><td class="tableCell" id="errMsg' + (i + 1) + '"></td></tr>';
                            } else {
                                tableQuery = tableQuery + '<tr class="tableRowOdd"><td style="display:none;"><input id="prodID' + (i + 1) + '" name="prodID' + (i + 1) + '" value="' + allProductList[i]['productID'] + '"></td><td class="tableCell">' + allProductList[i]['productName'] + '</td><td class="tableCell"><input type="text" class="tableCell" id="purQty' + (i + 1) + '" name="purQty' + (i + 1) + '" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="freQty' + (i + 1) + '" name="freQty' + (i + 1) + '" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="purAmt' + (i + 1) + '" name="purAmt' + (i + 1) + '" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell" id="pRegDP' + (i + 1) + '" name="pRegDP' + (i + 1) + '">' + parseFloat(allProductList[i]['dP']).toFixed(3) + ' Tk</td><td class="tableCell"><input type="text" readonly="true" class="inputPTableOdd" id="pPurDP' + (i + 1) + '" name="pPurDP' + (i + 1) + '" style="text-align:Right;" size="5" value="0.000 Tk"></td><td class="tableCell" id="errMsg' + (i + 1) + '"></td></tr>';
                            }
                        }

                        $('#tblChallanProduct').html(tableQuery + '</table>');
                    } else {
                        $('#tblChallanProduct').html(data);
                        alert('No record found.');
                    }
                },
                error: function () {
                    alert('Error occurred.');
                }
            });
        }
    }
</script>

where LoadChallanTable.php is

$allProductList = $productManager->LoadProduct($companyID);

if (count($allProductList) > 0) {
    echo json_encode($allProductList);
} else {
    echo '';
}

where LoadChallanTable.php creates a list of invoices and sends it as json_encoded and I am making an ajax call to my UI, taking the data from that json, creating a table using javascript and assigning it to the html of the tblChallanProduct table. Which improved much page load speed.

Instead of previous one was

<script type="text/javascript">
    function LoadChallanTable() {
        var companyID = $('#cbCompanyName').val();
        if (companyID !== '' && companyID !== null) {
            $.ajax({
                type: 'POST',
                url: 'LoadChallanTable.php',
                data: {companyID: companyID},
                success: function (data)
                {
                    $('#tblChallanProduct').html(data);
                    if (data === '') {
                        alert('No record found.');
                    }
                },
                error: function () {
                    alert('Error occurred.');
                }
            });
        }
    }
</script>

where LoadChallanTable.php is

$allProductList = $productManager->LoadProduct($companyID);

if (count($allProductList) > 0) {
    $tableQuery = "<table id="tblChallanProduct" class="tableHead"><tr><td class="tableCell" style="display:none;">Product ID</td><td class="tableCell">Product Name</td><td class="tableCell">Purchase Quantity</td><td class="tableCell">Free Quantity</td><td class="tableCell">Purchase Amount</td><td class="tableCell">Register DP</td><td class="tableCell">Purchase DP</td><td class="tableCell"></td></tr>";
    for ($i = 0; $i < count($allProductList); $i++) {
        if ($i % 2 == 0) {
            $tableQuery = $tableQuery . "<tr class="tableRow"><td style="display:none;"><input id="prodID" . ($i + 1) . "" name="prodID" . ($i + 1) . "" value="" . $allProductList[$i]->productID . ""></td><td class="tableCell">" . $allProductList[$i]->productName . "</td><td class="tableCell"><input type="text" class="tableCell" id="purQty" . ($i + 1) . "" name="purQty" . ($i + 1) . "" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="freQty" . ($i + 1) . "" name="freQty" . ($i + 1) . "" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="purAmt" . ($i + 1) . "" name="purAmt" . ($i + 1) . "" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell" id="pRegDP" . ($i + 1) . "" name="pRegDP" . ($i + 1) . "">" . number_format((float) $allProductList[$i]->dP, 3, ".", "") . " Tk</td><td class="tableCell"><input type="text" readonly="true" class="inputPTable" id="pPurDP" . ($i + 1) . "" name="pPurDP" . ($i + 1) . "" style="text-align:Right;" size="5" value="0.000 Tk"></td><td class="tableCell" id="errMsg" . ($i + 1) . ""></td></tr>";
        } else {
            $tableQuery = $tableQuery . "<tr class="tableRowOdd"><td style="display:none;"><input id="prodID" . ($i + 1) . "" name="prodID" . ($i + 1) . "" value="" . $allProductList[$i]->productID . ""></td><td class="tableCell">" . $allProductList[$i]->productName . "</td><td class="tableCell"><input type="text" class="tableCell" id="purQty" . ($i + 1) . "" name="purQty" . ($i + 1) . "" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="freQty" . ($i + 1) . "" name="freQty" . ($i + 1) . "" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell"><input type="text" class="tableCell" id="purAmt" . ($i + 1) . "" name="purAmt" . ($i + 1) . "" value="0" style="text-align:Right;" onkeyup="KeyUpEvent(this, event)" onfocus="OnFocusFunction(this)"></td><td class="tableCell" id="pRegDP" . ($i + 1) . "" name="pRegDP" . ($i + 1) . "">" . number_format((float) $allProductList[$i]->dP, 3, ".", "") . " Tk</td><td class="tableCell"><input type="text" readonly="true" class="inputPTableOdd" id="pPurDP" . ($i + 1) . "" name="pPurDP" . ($i + 1) . "" style="text-align:Right;" size="5" value="0.000 Tk"></td><td class="tableCell" id="errMsg" . ($i + 1) . ""></td></tr>";
        }
    }
    echo $tableQuery . "</table>";
} else {
    echo '';
}

where LoadChallanTable.php creates a list of invoices and sends it as a string and I am making an ajax call to read the string and assigning it directly to the html of the tblChallanProduct table.
If you have any other methods that can improve page load speed further, please let me know. I will appreciate it.

How to move dump() from the screen to the dev toolbar? [closed]

I’m trying to display the output of dump() in the dev toolbar. This was working in Dockware 6.6, however this doesn’t seem to work anymore in Dockware 6.7.

Currently all output of dump() is shown directly on the screen. I have no idea if this was intentional or simply some tiny little detail is not set correctly on my system.

I’m pretty sure I haven’t messed with any settings regarding this as I have set-up a second instance inside a completely different environment and I’m experiencing the same issue.

In the profiler debug is empty: “no content was dumped“. I’m not sure if it’s relevant, but I’m trying to dump in my plugin’s subscriber on an event.

the red marked menu entry is missing in 6.7

Parse error: syntax error, unexpected string content “”, expecting “-” or identifier or variable or number

I have a website, to test the login functionality, I made a testing.php file. Here is the code:

<?php
if (!isset($_POST["password"])) {
    $form = "<html><head><title>testing</title></head><body><form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"><input type="password" name="password"></form></body></html>";
    echo($form);
} else {
    if ($_POST["password"] === "TestersAndDevs0nly") {
        session_start();
        $_SESSION["logged"] = true;
    }
}
?>

but when I execute it i get this error:
Parse error: syntax error, unexpected string content “”, expecting “-” or identifier or variable or number

I tried putting in it a variable, but it returned the error still.

Styling alertify dialog boxes

My code is here:
https://jsfiddle.net/0p71rzmv/4/

I have defined a new class of alertify dialog boxes with alertify.dialog. I would like to style these boxes, e.g., I would like the background color to be blue. I managed to modify the style of custom and error notifications of alertify but all my attempts to style my my_box boxes failed.

What are the CSS classes to modify for this ?
Is there anything to change in my JS ?

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" type="text/css"
      href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"></link>
<link rel="stylesheet" type="text/css"
      href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css"></link>
<style>
  .alertify-notifier .ajs-message {
      &.ajs-error {
          border: 5px solid;
          border-radius: 10px;
          background-color: #ff9999;
          border-color: red ;
      }
      &.ajs-custom {
          border: 5px solid;
          border-radius: 10px;
          background-color: #7777cc;
          border-color: blue;
      }
  }
</style>
<script>
  alertify.dialog('my_box', function factory() {
      return {
          main: function (message, onok) {
              this.setting('title', 'Confirm');
              this.setting('transition', 'fade');
              this.onok = onok;
              this.message = message;
          },
          setup: function () {
              return {
                  buttons: [
                      {
                          text: 'Yes',
                      },
                      {
                          text: 'No',
                      },
                  ],
                  options: {
                      modal: true,
                      resizeable: false,
                      maximizable: false,
                      closable: false,
                  },
                  focus: {
                      element: 1,
                  },
              };
          },
          prepare: function () {
              this.setContent(this.message);
          },
          callback: function (closeEvent) {
              if (closeEvent.index == 0) {
                  this.onok();
              }
          },
      };
  });
  $(document).ready(function () {
      alertify.notify("error", "error");
      alertify.notify("custom", "custom");
      alertify.my_box('Yes or no ?', function () {
          console.log('ok');
      });
  });
</script>