React-Spring – springs with delay get accumulated if the browser tab becomes inactive

I’m using react-spring for animating my website. I’m using useSprings to create multiple springs and add staggered delay for each spring using the index (check below). Everything works fine as expected.

But if I switch to a different tab and come back to my web app, all the delays get expired and all springs start at the same time. How to solve this?

const [circleSprings] = useSprings(dropCount, (i)=> {
    const xPos = Math.random() * w;
    return {
    from: { x: xPos, y: -20 },
    to: { x: xPos, y: h+20 },
    config: {
        duration: 1000,
        easing: easings.easeInQuart,
    },
    reset: true,
    delay: i * 500, // delay is staggered here
    loop: true,

}},[]);

How to render icon at right end of cell?

I have a Primereact v9 ReactJS code

<Column
                    field="status"
                    header="Status"
                    style={{
                        maxWidth: '150px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap'
                    }}
                    body={(rowData) => {
                        // Check if status is numeric
                        if ((rowData.status) !== "Дистрибутив обработан") {
                            // Render status with icon for numeric values
                            return (
                                <div>
                                    {/* Assuming you want to display the status value */}
                                    {rowData.status}
                                    {/* Replace with your icon component */}
                                    <i className="pi pi-check"></i>
                                </div>
                            );
                        } else {
                            // Render status as is for non-numeric values
                            return <div>{rowData.status}</div>;
                        }
                    }}
                    sortable
                />

I want to render icon from:

                          return (
                                <div>
                                    {/* Assuming you want to display the status value */}
                                    {rowData.status}
                                    {/* Replace with your icon component */}
                                    <i className="pi pi-check"></i>
                                </div>
                            );

at the right end of datatable cell
I’ve tried to use absolute position, but without normal result
How can i do that?

Html2Canvas removes the leading empty lines

I’d like to take a screenshot of a text area. I use html2canvas for this as I found in some example.

The problem is that if the words have empty lines above them, html2canvas removes these lines and just takes a screenshot for the words from the beginning of the field.

html:

Welcome there

</textarea>

<button onclick="takeScreenShot()">to image</button>

css:

 #target {
  width: 400px;
  height: 300px;
  background: black;
  color: #fff;
}
button {
  display: block;
  height: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
}

js:

window.takeScreenShot = function() {
  var textarea = document.getElementById("target");
  //textarea.style.height =300 + "px";
  html2canvas(textarea, {
    onrendered: function(canvas) {
      document.body.appendChild(canvas);
    },
  });
}

How can I just take a screenshot for the text area as it is without shifting the words to the beginning?

Here is my example: https://jsfiddle.net/uwkgd6yn/2/

Selecting a subset of features from feature collection in reduceRegions()

In an attempt to find ndvi and gndvi over a geometry containing 160 polygons, I have the following code.

var s2 = ee.ImageCollection('COPERNICUS/S2_HARMONIZED');
var geometry = ee.FeatureCollection('projects/ypm-rs-ml/assets/plots_160');

var startDate = ee.Date.fromYMD(2016, 11, 1);
var endDate = ee.Date.fromYMD(2018, 4, 1);

function addVegIndices(image) {
  image = image.addBands(image.normalizedDifference(['B8', 'B4']).rename('ndvi'));
  image = image.addBands(image.normalizedDifference(['B8', 'B3']).rename('gndvi'));
  return image;
} 

var originalCollection = s2
                        .filter(ee.Filter.date(startDate, endDate))
                        .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 30))
                        .filter(ee.Filter.bounds(geometry))
                        .map(addVegIndices);

var viBandsOriginal = originalCollection.select(['ndvi', 'gndvi'])

var stats = viBandsOriginal.reduceRegions({
collection: geometry,
reducer: ee.Reducer.mean(),
scale: 10
})

If collection parameter in reduceRegions() is set to ee.Feature(geometry.toList(159).get(0)), I get the stats for the 0th polygon only. But if I want to find stats for a subset of these features say only for the first 10 features, or for features 20 to 30 in the collection, how do we do it? (Note: If this helps, each polygon has a unique property called ‘poly_id’ for its identification.)

Find value of a nested array dynamically based on a condition

