javascript: summernote: passing a parameter when dynamically adding buttons

I am creating dynamical custom buttons for my summernote wysiwygs, but i’m running into a problem. I want to pass the data i’m iterating through to the button’s render function, but since it is already being passed the context as a parameter, I’m a bit clueless here.

Here’s the relevant code:

var formButtons = {};
var formButtonIds = [];
if(FormsModule.currentForm) {
    for(var i=0; i<FormsModule.currentForm.fields.length; i++) {
        var field = FormsModule.currentForm.fields[i];
        var fieldId = 'button_' + i;
        formButtons[fieldId] = (function (context) {
            console.log(context);
            console.log(field);
            var ui = $.summernote.ui;
            var tooltip = 'Insert ' + field.title;
            // create button
            var button = ui.button({
                contents: HelperModule.getTitle(field.title),
                tooltip: tooltip,
                click: function () {
                    context.invoke("editor.insertText", '<span clas="field-input-button">#' + field.title + '#</span>');
                },
            });

            return button.render();
        });
        formButtonIds.push(fieldId);
    }
} 
$("#form-modal #form-form .wysiwyg").each(function(index, wysiwyg) {
    var content = $(wysiwyg).summernote('code');
    $(wysiwyg).summernote('destroy');
    $(wysiwyg).summernote({
        buttons: formButtons,
        toolbar: [
            ["style", ["style"]],
            ['font', ['bold', 'underline', 'clear']],
            //['fontname', ['fontname']],
            ["color", ["color"]],
            ["para", ["ul", "ol", "paragraph"]],
            ["mybutton", formButtonIds],
            ["table", ["table"]],
            ["insert", ["link"]],
            ["view", ["codeview"]],
        ],
    });
    $(wysiwyg).summernote('code', content);
})

If I try and pass the field to the formButtons[x] function, it (replaces the context’s value):

    formButtons[fieldId] = (function (context) {
        console.log(context);
        console.log(field);
        var ui = $.summernote.ui;
        var tooltip = 'Insert ' + field.title;
        // create button
        var button = ui.button({
            contents: HelperModule.getTitle(field.title),
            tooltip: tooltip,
            click: function () {
                context.invoke("editor.insertText", '<span clas="field-input-button">#' + field.title + '#</span>');
            },
        });

        return button.render();
    })(field); 

The console.log of both field and context are the field value

how to save infromation while video editing at online tool? in the web ask me to refresh

I need to save my information I made video. but the webstied working not and stopped and ask me click refresh. I feel if I click the refresh button, there would be lick of informatmion by being not saved. I wish it is stroed automatically in a web databse. for example copying the data after clicking F12 Image Im working and error

I made a new tap but it also ask me close the tabp because other working tab is on. I expect to know how I store and save my wroking history certainly in this situation.

ReactJS – Firebase push notification not working in firefox browser

Inconsistent Click Behavior:

Sometimes, when a user clicks on a notification, nothing happens.
On other occasions, the redirection after clicking the notification is not proper.

Multiple Notifications for Single Action:

When clicking on the browser’s notification (not ours), multiple notifications are triggered for a single action.

Is there any solution to solve this in firefox browser.

AJAX – insert data in mysql

The code below displays a message after typing a value into the field

Poprawnie zapisano: - but without this value

Also does not write anything to the database. Did I make a mistake somewhere?

HTML file

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

        <input type="text" id="wartosc" placeholder="Wartość do zapisania">
        <button id="zapiszBtn">Zapisz do bazy danych</button>


        <script>
            $(document).ready(function(){
                $("#zapiszBtn").click(function(){
                    var wartosc = $("#wartosc").val();
                    $.ajax({
                        url: "zapisz.php",
                        type: "POST",
                        data: wartosc,
                        success: function(wartosc){
                            alert("Poprawnie zapisano: " + wartosc);
                        }
                    });
                });
            });
        </script>
</body>

ZAPISZ.php

<?php

$sname= "localhost";
$unmae= "root";
$password = "root";

