curl in php version 7.3 post data are empty in endpoint

i have trouble to solve problem for post-ing data from webpage to endpoint.
I create webpage in html/css and javascript. User can add or delete data and if user want to submit data, i use php to send this usercreated data with php to endpoint. Endpoint is database, where rest api is used. For the problem of CORS we added proxy server as nginx, which just listen to ip and port and redict from this incoming ip port to another ip and port. We added also SSL Cert from trusted CA. Sofar OK, but randomly post data comes empty to endpoint. Authenfitication for user sudmiting data happens over Bearer Token. All logs show valid bearer token and data “should” be there, but is empty on endpoint. I am really desperate for solution.
For security we also add cloudflare recaptca on client-site. I forget to mention, we dont own webserver. This host webprovider. I cant set any php.ini values.

We tried with different browser, ms edge, chrome, firefox, opera, result is always the same.

How to show labels in an apache echarts custom series?

I’m trying to create a “custom” apache echarts component that acts as a timeline for a series of events. However, I managed to do everything but to get the labels to show. Here’s my script:

 <script type="text/javascript">
        var myChart = echarts.init(document.getElementById('main'));
    
        myChart.setOption({
            grid: {
                containLabel: true,
            },
            width: 1300,
        });
    
        fetch('data.json')
            .then(response => response.json())
            .then(data => {
                data.sort((a, b) => new Date(a.date) - new Date(b.date));
    
                const uniqueDates = [...new Set(data.map(item => item.date))];
                uniqueDates.sort((a, b) => new Date(a) - new Date(b));
                const startDate = new Date(uniqueDates[0]);
                const endDate = new Date(uniqueDates[uniqueDates.length - 1]);
                const allDates = [];
                for (let dt = new Date(startDate); dt <= endDate; dt.setDate(dt.getDate() + 1)) {
                    allDates.push(dt.toISOString().split('T')[0]);
                }
    
                const groupedByDate = data.reduce((acc, curr) => {
                    if (!acc[curr.date]) {
                        acc[curr.date] = [];
                    }
                    acc[curr.date].push(curr);
                    return acc;
                }, {});
    
                Object.keys(groupedByDate).forEach(date => {
                    groupedByDate[date].forEach((item, index) => {
                        item.value[0] = allDates.indexOf(date);
                        item.value[1] = index;
                    });
                });
    
                const processedData = Object.values(groupedByDate).flat();
    
                var option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: function (params) {
                            if (params.name && params.value[2] && params.value[2].detail) {
                                return params.name + '<br/>' + params.value[2].detail;
                            }
                            return params.name;
                        },
                        axisPointer: {
                            type: 'cross'
                        },
                    },
                    xAxis: {
                        type: 'category',
                        data: allDates
                    },
                    yAxis: {
                        type: 'value',
                        show: false
                    },
                    dataZoom: [{
                        type: 'inside',
                        xAxisIndex: [0, 1],
                        start: 0,
                        end: 100
                    }, {
                        show: true,
                        xAxisIndex: [0, 1],
                        type: 'slider',
                        bottom: 30,
                        start: 0,
                        end: 100
                    }],
                    series: [{
                        type: 'custom',
                        renderItem: function (params, api) {
                            const currentData = data[params.dataIndex];
                            const yValue = api.value(1);
                            const start = api.coord([api.value(0), yValue]);
                            const size = currentData.size || api.size([0, 1]);
                            const style = {
                                fill: currentData.color || '#000'
                            };
    
                            return {
                                type: 'group',
                                children: [
                                    {
                                        type: 'rect',
                                        shape: {
                                            x: start[0] - size[0] * 0.4,
                                            y: start[1] - size[1] / 2,
                                            width: size[0] * 0.8,
                                            height: size[1] / 2
                                        },
                                        style: style
                                    }
                                ]
                            };
                        },
                        name: 'Events',
                        barWidth: '20%',
                        data: processedData,
                        animation: true,
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: 'test',  // Hardcoding 'test' as the label text for testing
                            fontWeight: 'medium',
                            color: '#fff',
                            shadowColor: '#000',
                            shadowBlur: 2,
                            shadowOffsetX: 1,
                            shadowOffsetY: 1
                        }
                    }]
                };
    
                myChart.setOption(option);
            })
            .catch(error => {
                console.error('Error fetching the data:', error);
            });
    </script>