I am working on nested array and try to find a value inside the nested array based on condition. The API returns the data in the format shown below.

data=
  {
    "ch_Id": "1234",
    "title": "Title",
    "status": 4,
    "options": [
      {
        "ch_message": "ABC broad casting ",
        "ch_title": "ABC",
        "referenceType": "Internal"
      }
    ],
    "stage": "active"
  }
]

I am working on loading data dynamically into a div based on a condition. So based on a condition, sometimes the fieldname is ch-Id, and other times it is options[0].ch_message. So, how do I dynamically retrieve the value of fieldname whatever is coming from the input and bind it to the div?

For ch_Id, I can get the value using data[ch_Id], but if I give data[options[0].ch_message], I get undefined.

displayValue: any;

    constructor() { }

    ngOnInit(): void {

    this.fieldName= resultData[fieldName] ;// this can be ch_Id or options[0].ch_message

        // Filter the array value based on fieldName
        const filteredData = Object.entries(this.data).filter(([key, value]) => key === this.fieldName)
        this.displayValue = filteredData[0][1]
        console.log('this.displayValue',this.displayValue);
    }

JS Interop in MAUI Hybrid App on target Android not working with inheritation

I have a Maui App targeting Android and Windows. In this app I use scoped JS files for my custom components. All custom components are inheriting from a base class called ComponentBaseExtended which inherits from ComponentBase. in ComponentBaseExtended i have a method trying to load JS modules for the custom component if existing.

This is my scoped CS (SwipeItem.razor.cs):

            if (swipeDirection == MudBlazor.SwipeDirection.LeftToRight && !_editDrawerOpen)
        {
            // from default to edit
            motionClass = "move-right";
            deleteIconClass = "icon-hidden";
            editIconClass = "icon-visible";
            //await JSRuntime.InvokeVoidAsync("adjustWidthOnSwipeRight", swipeAreaRef, swipeDistance);
            await JSRuntime.InvokeVoidAsync("adjustWidthOnSwipeRight");
        }

This is my scoped JS (SwipeItem.razor.js):

let isModuleLoaded = false;

export function initModule() {
    console.log("initModule - Value of isModuleLoaded:", isModuleLoaded);
    isModuleLoaded = true;
}


export function SwipeRight() {
    console.log("adjustWidthOnSwipeRight - Value of swipeDistance:");
}

export function moduleLoaded() {
    console.log("moduleLoaded - Value of isModuleLoaded:", isModuleLoaded);
    return isModuleLoaded;
}

This is how i load the module and execute its functions (ComponentBaseExtended.razor.cs):

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var type = typeof(TComponent);
        var namespaceParts = type.Namespace?.Split('.') ?? Array.Empty<string>();
        var folderPath = string.Join("/", namespaceParts.Skip(1)); // Skip the root namespace
        var componentName = type.Name;
        var scriptPath = $"./{folderPath}/{componentName}.razor.js";

        try
        {
            // Load the JS module
            var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", scriptPath);
            await module.InvokeVoidAsync("initModule");
            var isLoaded = await module.InvokeAsync<bool>("moduleLoaded");
            if (!isLoaded)
            { }
            else
            {
                await module.InvokeVoidAsync("SwipeRight");
            }
        }
        catch (JSException jsex)enter code here
        {
            // Handle the case where the script doesnt exist
            Console.WriteLine($"No JS module found for {componentName}, or there was an error in loading it.");
        }
    }
}

Well on Android i successfully can load the module, after that i successfully execute methods of this module called initModule, SwipeRight and moduleLoaded. I also see the debug lines in Output.
But SwipeRight method can not be executed from SwipeItem.razor.cs, I get this error:
[chromium] Error: Could not find “adjustWidthOnSwipeRight” (“adjustWidthOnSwipeRight” was undefined).

I guess i am having some issues due to scope of module, which seems to be lost in custom component. How to get rid of this?!

XState: guard for finite number of retries

I have an XState state machine in JavaScript that is pretty simple; it initiates a connection to a server and on FAILURE, tries reconnecting. My objective is to do a finite number of retries (say, 3 times) after which it goes into final state.

I can’t figure out how to achieve this. Any help is appreciated.