$db_name = "vote2";

$conn = mysqli_connect($sname, $unmae, $password, $db_name);

if (!$conn) {
    echo "Połączenie się nie powiodło!";
}

// Uzyskanie wartości z AJAX
if(isset($_POST['wartosc'])){

    $wartosc = $_POST['wartosc'];

    // Wstawienie wartości do bazy danych
    $stmt = $pdo->prepare("INSERT INTO 'test' ('r1') VALUES ('$wartosc')");
    $result = mysql_query($stmt);


    if($result) {
        echo "Wartość została pomyślnie zapisana do bazy danych.";
        } else {
            echo "Wystąpił błąd podczas zapisywania wartości do bazy danych.";
        }
}

?>

I would like the value I enter in the field to be saved in the database

Pixi JS image render issue

I am using Pixi 8.1.0 and am having issue with rendering the image. I have no issues with drawing rectangles or circles, only with images it does not render. I am using a try catch block below.

try { Assets.add('bg', 'bg-10001.png'); const textures = await Assets.load('bg'); app.stage.addChild(textures); } catch (e) { console.log(e); }

The error is logged out: TypeError: Cannot read properties of undefined (reading 'startsWith') at checkDataUrl (checkDataUrl.mjs:9:15) at Object.test (loadTextures.mjs:54:81) at eval (Resolver.mjs:329:26) at Array.forEach (<anonymous>) at eval (Resolver.mjs:323:14) at Array.forEach (<anonymous>) at eval (Resolver.mjs:322:17) at Array.forEach (<anonymous>) at Resolver.add (Resolver.mjs:310:16) at AssetsClass.add (Assets.mjs:152:19)

Any help will be appreciated. I do not wish to roll back to previous versions of Pixi and the image path is correct. Have also tried deleting node_modules and package.lock.json and reinstalling again but still no success.

I do not wish to roll back to previous versions of Pixi and the image path is correct. Have also tried deleting node_modules and package.lock.json and reinstalling again but still no success. Also tried with other images, both jpeg and png and still not successful.

Vue JS: async function returns Promise Object

I’m newbee in JS, and i have a problem. There is a object with a shift in the camp.I need to redo his name to “name (shift occupancy)” format. I wrote a function that collects shift data, calculates it, and returns the name. But it doesn’t work

func