Here’s what it looks like now:
Current version

I tried to add the table in the custom render function like this:

    return {
        type: 'group',
        children: [
            {
                type: 'rect',
                shape: {
                    x: start[0] - size[0] * 0.4,
                    y: start[1] - size[1] / 2,
                    width: size[0] * 0.8,
                    height: size[1] / 2
                },
                style: style 
            },
            {
                type: 'text',
                style: {
                    text: currentData.name,
                    x: start[0],
                    y: start[1] - size[1] / 4,
                    textAlign: 'center',
                    textVerticalAlign: 'middle',
                    fontWeight: 'medium',
                    textFill: '#fff',
                    textShadowColor: currentData.color || '#000',
                    textShadowBlur: 2,
                    textShadowOffsetX: 1,
                    textShadowOffsetY: 1
                }
            }
        ]
    };

It worked but it broke other things, and it does not have the functionalties I want that are easily configured in the label

Elementor custom widget using toggle javascript

I have created an Elementor custom widget, a clone of the official Toggle widget with the same code of the original but different widget name.

The problem is that the official javascript handler that manages the open/close feature is not attached to my widget and it’s not working (all tabs are always closed and don’t open).

Can I use the Elementor built-in JS handler with my clone in some way?

Thanks

requestFullscreen is unreliable when called from touchstart

I’m using firefox on android, and remote debugging it on linux via adb.

I’m making a webapp to be used on mobile, and I’d like it to be fullscreen. My solution is to enter fullscreen when the user taps the screen, but my problem is that requestFullscreen is unreliable when called from a touchstart event. In this simplified example I use toggle so we can see it’s continuing effect.

<!DOCTYPE html>
<html lang="en">
  <body>
    <script>
      function toggleFullscreen(event) {
        event.preventDefault();

        if (document.fullscreenElement) {
          document.exitFullscreen();
        } else {
          document.documentElement.requestFullscreen();
        }
      }

      touchCatcherElement.addEventListener('touchstart', toggleFullscreen, false);
    </script>
  </body>
</html>

This will fail at lease once, but once it works it seems to keep working reliably. I get the following error:

Request for fullscreen was denied because Element.requestFullscreen() was not called from inside a short running user-generated event handler.

A solutions I’ve tried is using the click event, which is 100% reliable

<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="a"></div>
    <script>
      function toggleFullscreen(event) {
        if (document.fullscreenElement) {
          document.exitFullscreen();
        } else {
          document.documentElement.requestFullscreen();
        }
      }
      function dummy(event) {
        event.preventDefault();
      }

      window.addEventListener('touchstart', dummy, { passive: false });
      window.addEventListener('click', toggleFullscreen, false);
    </script>
  </body>
</html>

The problem with this is I want to use preventDefault and that seems to stop the other handler from running, and I can’t be sure which order they’ll be executed in.

Does anyone know why touchstart doesn’t create reliable transient activation?
Or do you have any recommendations on other ways I could do this fullscreen functionality?

Can’t resolve ‘fs’, ‘path, ‘util’ in create-react-app

In creat-react-app, in src folder, I have a database folder, with new.db file, and sql.js file with the following code in the sql.js file:

import sqlite3 from 'sqlite3';

const path = new URL('new.db', import.meta.url).pathname;
const db = new sqlite3.Database(path);

db.run('CREATE TABLE IF NOT EXISTS newTable (id INTEGER PRIMARY KEY, name TEXT, password TEXT)');

export default db;

Then, in App.js I have the following code:

import db from "../../database/sql";

function App() {
  return (
    <p>Hello, World!</p>
  );
}

export default App;

The problem is that it throws me a couple of errors:

ERROR in ./node_modules/bindings/bindings.js 5:9-22 Module not found: Error: Can't resolve 'fs' in 'D:projectssecond_practicemy-appnode_modulesbindings' ERROR in ./node_modules/bindings/bindings.js 6:9-24 Module not found: Error: Can't resolve 'path' in 'D:projectssecond_practicemy-appnode_modulesbindings'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
    - install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "path": false } ERROR in ./node_modules/file-uri-to-path/index.js 5:10-29 Module not found: Error: Can't resolve 'path' in 'D:projectssecond_practicemy-appnode_modulesfile-uri-to-path'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
    - install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "path": false } ERROR in ./node_modules/sqlite3/lib/sqlite3.js 1:13-28 Module not found: Error: Can't resolve 'path' in 'D:projectssecond_practicemy-appnode_modulessqlite3lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
    - install 'path-browserify' If you don't want to include a polyfill, you can use an empty module like this:     resolve.fallback: { "path": false } ERROR in ./node_modules/sqlite3/lib/trace.js 2:13-28 Module not found: Error: Can't resolve 'util' in 'D:projectssecond_practicemy-appnode_modulessqlite3lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
    - install 'util' If you don't want to include a polyfill, you can use an empty module like this:    resolve.fallback: { "util": false } 

I tried to add this in package.json:

"browser": {"fs": false, "path": false, "os": false}`

but it didn’t help. Then I tried to add this code in config.overrides.js after installing necessary dependencies (and changing react scripts to react-app rewired start and etc.):

const webpack = require('webpack');

module.exports = function override(config) {
    const fallback = config.resolve.fallback || {};
    Object.assign(fallback, {
        "crypto": require.resolve("crypto-browserify"),
        "stream": require.resolve("stream-browserify"),
        "assert": require.resolve("assert"),
        "http": require.resolve("stream-http"),
        "https": require.resolve("https-browserify"),
        "os": require.resolve("os-browserify"),
        "url": require.resolve("url")
    })
    config.resolve.fallback = fallback;
    config.plugins = (config.plugins || []).concat([
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer']
        })
    ])
    return config;
}
                                                                          

And none of them much of a help, the same couple of errors throws onto screen.

OAuth 2.0 Spotify InternalOAuthError

InternalOAuthError: failed to fetch user profile
    at C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-spotifylibpassport-spotifystrategy.js:151:19
    at passBackControl (C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2node_modulesoauthliboauth2.js:132:9)
    at IncomingMessage.<anonymous> (C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2node_modulesoauthliboauth2.js:157:7)
    at IncomingMessage.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

after refreshing page message gets changed:

TokenError: Invalid authorization code
    at OAuth2Strategy.parseErrorResponse (C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2libstrategy.js:373:12)
    at OAuth2Strategy._createOAuthError (C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2libstrategy.js:420:16)
    at C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2libstrategy.js:177:45
    at C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-spotifylibpassport-spotifystrategy.js:81:20
    at passBackControl (C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2node_modulesoauthliboauth2.js:132:9)
    at IncomingMessage.<anonymous> (C:UsersPAKSHALDocumentsPakshalProjectsSaarangbackendnode_modulespassport-oauth2node_modulesoauthliboauth2.js:157:7)
    at IncomingMessage.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
  • This happens for different user’s ,I tried with three users , two of the users get this problem, one user doesnt get this problem.

  • ‘/’ -> Hello World

  • ‘/auth/spotify’ -> ‘auth/spotify/callback’ -> enter credentials

  • ‘/dashboard’ -> Welcome, username!

    instead of above output of recieving username upon logging in with correct credentials i get those two errors listed.
    I am using Oauth 2.0 spotify for logging in my app , i created app in spotify dashboard , took client credentials , secret key and entered correct callback uri, used passport-spotify .
    This is what im doing :

  • Index.js

    const express = require('express');
    const mongoose = require('mongoose');
    const passport = require('passport');
    const session = require('express-session');
    const authRoutes = require('./routes/auth');
    const groupRoutes = require('./routes/grouproutes');
    require('dotenv').config();
    require('./config/passport');  // Initialize passport strategy
    const cors = require('cors');
    
    const app = express();
    
    app.use(cors());
    app.use(express.json());
    // Middleware for session management
    app.use(session({
      secret: process.env.SESSION_SECRET,
      resave: false,
      saveUninitialized: true
    }));
    
    // Passport middleware
    app.use(passport.initialize());
    app.use(passport.session());
    
    // MongoDB connection
    mongoose.connect(process.env.MONGO_URI)
      .then(() => console.log('MongoDB connected'))
      .catch(err => console.error('MongoDB connection error:', err));
    
    // Auth routes
    app.use('/auth', authRoutes);
    app.use('/group',groupRoutes);
    
    app.listen(process.env.PORT || 3000, () => {
      console.log(`Server running on port ${process.env.PORT || 3000}`);
      app.get('/', (req, res) => {
        res.send('Hello, world!');
      });
    });
    
    
    app.get('/dashboard', (req, res) => {
      if (!req.isAuthenticated()) {
        return res.redirect('/auth/spotify');
      }
      res.send(`Welcome, ${req.user.displayName}!`);  // Access user info from Spotify profile
    });
    
    
  • Passport.js

    const passport = require('passport');
    const SpotifyStrategy = require('passport-spotify').Strategy;
    const User = require('../models/User');  // Your User model
    
    passport.use(new SpotifyStrategy({
      clientID: process.env.SPOTIFY_CLIENT_ID,
      clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
      callbackURL: "http://localhost:3000/auth/spotify/callback",
    },
      async function(accessToken, refreshToken, expires_in, profile, done) {
        try {
          // Check if the user already exists
          let user = await User.findOne({ spotifyId: profile.id });
    
          if (!user) {
            // If user doesn't exist, create a new one
            user = new User({
              spotifyId: profile.id,
              displayName: profile.displayName,
              email: profile.emails[0].value,
              profileImage: profile.photos[0]?.value,
              accessToken,
              refreshToken
            });
            await user.save();
          } else {
            // If user exists, update tokens
            user.accessToken = accessToken;
            user.refreshToken = refreshToken;
            await user.save();
          }
    
          return done(null, user);
        } catch (err) {
          return done(err, null);
        }
      }
    ));
    
    passport.serializeUser((user, done) => {
      done(null, user.id);
    });
    
    passport.deserializeUser(async (id, done) => {
      try {
        const user = await User.findById(id);
        done(null, user);
      } catch (err) {
        done(err, null);
      }
    });
    
    
  • authmiddleware.js

    const axios = require('axios');
    const User = require('../models/User');
    
    const ensureAuthenticated = async (req, res, next) => {
      const authHeader = req.headers.authorization;
    
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).json({ message: 'User not authenticated' });
      }
    
      const token = authHeader.split(' ')[1];
    
      try {
        // Validate the token by making a request to Spotify API
        const response = await axios.get('https://api.spotify.com/v1/me', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
    
        const spotifyUserData = response.data;
    
        // Find the user in your MongoDB by spotifyId
        const user = await User.findOne({ spotifyId: spotifyUserData.id });
    
        if (!user) {
          return res.status(401).json({ message: 'User not found in the system' });
        }
    
        // Attach MongoDB user object to req.user
        req.user = user;
    
        next(); // Continue to the next middleware or route handler
      } catch (error) {
        return res.status(401).json({ message: 'Invalid token or session expired' });
      }
    };
    
    module.exports = ensureAuthenticated;
    
    
  • User.js (model)

    const mongoose = require('mongoose');
    
    const userSchema = new mongoose.Schema({
      spotifyId: { type: String, required: true, unique: true }, // Spotify ID
      displayName: { type: String },  // Spotify username
      email: { type: String },        // Spotify email
      profileImage: { type: String }, // Spotify profile picture
      accessToken: { type: String },  // Spotify OAuth access token
      refreshToken: { type: String }, // Spotify OAuth refresh token
      friends: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }], // Friends in your app
      friendRequests: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }], // Pending friend requests
      activeGroup: { type: mongoose.Schema.Types.ObjectId, ref: 'Group', default: null },  // Active group, null if not in any
      createdAt: { type: Date, default: Date.now }
    });
    
    module.exports = mongoose.model('User', userSchema);
    
    

Add data attribute to WooCommerce script

I would like to add a data attribute to a script that is placed by the WooCommerce plugin. This is the script:

woocommerce/assets/js/select2/select2.min.js

Because Cookiebot is set to automatic for us, this script is not loaded if the Cookies are refused. This causes a problem with our checkout and can be solved if we ignore the script.

Is it possible to add this attribute to that script via a function?

data-cookieconsent="ignore"

That should solve it, but I don’t know if this can be done with a function or another way.

TypeError: post._id is undefined

I am learning NextJS, and I have encountered the following error:

const QuoteCard = ({ post }) => {
  const handleEdit = (post) => {
    router.push(`/update-quote/${post._id.toString()}`);
  };

  const handleDelete = async (post) => {
    const hasConfirmed = confirm(
      "Are you sure you want to delete this quote?"
    );

    if (hasConfirmed) {
      try {
        await fetch(`/api/quote/${post._id.toString()}`, {
          method: "DELETE",
        });

        const filteredPosts = myPosts.filter((item) => item._id !== post._id);

        setMyPosts(filteredPosts);
      } catch (error) {
        console.log(error);
      }
    }
  };
};

Whenever I try to invoke the handleEdit or handleDelete functions:

<div className="mt-5 flex flex-row items-center justify-center gap-4 border-t pt-3">
  <p className="button p-3 bg-gray-900 text-gray-100 text-sm cursor-pointer w-full" onClick={handleEdit}>
    Edit
  </p>
  <p className="button p-3 bg-red-600 text-gray-100 text-sm cursor-pointer w-full" onClick={handleDelete}>
    Delete
  </p>
</div>

I get an error saying post._id is not defined. Every other function involving ‘post’ is working fine however.

I tried logging post to the console and it does have an ‘_id’ attribute, what could the problem be?

Odoo 15 POS multi uom and lot set up

Odoo 15 pos

I was add multi uom that for each product. So I was write multi uom and overwite function _onDoRefund and _fetchSyncedOrders at Ticket Screen.js like this.
async _fetchSyncedOrders() { const domain = this._computeSyncedOrdersDomain(); const limit = this._state.syncedOrders.nPerPage; const offset = (this._state.syncedOrders.currentPage - 1) * this._state.syncedOrders.nPerPage; const { ids, totalCount } = await this.rpc({ model: 'pos.order', method: 'search_paid_order_ids', kwargs: { config_id: this.env.pos.config.id, domain, limit, offset }, context: this.env.session.user_context, }); const idsNotInCache = ids.filter((id) => !(id in this._state.syncedOrders.cache)); if (idsNotInCache.length > 0) { const fetchedOrders = await this.rpc({ model: 'pos.order', method: 'export_for_ui', args: [idsNotInCache], context: this.env.session.user_context, }); // Check for missing products and load them in the PoS await this.env.pos._loadMissingProducts(fetchedOrders); // Cache these fetched orders so that next time, no need to fetch // them again, unless invalidated. See _onInvoiceOrder`.
fetchedOrders.forEach((order) => {
this._state.syncedOrders.cache[order.id] = new models.Order({}, { pos: this.env.pos, json: order });
var cacheOrder = this._state.syncedOrders.cache[order.id];
for(var index=0; index < order.lines.length; index++){
var values = order.lines[index][2];
console.log(‘This is fetching’,cacheOrder.orderlines.models[index])
console.log(‘This is fetching value’,values)
cacheOrder.orderlines.models[index].multi_uom_line_id = values.multi_uom_line_id;
cacheOrder.orderlines.models[index].price_manually_set = values.price_manually_set;
cacheOrder.orderlines.models[index].set_unit_price(values.multi_price_unit);
cacheOrder.orderlines.models[index].set_discount(values.multi_discount);
cacheOrder.orderlines.models[index].refunded_qty = values.refunded_qty;
cacheOrder.orderlines.models[index].refunded_orderline_id = values.refunded_orderline_id;
}
this._state.syncedOrders.cache[order.id] = cacheOrder;
});
}
this._state.syncedOrders.totalCount = totalCount;
this._state.syncedOrders.toShow = ids.map((id) => this._state.syncedOrders.cache[id]);
}