From my understanding, if the guard evaluates to TRUE, TARGET is transitioned to. What if the guard evaluates to FALSE? How do I transition to TRIED_ENOUGH_TIMES_DONE?

WAITFORRECONNECT: {
            //activities: ["showingLoadingPanel"],
            entry: (context, event) => {
                console.log("logging re-connect entry call");
                console.log('Retry Count: ' + context.iNumberOfRetries);
            },
            on: {
                DISCONNECTED: { target: 'showingAlert', actions: assign({ errorMessage: (context, event) => event.data }) },                    
                LOGIN_SUCCESS: 'IDLE',

                LOGIN_FAILURE: {
                    
                    actions: assign({ iNumberOfRetries: (context, event) => context.iNumberOfRetries + 1 }),                        
                    target:  'WAITFORRECONNECT',
                    cond: 'isMaxRetriesReached',
                    internal: false

                },
                LOGOUT: {
                    target: 'showingFinalAlert',
                    actions: assign({ errorMessage: (context, event) => event.data })
                },
                CLOSEWINDOW: {
                    target: 'showingFinalAlert',
                    actions: assign({ errorMessage: (context, event) => event.data })
                }
            },
            invoke: {
                src: (context, event) =>
                    connectToServer(
                        context.waitTimeInMilliSeconds,
                        context.sServerAddress,
                        context.sUsername,
                        context.sPassword,
                        context.sPort,
                    ),

                onError: {
                    target: "showingAlert",
                    actions: assign({ errorMessage: (context, event) => event.data })
                }
            },



        },       

    {
        activities: { showingLoadingPanel: createLoadingActivity },
        guards: { 
                isMaxRetriesReached: ({context}) =>
                    {                           
                        return context.iNumberOfRetries <=2;
                    }
            }

   }

Stomp NodeJS Never Start

I have problem with stompJS.I would like to use it with nodeJS and send or subscribe in queue with ActiveMQ.
But when I launch my app I see that stomp is never working..
I using Client from StompJS because the others and oldest library are deprecated.

https://stomp-js.github.io/guide/stompjs/using-stompjs-v5.html

This is my code

"use strict";
const WebSocket = require("ws")
const express = require("express");
const app = express()
const port = 3002;
const {Client} = require('@stomp/stompjs')

Object.assign(global, {WebSocket});
const client = new Client({
    brokerURL: 'ws://localhost:61613/ws',
    connectHeaders:{
        login: 'admin',
        passcode: 'admin',
    },
    onConnect: () => {
        client.publish({ destination: '/queue/test', body: 'First Message' });
        console.log("publish");
    },
});

client.activate();

app.listen(port, () => console.log(`App connected in ${port}`));

And what I received in console enter image description here

And in ActiveMQ Cli after few minutes enter image description here

Thanks for your help 🙂 !

how to get the form data value to payload in next 14

"use client";
import { addCategory } from '@/services/api.method';
import Image from 'next/image';
import React, { FormEvent, useState } from 'react';

const AddNew: React.FC = () => {
    const [title, setTitle] = useState('');
    const [image, setImage] = useState<File | null>(null);

    const handleTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setTitle(event.target.value);
    };

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files && event.target.files.length > 0) {
            const file = event.target.files[0];
            setImage(file);
        }
    };

    const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        let formData = new FormData(event.currentTarget);
        formData.append('title', title);
        if (image) {
            formData.append('image', image, image.name);
        }
        try {
            const res = await addCategory(formData);
            console.log('Response from addCategory:', res);
        } catch (error) {
            console.error('Error adding category:', error);
        }
    };
    

this is above my code I was trying to send the form-data then I always get form-data in payload {}, I have logged the state value then got it, but when I set the from-data to submit the form in payload I’m not able to get any value
kindly help if anyone.

aws sdk v3 lib-storage: upload file of 112 GB crash chrome for out of memory

I have bundled “@aws-sdk/lib-storage” and “@aws-sdk/client-s3” with webpack for use it on frontend

package.json