const sessionName = async (payload) => {
  const orgId = form.value.findFieldByFieldId('organization').value;
  const session = await getSessions(orgId, payload);
  console.log(JSON.stringify(session.data.data));
  const data = Object.values(session.data.data);
  for (let i = 0; i < data.length; i++) {
    const name = data[i].children_capacity > data[i].children_register ?
      `${data[i].name} (${data[i].children_capacity - data[i].children_register} places)`
      : `${data[i].name} (out of places)`;
    console.log(name);
    return name;
  }

json response from await getSessions

[{"id":3277,"price":500,"date_start":"2025-05-29","date_end":"2025-06-29","name":"1st shift","theme":"Physical education ","children_capacity":30,"children_register":0,"is_active":true,"organization":1148,"organization_name":"Hawk"]

form input (there is autocomplete vue js element)

{
        type: 'autocomplete',
        fieldId: 'session',
        value: null,
        label: 'Session choice',
        items: [],
        methods: getSessions,
        rules: [...requiredRules],
        itemTitle: sessionName,
        itemValue: 'id',
        multiple: false,
        idParam: 'organization',
        triggerFields: [
      
          { fieldId: 'organization', isExist: true },
        ],
      },

I tried using await and then in the form, but this does not give a result, and returns either an Object Object that cannot be converted, or throws an error.
The required values are output to the console, but the return value is Promise. Perhaps there is some way to fill in without getting the return value?

Service Worker cache – able to put but not able to retrieve

I created a Service Worker that caches the results of nearmap and metromap tiles for a longer period of time. See below code.

const version = 10;
const CACHE_NAME = `mapbox-tiles-nearmap-${version}`;
const periodForTiles = (1000 * 60 * 60 * 24 * 356) / 2; // half year
const listResorcesForCache = ['api.nearmap.com/tiles', 'api-v3.metromap.com.au/tiles'];

self.addEventListener('fetch', event => {
    if (isCachedResource(event.request.url)) {
        event.respondWith(fromCacheOrNetwork(event.request));
    } else {
        event.respondWith(fromNetwork(event.request));
    }
});

async function fromCacheOrNetwork(request) {
    const cache = await caches.open(CACHE_NAME);
    const response = await cache.match(request, {ignoreVary: true});

    console.log('test', {cache, response});
    // @todo: this is where the issue is, the response is always undefined

    return isFresh(response) ? response : fromNetwork(request);
}
function fromNetwork(request) {
    return fetch(request.clone())
        .then(function (response) {
            if (isCachedResource(request.url) && response.status < 300) {
                cachePut(request, response);
            }
            return response;
        })
        .catch(function (error) {
            // This catch() will handle exceptions that arise from the match() or fetch() operations.
            // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
            // It will return a normal response object that has the appropriate error code set.
            console.error('  Error in fetch handler:', error);
            throw error;
        });
}
async function cachePut(request, response) {
    const options = {
        status: response.status,
        statusText: response.statusText,
        headers: new Headers(),
    };
    response.headers.forEach((v, k) => options.headers.set(k, v));
    options.headers.set(
        'Expires',
        new Date(Date.now() + periodForTiles).toUTCString()
    );
    const clonedResponse = response.clone();

    const cache = await caches.open(CACHE_NAME);
    cache.put(request, new Response(clonedResponse.body, options));
}
function isFresh(response) {
    if (!response) return false;

    const expires = new Date(response.headers.get('Expires'));
    return expires > Date.now();
}

function isCachedResource(url) {
    return (
        undefined !==
        listResorcesForCache.find(item => {
            return url.includes(item);
        })
    );
}

Currently, the code is able to intercept the fetch requests from nearmap and metrop and store the result to Cache Storage. However, when I to fetch from cache, it is always returning “undefined” based on the result returned from cache.match(). Any idea why it’s able to store but not able to retrieve?

I have tried adding ignoreVary option on the cache.match() function but it still returned undefined.

React Route Configuration: Component Not Rendering Despite Correct URL Update

I’m encountering a problem where the SearchResults component in my React application is not rendering as expected. Despite configuring the route correctly and verifying that the URL updates appropriately, the component fails to render. I’ve checked the console logs and network requests, but there are no errors reported.

This code was suppose to display the fetched results. But the URL is getting updated according to query made but the results are not.

import React, { useState, useEffect } from "react";
import axios from "axios";
import Layout from "../../components/Layout/Layout";
import { useLocation } from "react-router-dom";
import { useParams } from "react-router-dom";

const SearchResults = () => {
  console.log("Component rendered");
  const [doctors, setDoctors] = useState([]);
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const specialization = searchParams.get("q");

  // Check specialization value received from URL
  console.log("Specialization before rendering:", specialization);

  useEffect(() => {
    // Log specialization value within useEffect
    console.log("useEffect hook triggered");

    const fetchDoctors = async () => {
      try {
        const response = await axios.get(
          `/api/v1/fetch/searchQuery/${specialization}`
        );
        setDoctors(response.data);
      } catch (error) {
        console.error("Error fetching doctors:", error);
      }
    };

    if (specialization) {
      fetchDoctors();
    }
  }, [specialization]); // Ensure specialization is included in dependency array

  // Log when component is rendered
  console.log("SearchResults component rendered");
  console.log("SearchResults component rendered");
  // Inside the SearchResults component
  return (
    <Layout title="Search Results">
      <div>
        <h4>Doctor Details</h4>
        <div className="table-container">
          <table className="table">{/* Table headers */}</table>
        </div>
      </div>
      <p>SearchResults Component Rendered</p>
    </Layout>
  );
};

export default SearchResults;

Facing an issue in the NPM

I was trying to build a leetcode clone but I am continuously encountering a problem as when i try to run
npm run build I get a error saying “missing script build ” ,even though that script is already present in package.json ,Moreover when I try to use npm run to check for scripts i get nothing Anyone knows the solution for this problem SS of the package and the error I am facing

I tried running npm run build inorder to check whether my code is working and building the app or not
The result was constant error ,continuous failure from backend while opening localhost

animate not works in mini ipad and mobile

$(".section-form .form-wrap").hide();
$(".thank-you-content-wrap").show();
var $sectionForm = $('.section-form');
var stickyHeaderHeight = 85;
var offset = $sectionForm.offset().top - stickyHeaderHeight;
console.log('offset', offset);
setTimeout(() => {
  if ($sectionForm.length > 0) {
    var stickyHeaderHeight = 85;
    var offset = $sectionForm.offset().top - stickyHeaderHeight;
    console.log('offset', offset);
    $('html, body').animate({
      scrollTop: offset
    }, 'slow');
  }
}, 1100);

The animate behaves differently for mini iPad (below 1023px) and mobile why?
Work on all devices with the same behaviour

Implement a Concurrent Binary Search Tree

Problem Description:

You are required to implement a concurrent binary search tree (BST) in Node.js. The concurrent BST should support multiple concurrent read and write operations without compromising data consistency. Specifically, you need to implement the following functionalities:

Insertion Operation: Implement a method to insert a new node into the BST while maintaining the binary search tree property.

Deletion Operation: Implement a method to delete a node from the BST while preserving the binary search tree property.

Search Operation: Implement a method to search for a given key in the BST.

Concurrent Access: Ensure that multiple read operations (searching) can be performed concurrently without conflicting with write operations (insertion and deletion).

Data Consistency: Ensure that concurrent operations do not result in data inconsistency, such as race conditions or corrupted tree structure.

Expecting good logic and DSA!

how to add Poll in Quill Editor

I’m building a chat Application in that chat app I also need to add a Poll I want whenever a user presses (‘/’) in the editor, poll popper should open, after selecting the poll from the popper, we need to type question, and objective in the editor, I m little bit getting answer but I need a perfect solution.

Making Quill Editor Poll, in the Quill editor pressing (‘/’) how to Implement Poll. I am building a chat application that requires a poll feature. I want the poll pop-up to appear when the user presses the forward slash (‘/’) key in the editor. Once the user selects the poll from the pop-up, they should be able to type their question and objective in the editor. Although I have found some solutions, I am still looking for the perfect solution to implement a poll feature in the Quill editor.

How to handle data persistence with local storage when the data structure changes?

I’m building a web application that uses local storage to store user data and application state. However, I’m facing an issue when the structure of the data changes between versions of the application.

For example, let’s say I initially stored an array of user objects in local storage, with each user object having properties like name, age, and email. In the next version of the application, I need to add a new property address to the user objects.

The problem is that when the application loads, it tries to parse the data from local storage using the new data structure, which causes an error because the existing data in local storage doesn’t have the address property.

Here’s a simplified example of the code:

// Initial data structure
const initialUsers = [
  { name: 'John', age: 30, email: '[email protected]' },
  { name: 'Jane', age: 25, email: '[email protected]' }
];

// Save initial data to local storage
localStorage.setItem('users', JSON.stringify(initialUsers));

// Later, when the app loads with the new data structure
const storedUsers = JSON.parse(localStorage.getItem('users'));
// Error: storedUsers[0].address is undefined

// New data structure with the added 'address' property
const newUsers = [
  { name: 'John', age: 30, email: '[email protected]', address: '123 Main St' },
  { name: 'Jane', age: 25, email: '[email protected]', address: '456 Oak Ave' }
];

I’ve tried various approaches, such as checking for the existence of the new property before accessing it, but I haven’t found a satisfactory solution that handles all edge cases.

What is the best practice for handling data persistence with local storage when the data structure changes between versions of the application? How can I ensure that the application can gracefully handle data migration and avoid errors or data loss?