async _onDoRefund() {
    const order = this.getSelectedSyncedOrder();
    if (!order) {
        this._state.ui.highlightHeaderNote = !this._state.ui.highlightHeaderNote;
        return this.render();
    }

    if (this._doesOrderHaveSoleItem(order)) {
        this._prepareAutoRefundOnOrder(order);
    }

    const customer = order.get_client();

    // Select the lines from toRefundLines (can come from different orders)
    // such that:
    //   - the quantity to refund is not zero
    //   - if there is customer in the selected paid order, select the items
    //     with the same orderPartnerId
    //   - it is not yet linked to an active order (no destinationOrderUid)
    const allToRefundDetails = Object.values(this.env.pos.toRefundLines).filter(
        ({ qty, orderline, destinationOrderUid }) =>
            !this.env.pos.isProductQtyZero(qty) &&
            (customer ? orderline.orderPartnerId == customer.id : true) &&
            !destinationOrderUid
    );
    if (allToRefundDetails.length == 0) {
        this._state.ui.highlightHeaderNote = !this._state.ui.highlightHeaderNote;
        return this.render();
    }

    // The order that will contain the refund orderlines.
    // Use the destinationOrder from props if the order to refund has the same
    // customer as the destinationOrder.
    const destinationOrder =
        this.props.destinationOrder && customer === this.props.destinationOrder.get_client()
            ? this.props.destinationOrder
            : this.env.pos.add_new_order({ silent: true });

    // Add orderline for each toRefundDetail to the destinationOrder.
    for (const refundDetail of allToRefundDetails) {
        const { qty, orderline } = refundDetail;
        const syncedOrders = this._state.syncedOrders.cache;
        let uom_line;
        for(var orderId of Object.keys(syncedOrders)){
            for(var line of syncedOrders[orderId].orderlines.models){
                if(line.id === orderline.id){
                    uom_line = line.multi_uom_line_id;
                    break;
                }
            }
        }
        console.log('This is lot',orderline.pack_lot_lines)
        await destinationOrder.add_product(this.env.pos.db.get_product_by_id(orderline.productId), {
            quantity: -qty,  // Refund the correct quantity
            qty: -qty,  // Refund the correct quantity
            price: orderline.price,
            lst_price: orderline.price,
            extras: { price_manually_set: true },
            merge: false,
            refunded_orderline_id: orderline.id,
            tax_ids: orderline.tax_ids,
            discount: orderline.discount,
            multi_uom_line_id: uom_line,
            draftPackLotLines: orderline.pack_lot_lines ? { modifiedPackLotLines: [], newPackLotLines: orderline.pack_lot_lines} : false
        });

        refundDetail.destinationOrderUid = destinationOrder.uid;
    }

    // Set the customer to the destinationOrder.
    if (customer && !destinationOrder.get_client()) {
        destinationOrder.set_client(customer);

// destinationOrder.set_quantity(-qty)
}

    this._onCloseScreen();
}`

At this
`destinationOrder.add_product(this.env.pos.db.get_product_by_id(orderline.productId), {
quantity: -qty, // Refund the correct quantity
qty: -qty, // Refund the correct quantity
price: orderline.price,
lst_price: orderline.price,
extras: { price_manually_set: true },
merge: false,
refunded_orderline_id: orderline.id,
tax_ids: orderline.tax_ids,
discount: orderline.discount,
multi_uom_line_id: uom_line,
draftPackLotLines: orderline.pack_lot_lines ? { modifiedPackLotLines: [], newPackLotLines: orderline.pack_lot_lines} : false
});

        refundDetail.destinationOrderUid = destinationOrder.uid;
    }`

If not including draftPackLotLines, qty is working. But if it contain, How mush return qty, qty change to -1. How to fix?

At this
`destinationOrder.add_product(this.env.pos.db.get_product_by_id(orderline.productId), {
quantity: -qty, // Refund the correct quantity
qty: -qty, // Refund the correct quantity
price: orderline.price,
lst_price: orderline.price,
extras: { price_manually_set: true },
merge: false,
refunded_orderline_id: orderline.id,
tax_ids: orderline.tax_ids,
discount: orderline.discount,
multi_uom_line_id: uom_line,
draftPackLotLines: orderline.pack_lot_lines ? { modifiedPackLotLines: [], newPackLotLines: orderline.pack_lot_lines} : false
});

        refundDetail.destinationOrderUid = destinationOrder.uid;
    }`

If not including draftPackLotLines, qty is working. But if it contain, How mush return qty, qty change to -1. How to fix?

How to declare a true #private field with Symbol?

I try to declare private Symbol property in ES6+ class, below’s approach are all wrong.

class MyClass {
  #[Symbol.for('my-symbol-prop1')] = 'my-symbol-prop1';  // SyntaxError
  [#Symbol.for('my-symbol-prop1')] = 'my-symbol-prop1';  // SyntaxError
}

My question: Is there any way to declare a true private Symbol property, just using hash notation like #myPrivateSymbolfield, don’t using WeakMap or enclosure approach

Chrome extension: Run a function for specific website context?

Theres a specific website that has certain funtions that I’d like my Chrome extension to run whenever the page is active. Lets call this website website1

Website1 has function called enabled() that I’d like to run:

website1.enable()

Now to my understaning calling contentScript will run in its own sort of context and not website1 context. So calling website1.enable() actually results in below error

contentScript.js:2 Uncaught ReferenceError: website1

How can I call website1.enable() in its context?

Which is the better way to implement Array function in Javascript: _ => null or () => null? [closed]

I have recently realized that an Arrow function of Javascript can be even shorter than the traditional one, like this: _ => null

But I am unsure if there will be any performance cost over () => null.

If the unnamed variable in Javascript is similar to Java, then there shouldn’t be any memory allocation, so there won’t be any extra memory overhead.

I would like to know an expert’s opinion on this.
Thank you for your time.

Issue Updating Dynamic Table Inputs in PHP and JavaScript Code When Adding a New Row

I have PHP and JavaScript code that is used to update journal entries retrieved from a database. When I attempt to edit entries without adding a new dynamic row, the update works successfully. However, when I add a new dynamic row with JavaScript, I get the following error message:
“An error occurred while processing the data. Please try again.”
The main issue is that the new inputs added dynamically in the table are not recognized properly in the $_POST array, while only the rows fetched from the database are recognized.

**PHP and JavaScript Code:
**

$test_date = htmlspecialchars(strip_tags($antiXss->xss_clean($_POST['date'])));
$descrip = htmlspecialchars(strip_tags($antiXss->xss_clean($_POST['descrip'])));
$company = htmlspecialchars(strip_tags($antiXss->xss_clean($_POST['company'])));
$auth_token = htmlspecialchars(strip_tags($antiXss->xss_clean($_POST['auth_token'])));
$sum1 = filter_var($_POST['sum1'], FILTER_VALIDATE_FLOAT);
$sum2 = filter_var($_POST['sum2'], FILTER_VALIDATE_FLOAT);
$account = $antiXss->xss_clean($_POST["account"]); 
$debtor = $_POST["debtor"]; 
$creditor = $_POST["creditor"]; 
$description = $antiXss->xss_clean($_POST["description"]); 
$acc_serial = $antiXss->xss_clean($_POST["acc_serial"]);
$has_error = false;

foreach ($account as $index => $count) {
if (isset($account[$index]) && isset($debtor[$index]) && isset($creditor[$index]) && isset($description[$index]) && isset($acc_serial[$index])) {
    $s_account = htmlspecialchars(strip_tags($antiXss->xss_clean($account[$index])));
    $s_debtor = filter_var($debtor[$index], FILTER_SANITIZE_NUMBER_INT);
    $s_creditor = filter_var($creditor[$index], FILTER_SANITIZE_NUMBER_INT);
    $s_description = htmlspecialchars(strip_tags($antiXss->xss_clean($description[$index])));
    $s_acc_serial = htmlspecialchars(strip_tags($antiXss->xss_clean($acc_serial[$index])));

    if (empty($s_account) || $s_debtor == "" || $s_creditor == "" || empty($s_description) || empty($s_acc_serial)) {
        echo '<script> $(document).ready(function(){ toastr.error("Please fill in all fields"); }) </script>';
        $has_error = true;
        break;
    }
    if ($s_debtor == $s_creditor) {
        echo '<script> $(document).ready(function(){ toastr.error("Debtor and Creditor cannot be equal in the same row"); }) </script>';
        $has_error = true;
        break;
    }
} else {
    echo '<script> $(document).ready(function(){ toastr.error("An error occurred while processing the data. Please try again."); }) </script>';
    var_dump($_POST["account"], $_POST["debtor"], $_POST["creditor"], $_POST["description"], $_POST["acc_serial"]);
    $has_error = true;
    break;
}
}

**JavaScript for Dynamically Adding Rows:
**

var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr>'+
  '<td class="td">'+product_dd+'</td>'+
  '<td class="td"><input type="text" name="debtor[]" class="form-control debtor" required></td>'+
  '<td class="td"><input type="text" name="creditor[]" class="form-control creditor" required></td>'+
  '<td><input type="text" name="description[]" class="form-control" required></td>'+
  '<td><input type="hidden" name="acc_serial[]" class="form-control acc_serial" required></td>'+
  '<td><button type="button" class="btn btn-danger remove-tr"><i class="fas fa-trash"></i></button></td>'+
  '</tr>');
$('.js-example-basic-single').select2();
});

HTML

<tr>
    <td>
        <select class="form-control select_acount js-example-basic-single select2" name="account[]" required>
            <option value="<?php echo $_acc_serial_token;?>"><?php echo $_account;?></option>
            <?php
            $stmt = $con->prepare("SELECT * FROM categories WHERE parent_id != ? AND status = ? AND company = ?");
            $a = 0;
            $stmt->bind_param('iis', $a, $a, $_SESSION["company"]);
            $stmt->execute();
            $resultCategories = $stmt->get_result();
            $rows = [];
            foreach ($resultCategories as $row) {
                $rows[] = $row;
            ?>
            <option value="<?php echo htmlspecialchars(strip_tags($antiXss->xss_clean($row['acc_serial']))); ?>">
                <?php echo htmlspecialchars(strip_tags($antiXss->xss_clean($row['acc_name']))); ?>
            </option>
            <?php } ?>
            <?php $stmt->close(); ?>
        </select>
    </td>
    <td>
        <input type="text" style="max-width: 94px;" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false" name="debtor[]" value="<?php echo $_debtor;?>" class="form-control debtor" required>
    </td>
    <td>
        <input type="text" style="max-width: 94px;" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false" name="creditor[]" value="<?php echo $_creditor; ?>" class="form-control creditor" required>
    </td>
    <td>
        <input type="text" name="description[]" value="<?php echo $_description; ?>" style="min-width: 205px;" class="form-control" required>
    </td>
    <td>
        <input name="acc_serial[]" class="form-control acc_serial" type="hidden" value="<?php echo $_acc_serial_token; ?>" required>
    </td>
    <td>
        <button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash"></i></button>
    </td>
</tr>
  • I used var_dump($_POST) to check the new inputs after clicking the “Add Row” button. The output showed that the dynamically added inputs weren’t passed in $_POST.
  • I ensured that input names included [] (like debtor[] and creditor[]) to gather them as array fields, but the issue persists.
  • I tried validating the values with JavaScript and PHP to make sure they’re correctly set when adding a new row.

Why do regular objects in Javascript not have access to the prototype property and why do we always have to use __proto__?

suppose this is my code snippet
let myHeroes = [“thor”, “spiderman”];

let heroPower = {
thor: “hammer”,
spiderman: “sling”,
getSpiderPower: function () {
console.log(spider power is ${this.spiderman});
}
};

heroPower.getSpiderPower();

heroPower.proto.getThorPower = function () {
return thor power is ${heroPower.thor};
};

heroPower.getThorPower();

Now since regular objects in javascript don’t have access to the prototype in order to add this functionality to the object heropower do I really need to write proto after the object name to add properties or is there another easy way ?

I tried using heroPower.prototype.getThorPower=function(){..}
but it resulted in an error
I expect to add get thorpower function within the heroPower object without explicitly defining that function inside the object inserting it from outside the object