{
  "name": "aws-s3-upload",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@aws-sdk/client-s3": "^3.499.0",
    "@aws-sdk/lib-storage": "^3.499.0"
  },
  "devDependencies": {
    "path-browserify": "^1.0.1",
    "webpack": "^5.90.0",
    "webpack-cli": "^5.1.4"
  }
}

browser.js

const { S3Client } = require('@aws-sdk/client-s3');
const { Upload } = require("@aws-sdk/lib-storage");
window.AWS = {S3Client, Upload}
export {S3Client, Upload};

webpack.config.js

// Import path for resolving file paths
var path = require("path");
module.exports = {
  mode: 'production',
  performance: {
    hints: false
  },
  // Specify the entry point for our app.
  entry: [path.join(__dirname, "browser.js")],
  // Specify the output file containing our bundled code.
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  // Enable WebPack to use the 'path' package.
  resolve: {
    fallback: { path: require.resolve("path-browserify") }
  }
  /**
  * In Webpack version v2.0.0 and earlier, you must tell 
  * webpack how to use "json-loader" to load 'json' files.
  * To do this Enter 'npm --save-dev install json-loader' at the 
  * command line to install the "json-loader' package, and include the 
  * following entry in your webpack.config.js.
  * module: {
    rules: [{test: /.json$/, use: use: "json-loader"}]
  }
  **/
};

Build produce bundle.js

npm run buid

usage

index.html

 <script src="bundle.js"></script>
 <script>
  const s3Client = new AWS.S3Client({
    region:  ...,
    endpoint:  ...,
    credentials: {
          accessKeyId: ...,
          secretAccessKey:  ...,
          sessionToken:  ...,
     }
   });
   const uploadParams = {
     Bucket: ...,
     Key: ...,
     Body: file // file from <input type="file">
   };
  const upload = new AWS.Upload({
    client: s3Client ,
    params: uploadParams,
    queueSize: 4, // optional concurrency configuration
    partSize: 1024 * 1024 * 5, // optional size of each part
    leavePartsOnError: false, // optional manually handle dropped parts
  });

  upload .on("httpUploadProgress", (progress) => {
    console.log(progress);
  });
  await upload.done();
</script>

If upload a file of 112 GB, after 25 GB chrome crash for out of memory.

AngularJS – Handling Interval Persistence and Restart After Browser Reload

Technology: AngularJs
Requirement: Call an API at a regular interval. The API will return tokens, which I’ve got to store in local storage.
To achieve this, I created a service called “refreshTokenService.js.” I am starting the interval after a successful login. The code works properly until the browser is reloaded.

Problem: Once the browser is reloaded, the angular services get reset, and the interval is stopped. Hence, the refreshTokenService code won’t execute.

Steps I followed.

  1. From the login controller, after successful login, I’m emitting “isUserLoggedIn” which is received in mainCtroller.js to start the interval. 
    mainCtroller.js Code: 
    $rootScope.$on('isUserLoggedIn', function(){
                if($localStorage.token)
                    refreshService.startInterval();
            });    
 
    $rootScope.$on('refreshTokenStop', function(){
                    refreshService.stopInterval();
                });

refreshService.js Code:

(function () {
    'use strict'
    app.service('refreshService', refreshServiceFunction);
    refreshServiceFunction.$inject = ['$rootScope','$http','$interval','$localStorage'];

    function refreshServiceFunction($rootScope,$http,$interval,$localStorage) {
        var tokenTime = 1000 * 60 * 1 ;
        var intervalStatus;
        
        function getRefreshToken(){
            console.log("Get Refresh Token Service Call ",new Date());
                $http({
                    method: 'GET',
                    url: $rootScope.ctx + '/api/auth/refresh-token'
                }).then(function (response) {
                    
                    if(response.data.statusCode === 'Success'){
                        console.log("New Token generated ",new Date());
                        $localStorage.lastRefreshTime = new Date();
                        $localStorage.token = response.data.data;
                        $http.defaults.headers.common.Authorization = 'Bearer ' + response.data.data;
                    }else{
                        console.log("New Token generation failed ", response.data.message,new Date());
                    }       
                    
                }).catch(function (error) {
                    console.log("Error while Refresh Token call at time ",error,new Date());
                }); 
        }
            
        function startInterval() {
            intervalStatus = $interval(getRefreshToken, tokenTime );
        }
       function stopInterval() {
            if (intervalStatus) {
                $interval.cancel(intervalStatus);
            }
        }
        
        return {
            startInterval: startInterval,
            stopInterval: stopInterval
        };
    }
})();

To fix the issue of reloading the browser, I thought to reactivate the interval by calling it again once the browser is refreshed.
I choose to use ‘$stateChangeStart’ as it is invoked every time, as shown in the below code:
main.js

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
        if($localStorage.token){
            refreshService.startInterval();
        }
}

But there is a problem: the ‘$stateChangeStart’ is invoked even while navigating the menu. So I can’t know whether it is browser reload or just navigation (I don’t want to do anything while navigation). Once browser reload is complete then activate the interval, calculate the remaning time if needed to trigger the API call.

I need a solution or any better approach to achieve the same.

Any help and guidance will be useful to me. Thanks in Advance.

How can I insert data in the MySql database

I have a data insertion form, but when I insert the information I get these errors:

PHP error encountered

Severity: 8192

Message: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated

File: helpers/form_helper.php

Numéro de la ligne: 647

This error indicates that this field is empty when this is not the case.

When I fill out this field again, this time it is this message that appears.

Fatal error: Uncaught Error: Call to a member function row() on string in C:xampphtdocshopitalapplicationmodulespatientcontrollerspatient.php:361 Stack trace: #0 C:xampphtdocshopitalsystemcoreCodeIgniter.php(360): Patient->addNew() #1 C:xampphtdocshopitalindex.php(208): require_once(‘C:xampphtdocs…’) #2 {main} thrown in C:xampphtdocshopitalapplicationmodulespatientcontrollerspatient.php on line 361.

here is the code of the form in the view class

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">
     <div class="modal-content">
      <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-plus-circle"></i> <?php echo lang('register_new_patient'); ?></h4>
     </div>
   <div class="modal-body">
<form role="form" action="patient/addNew" method="post" enctype="multipart/form-data">
  <div class="form-group">
   <div class="col-md-12">     
    <div class="col-md-3"></div>
  <div class="col-md-6"> 
<div class="col-md-3 payment_label"> 
<label for="exampleInputEmail1"><?php echo lang('doctor'); ?></label>
</div>
<div class="col-md-9"> 
<select class="form-control m-bot15 js-example-basic-multiple" multiple="" name="doctor[]" value=''> 
 <option value=""> </option>
  <?php foreach ($doctors as $doctor) { ?>                                        
   <option value="<?php echo $doctor->id; ?>"><?php echo $doctor->name; ?> </option>
  <?php } ?> 
</select>
</div>
</div>
<div class="col-md-3"></div>
</div>
 </div>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo lang('name'); ?></label>
<input type="text" class="form-control" name="name" id="exampleInputEmail1" value='' placeholder="">
 </div>
<div class="form-group">
 <label for="exampleInputEmail1"><?php echo lang('password'); ?></label>
 <input type="password" class="form-control" name="password" id="exampleInputEmail1" placeholder="">
</div>
<div class="form-group">
 <label for="exampleInputEmail1"><?php echo lang('email'); ?></label>
 <input type="text" class="form-control" name="email" id="exampleInputEmail1" value='' placeholder="">
</div>
<div class="form-group col-md-6 cat-container" data-id="Femme">
<label for="exampleInputEmail1"><?php echo lang('name_husband'); ?></label>
<input type="text" class="form-control" name="name_Us" id="nameUs" placeholder="">
<label for="exampleInputEmail1"><?php echo lang('number_pregnancy'); ?></label>
<input type="number" class="form-control" name="number_pregnancy" id="nbreEnfants" placeholder="">
</div>

<div class="form-group">
  <label for="exampleInputEmail1"><?php echo lang('address'); ?></label>
    <input type="text" class="form-control" name="address" id="exampleInputEmail1" value='' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="exampleInputEmail1"><?php echo lang('andtecedentMed'); ?></label>
 <input type="text" class="form-control" name="AntecedentMed" id="exampleInputEmail1" value='' placeholder="">
</div>

<div class="form-group col-md-6">
  <label for="exampleInputEmail1"><?php echo lang('andtecedentFam'); ?></label>
   <input type="text" class="form-control" name="AntecedentFam" id="exampleInputEmail1" value='' placeholder="">
</div>

<div class="form-group col-md-6">
 <label for="exampleInputEmail1"><?php echo lang('taille'); ?></label>
  <input type="text" class="form-control" name="taille" id="exampleInputEmail1" value='' placeholder="">
</div>

                    <div class="form-group col-md-6">
                        <label for="exampleInputEmail1"><?php echo lang('poids'); ?></label>
                        <input type="text" class="form-control" name="poids" id="exampleInputEmail1" value='' placeholder="">
                    </div>

                    <div class="form-group">
                        <label for="exampleInputEmail1"><?php echo lang('phone'); ?></label>
                        <input type="text" class="form-control" name="phone" id="exampleInputEmail1" value='' placeholder="">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1"><?php echo lang('sex'); ?></label>
                        <select class="form-control m-bot15" name="sex" value=''>

                            <option value="Masculin" <?php
                            if (!empty($patient->sex)) {
                                if ($patient->sex == 'Masculin') {
                                    echo 'selected';
                                }
                            }
                            ?> > Masculin </option>
                            <option value="Féminin" <?php
                            if (!empty($patient->sex)) {
                                if ($patient->sex == 'Féminin') {
                                    echo 'selected';
                                }
                            }
                            ?> > Féminin </option>
                            <option value="Autres" <?php
                            if (!empty($patient->sex)) {
                                if ($patient->sex == 'Autres') {
                                    echo 'selected';
                                }
                            }
                            ?> > Autres </option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label><?php echo lang('birth_date'); ?></label>
                        <input class="form-control form-control-inline input-medium default-date-picker" type="text" name="birthdate" value="" placeholder="">      
                    </div>


                    <div class="form-group">
                        <label for="exampleInputEmail1"><?php echo lang('blood_group'); ?></label>
                        <select class="form-control m-bot15" name="bloodgroup" value=''>
                            <?php foreach ($groups as $group) { ?>
                                <option value="<?php echo $group->group; ?>" <?php
                                if (!empty($patient->bloodgroup)) {
                                    if ($group->group == $patient->bloodgroup) {
                                        echo 'selected';
                                    }
                                }
                                ?> > <?php echo $group->group; ?> </option>
                                    <?php } ?> 
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="exampleInputEmail1"><?php echo lang('image'); ?></label>
                        <input type="file" name="img_url">
                    </div>

                    <input type="hidden" name="id" value=''>
                    <input type="hidden" name="p_id" value='<?php
                    if (!empty($patient->patient_id)) {
                        echo $patient->patient_id;
                    }
                    ?>'>
                    <section class="">
                        <button type="submit" name="submit" class="btn btn-info"><?php echo lang('submit'); ?></button>
                    </section>
                </form>

            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

Here is the controller code:

public function addNew() {
        $id = $this->input->post('id');
        $name = $this->input->post('name');
        $password = $this->input->post('password');
        $name_husband = $this->input->post('name_husband');
        $number_pregnancy = $this->input->post('nbreEnfants');
        $email = $this->input->post('email');
        $doctor = $this->input->post('doctor');
        $address = $this->input->post('address');
         $antecedentMed = $this->input->post('antecedentMed');
        $antecedentFam = $this->input->post('antecedentFam');
        $taille = $this->input->post('taille');
        $poids = $this->input->post('poids');
        $phone = $this->input->post('phone');
        $sex = $this->input->post('sex');
        $birthdate = $this->input->post('birthdate');
        $bloodgroup = $this->input->post('bloodgroup');
        $patient_id = $this->input->post('p_id');
        if (empty($patient_id)) {
            $patient_id = rand(10000, 1000000);
        }
        if ((empty($id))) {
            $add_date = date('d/m/y');
        } else {
            $add_date = $this->db->get_where('patient', array('id' => $id))->row()->add_date;
        }

        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        
         // Validating Catégory Field
        $this->form_validation->set_rules('category', 'Category', 'trim|min_length[2]|max_length[100]|xss_clean');
        // Validating Name Field
        $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[2]|max_length[100]|xss_clean');
        // Validating Password Field
        if (empty($id)) {
            $this->form_validation->set_rules('password', 'Password', 'trim|min_length[5]|max_length[100]|xss_clean');
        }
          // Validating husband_name Field
        if (empty($id)) {
            $this->form_validation->set_rules('name_husband', 'Name_husband', 'trim|min_length[3]|max_length[100]|xss_clean');
        }
        // Validating number_enfants Field
        if (empty($id)) {
            $this->form_validation->set_rules('number_pregnancy', 'Number_pregnancy', 'trim|min_length[1]|max_length[100]|xss_clean');
        }
        // Validating Email Field
        $this->form_validation->set_rules('email', 'Email', 'trim|min_length[5]|max_length[100]|xss_clean');
        // Validating Doctor Field
        $this->form_validation->set_rules('doctor', 'Doctor', 'trim|min_length[2]|max_length[100]|xss_clean');
         // Validating antécédents médicaux Field     
        $this->form_validation->set_rules('antecedentMed', 'AntecedentM', 'trim|required|min_length[2]|max_length[500]|xss_clean');
        // Validating antécédents familiaux Field     
        $this->form_validation->set_rules('antecedentFam', 'AntecedentF', 'trim|required|min_length[2]|max_length[500]|xss_clean');
        // Validating taille Field     
        $this->form_validation->set_rules('taille', 'Taille', 'trim|required|min_length[4]|max_length[500]|xss_clean');
        // Validating poids Field     
        $this->form_validation->set_rules('poids', 'Poids', 'trim|required|min_length[2]|max_length[500]|xss_clean');
        // Validating Address Field   
        $this->form_validation->set_rules('address', 'Address', 'trim|required|min_length[2]|max_length[500]|xss_clean');
        // Validating Phone Field           
        $this->form_validation->set_rules('phone', 'Phone', 'trim|required|min_length[2]|max_length[50]|xss_clean');
        // Validating Email Field
        $this->form_validation->set_rules('sex', 'Sex', 'trim|required|min_length[2]|max_length[100]|xss_clean');
        // Validating Address Field   
        $this->form_validation->set_rules('birthdate', 'Birth Date', 'trim|min_length[2]|max_length[500]|xss_clean');
        // Validating Phone Field           
        $this->form_validation->set_rules('bloodgroup', 'Blood Group', 'trim|min_length[1]|max_length[10]|xss_clean');


        if ($this->form_validation->run() == FALSE) {
            if (!empty($id)) {
                redirect("patient/editPatient?id=$id");
            } else {
                $data = array();
                $data['doctors'] = $this->doctor_model->getDoctor();
                $data['groups'] = $this->donor_model->getBloodBank();
                $data['settings'] = $this->settings_model->getSettings();
                $this->load->view('home/dashboard', $data); // just the header file
                $this->load->view('add_new', $data);
                $this->load->view('home/footer'); // just the header file
            }
        } else {
            $file_name = $_FILES['img_url']['name'];
            $file_name_pieces = explode('_', $file_name);
            $new_file_name = '';
            $count = 1;
            foreach ($file_name_pieces as $piece) {
                if ($count !== 1) {
                    $piece = ucfirst($piece);
                }

                $new_file_name .= $piece;
                $count++;
            }
            $config = array(
                'file_name' => $new_file_name,
                'upload_path' => "./uploads/",
                'allowed_types' => "gif|jpg|png|jpeg|pdf",
                'overwrite' => False,
                'max_size' => "20480000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
                'max_height' => "1768",
                'max_width' => "2024"
            );

            $this->load->library('Upload', $config);
            $this->upload->initialize($config);

            if ($this->upload->do_upload('img_url')) {
                $path = $this->upload->data();
                $img_url = "uploads/" . $path['file_name'];
                $data = array();
                $data = array(
                    'patient_id' => $patient_id,
                    'img_url' => $img_url,
                    'category' => $category,
                    'name' => $name,
                    'email' => $email,
                    'address' => $address,
                    'antecedentMed' => $antecedentMed,
                    'antecedentFam' => $antecedentFam,
                    'doctor' => $doctor,
                    'phone' => $phone,
                    'sex' => $sex,
                    'birthdate' => $birthdate,
                    'bloodgroup' => $bloodgroup,
                    'add_date' => $add_date
                );
            } else {
                //$error = array('error' => $this->upload->display_errors());
                $data = array();
                $data = array(
                    'patient_id' => $patient_id,
                    'category' => $category,
                    'name' => $name,
                    'email' => $email,
                    'doctor' => $doctor,
                    'address' => $address,
                     'antecedentMed' => $antecedentMed,
                    'antecedentFam' => $antecedentFam,
                    'phone' => $phone,
                    'sex' => $sex,
                    'birthdate' => $birthdate,
                    'bloodgroup' => $bloodgroup,
                    'add_date' => $add_date
                );
            }

            $username = $this->input->post('name');

            if (empty($id)) {     // Adding New Patient
                if ($this->ion_auth->email_check($email)) {
                    $this->session->set_flashdata('feedback', 'Cette adresse email est déjà enregistré dans la base données');
                    redirect('patient/addNewView');
                } else {
                    $dfg = 5;
                    $this->ion_auth->register($username, $password, $email, $dfg);
                    $user_id = $this->db->insert_id();
                    $ion_user_id = $this->db->get_where('users_groups', array('id' => $user_id))->row()->user_id;
                    $this->patient_model->insertPatient($data);
                    $patient_user_id = $this->db->insert_id();
                    $id_info = array('ion_user_id' => $ion_user_id);
                    $this->patient_model->updatePatient($patient_user_id, $id_info);
                    $this->session->set_flashdata('feedback', 'Ajouté');
                }
            } else { // Updating Patient
                $ion_user_id = $this->db->get_where('patient', array('id' => $id))->row()->ion_user_id;
                if (empty($password)) {
                    $password = $this->db->get_where('users', array('id' => $ion_user_id))->row()->password;
                } else {
                    $password = $this->ion_auth_model->hash_password($password);
                }
                $this->patient_model->updateIonUser($username, $email, $password, $ion_user_id);
                $this->patient_model->updatePatient($id, $data);
                $this->session->set_flashdata('feedback', 'Modifié');
            }
            // Loading View
            redirect('patient');
        }
    }

Finally, here is the model code:

class Patient_model extends CI_model {
 function insertPatient($data) {
        $data1 = array('hospital_id' => $this->session->userdata('hospital_id'));
        $data2 = array_merge($data, $data1);
        $this->db->insert('patient', $data2);
    }
}

And this is the Line 361 wich is indicated as containing the error:

 $ion_user_id = $ion_user_id->row()->id;

Would using createElement instead of template literals prevent XSS?

My messenger application is rendering each dialog using a template literal. This is causing unwanted behavior such as the last_message displaying links, images, or even executing scripts instead of just showing plain text. My messenger should only supports text messaging so users are unable to send images, voice attachments, etc.

Example incoming message:

var app = document.querySelector('body'); app.innerHTML = '<img src="x" onerror="alert(1)">';

  renderDialogs: () => {
    const dialogList = document.getElementById('dialogsList');
    dialogList.textContent = '';

    const df = document.createDocumentFragment();

    dialogs.list.forEach(
      ({
        id,
        created,
        modified,
        username,
        other_user_id,
        unread_count,
        last_message,
      }) => {
        const btn = document.createElement('button');
        btn.classList =
          'list-group-item list-group-item-action list-group-item';
        btn.dataset.username = username;
        btn.dataset.userId = other_user_id;

        const btnContent = `
        <div class="d-flex flex-column gap-1 disable-pointer-events">
          <h5 class="mb-0 fs-6">${username}</h5>
          <p class="mb-0 text-muted preview-text">${last_message.text}</p>
          <p class="mb-0 dialog-unread"><span class="dialog-unread-count">${unread_count}</span> unread messages</p>
        </div>
      `;

        btn.insertAdjacentHTML('beforeend', btnContent);
        df.appendChild(btn);
      },
    );
    dialogList.appendChild(df);
  },

Would converting the following to use createElement prevent this mess? I used to use python bleach package to sanitize text in the backend, but it’s now deprecated.