Need to clic twice to get language to change

I am developing a simple landing page where you can choose the language of the text displayed.

This is my code:

<?php
$defaultLang = isset($_COOKIE['lang_bcn']) ? $_COOKIE['lang_bcn'] : 'es'; //default 
if(isset($_GET['selectedLanguage'])){
    $languageOption = "";
    switch($_GET['selectedLanguage']){
        case 'en':
        $languageOption = 'en';
        break;
        case 'es':
        $languageOption = 'es';
        break;
        default:
        break;
    }
    if(isset($languageOption)){
        setcookie('lang_bcn',$languageOption,time()+24*7*60*60);//set cookie to expire in 7 days
    }
}

$arrayLang['en']['subtitle'] = 'Discover and learn by playing';
$arrayLang['es']['subtitle'] = 'Descubre y aprende jugando';
?>

//links to language selection
     <a href="?selectedLanguage=es">ES</a>
     <a href="?selectedLanguage=en">EN</a>

//showing the text in the selected language
      <p><?php echo $arrayLang[$defaultLang]['subtitle'];?></p>

And it works great, except that to change the language I have to click twice on the chosen language link. With just one click the language of the text doesn’t change and I can’t find the reason why.

Can someone help me?

Thank you!

Javascript scrollTo

 function scroll_move(obj) {
      const __target = document.getElementsByClassName(obj);
      const offsetT = __target[0].offsetTop;
      window.scrollTo({ top: offsetT, left: 0, behavior: "smooth" });
    }
[class^="box"] {
      height: 950px;
      width: 300px;
      border: solid;
      display: block;
    }
<div>
      <a href="#;" class="box1" onclick="scroll_move('box5');">11</a>
      <a href="#;" class="box2">22</a>
      <a href="javascript:void(0)" class="box3" onclick="scroll_move('box1');"
        >33</a
      >
      <a href="javascript:void(0)" class="box4" onclick="scroll_move('box2');"
        >44</a
      >
      <a href="#;" class="box5">55</a>
   </div>

If you save it to a vscode and run it, it doesn’t work properly
It works fine on the codepdn, but I don’t know why

React Suspense within a Context

Those days I had to solve a problem for my react app, I have all my data to be displayed in JSONs, those are served by an express API using FS of node in order to read those JSONs and return them depending on the path you’re passing in.

The real problem came when I tried to render my components, the components are useless without that JSON information, so I’ll have to always wait till I get those.

My first idea was to call the API synchronously with XMLHttpRequest but I saw in the docs that it is deprecated. So I read about the new features of Suspense and Transitions but I do not understand it as well as placing them into my DataContext. I’ll share with you all code I think is relevant in order to let you see where I reached:

// jsonLoader.js
// Here I try to get the data with XMLHttpRequest, I replaced to sync to async

export const loadJSON = async (path) => {
    const json = await readFile(path, 'application/json');
    return json ? JSON.parse(json) : undefined;
};

const readFile = async (path, mimeType) =>
    new Promise((resolve) => {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open('GET', path, true);
        if (!!mimeType && xmlHttp.overrideMimeType) xmlHttp.overrideMimeType(mimeType);
        xmlHttp.send();
        if (xmlHttp.status == 200 && xmlHttp.readyState == 4) resolve(xmlHttp.responseText);
        else return resolve(undefined);
    });

Then I use that module in my DataContext:

// DataContext.js
// I'm trying to serve a "useQuery" called "getData" in order to fetch the API
let data = {};

const index = (obj, path) => path.split('.').reduce((o, i) => o[i], obj);
const setter = (obj, path, value) => {
    if (typeof path == 'string') return setter(obj, path.split('.'), value);
    else if (path.length == 1 && value !== undefined) return (obj[path[0]] = value);
    else if (path.length == 0) return obj;
    else return setter(obj[path[0]], path.slice(1), value);
};

const DataContextInstance = createContext({
    getData: async (...paths) => ({}),
    getTranslations: () => ({}),
});

export const DataContext = ({dataLoaded, children}) => {
    if (dataLoaded) data = dataLoaded;

    const {lang} = useContext(UserContext);
    const [prevLang, setPrevLang] = useState();

    const loadData = (path) => {
        if (Object.keys(data).length > 0) {
            const foundData = index(data, path);
            if (foundData?.then) throw foundData;
            if (foundData) return data;
        }
        const filePath = `/data/${path || `translations/${lang}`}.json`;
        const json = loadJSON(filePath).then((newData) => (data[path] = newData));
        data[path] = json;
    };

    const getData = (...paths) => {
        if (paths.every((p) => index(data, p))) return data;
        paths.forEach((p) => loadData(p));
        return data;
    };

    useEffect(() => {
        if (lang === prevLang && Object.keys(data).length > 0) return;
        if (Object.keys(data).length > 0) return;
        loadData();
        setPrevLang(lang);
    }, [lang, prevLang, setPrevLang, data]);

    const contextValue = useMemo(
        () => ({getData, getTranslations: () => getData()}),
        [data, lang]
    );

    return (
        <DataContextInstance.Provider value={contextValue}>
            <Suspense fallback={<span>Loading...</span>}>{children}</Suspense>
        </DataContextInstance.Provider>
    );
};

export const useDataContext = () => {
    const context = useContext(DataContextInstance);
    if (!context) throw new Error('Context must be used within a Provider');
    return context;
};

And then, I use that “getData” in my components in order to get the data needed for that one:

// NavBar.js
// Here I use my hook to get the DataContext context and get the "getData" func
function NavBar() {
    const {getData} = useDataContext();
    const {pages} = getData('menu').menu;
[...]

As you can see, I specify the json I want in every component in order to avoid loading all of them, so I have the “data” variable in my DataContext as a “cache”, so if it is loaded I simply return it.

Just syntax Error: Trying to call function from a class but getting an error. this[#currentRide].createRide

I have developed low level design of Cab Booking System.
But getting error when calling createRide function from class Rider.
Need Help
Flow of execution:
Rider: User
Driver: Cab Driver
Ride class used to book a ride.
Also I have created an object RideStatus to get status of Ride

const RideStatus={
    IDLE:"idle",
    CREATED:"created",
    WITHDRAWN:"withdrawn",
    COMPLETED:"completed"
}

class Ride{
   #id;
   #origin;
   #destination;
   #seats;
   #status=RideStatus.IDLE;
    static AMT_PER_KM=20   

   calculateFare(isPrivilleged){
       const totalKm=this.#destination-this.#origin;
        //console.log("FARE",this.#destination,this.#origin,totalKm,Ride.AMT_PER_KM,this.#seats,isPrivilleged);

    if(this.#seats>1){
        return totalKm*Ride.AMT_PER_KM*this.#seats* (isPrivilleged?0.5:0.75);
    }
    
    return totalKm*Ride.AMT_PER_KM*(isPrivilleged?0.75:1);
       
   }
   
   get getDesitnation(){
       return this.#destination;
   }
   
   set setDesitnation(destination){
       this.#destination=destination;
   }
   
   get getId(){
       return this.#id;
   }
   
   set setId(id){
       this.#id=id;
   }
   
   get getOrigin(){
       return this.#origin;
   }
   
   set setOrigin(origin){
       this.#origin=origin;
   }   
   
   get getSeats(){
       return this.#seats;
   }
   
   set setSeats(seats){
       this.#seats=seats;
   }
   
   
   get getStatus(){
       return this.#status;
   }
   
   set setStatus(status){
       this.#status=RideStatus[status];
   }
}

class Person{
    constructor(name){
        this.name=name;
    }
}

class Rider extends Person{
    #completedRides;
    #currentRide;
    
    constructor(name){
        super(name)
        this.name=name;
        this.#currentRide=new Ride();
        this.#completedRides=[];
    }
    
    createRide(id,origin, destination, seats){
        
        if(origin>=destination){
            console.log("Cannot create RIDE: Invalid ride values");
            return 
        }
        
        this.#currentRide.setId=id;
        this.#currentRide.setOrigin=(origin);
        this.#currentRide.setDestination=(destination);
        this.#currentRide.setSeats=(seats);
        this.#currentRide.setStatus=("CREATED");
    }
    updateRide(id,origin, destination, seats){
        if(this.#currentRide.getStatus==="withdrawn"||this.#currentRide.getStatus==="completed"){
            console.log(`Cannot update the ride. Ride was ${this.#currentRide.getStatus}`);
            return;
        }
        
        this.#currentRide.createRide(id,origin, destination, seats);
        
    }
    withdrawRide(id){
        if(this.#currentRide.getId!==id){
            console.log("Invalid Id current ride can't be withdrawn");
        }
        
        if(this.#currentRide.getStatus!=="created"){
            console.log("Ride wasn't in progress. Can't withdraw ride");
            return
        }
        
        this.#currentRide.setStatus=("WITHDRWAWN");
    }
    closeRide(){
        if(this.#currentRide.getStatus!=="created"){
            console.log("Ride wasn't in progress. Can't close ride");
            return 0;
        }
        this.#currentRide.setStatus=("COMPLETED");
        this.#completedRides.push(this.#currentRide);
        return this.#currentRide.calculateFare( this.#completedRides.length>=10);
        
    }
}

class Driver extends Person{
    
}


const rider =new Rider("Aman");
const driver= new Driver("Hari");

rider.createRide(1,50,76,1);
console.log(rider.closeRide());
rider.updateRide(1,50,76,2);
console.log(rider.closeRide());

console.log("***************************************************");

rider.createRide(1,50,70,1);
rider.withdrawRide(1);
rider.updateRide(1,50,70,2);
console.log(rider.closeRide());

Help me how to solve this issue.

Thank you.

UseEffect stop working after refreshing the site

I’m working in ReactJS. I have a form that is suppossed to be the configuration of another form. This specif form kind of looks like this:

  const [startingDate, setStartingDate] = useState();
  const [endingDate, setEndingDate] = useState();
  const [startingTime, setStartingTime] = useState();
  const [endingTime, setEndingTime] = useState();
  const [places, setPlaces] = useState();

  const createConfig = () => {
    Axios.post("http://localhost:3005/adminConfig", {
      startingDate,
      endingDate,
      startingTime,
      endingTime,
      places,
      organization: user._id,
    }).then((response) => {
      alert("successful")
    })
  }

After you send that data to the server I’m supposed to retrieve and set it as the configuration of another form (This second form is supposed to be shared and filled by other people) in the next way:

const [config, setConfig] = useState([]);

  useEffect(() => {
    Axios.get(`http://localhost:3005/adminConfig/`).then((response) => {
      setConfig(response.data);
    });
  }, []);

          <input
            type="date"
            placeholder="Date of the meeting
            name="date"
            id="datePickerId"
            min={config[0].startingDate}
            max={config[0].endingDate}
            onChange={(event) => {
              setDate(event.target.value);
            }}
            required
          />

When you access this form and havent set the configuration in React it works good. After accessing it and starting the configuration you can see how it updates; the dates are limited and in theory everything works good, the problem comes when you refresh the site or someone else try to access, it stops working and you have to delete the settings (config[0].startingDate, etc)

console shows:

Cannot read properties of undefined (reading ‘startingDate’)

Any help is appreciated

Оплата в форме регистрации с условием вывода цены из select [closed]

Данный код при нажатии на кнопку “Купить” выводит окно Сбербанка для оплаты с ценой 499,99

<a onclick=”ipayCheckout({
amount:499.99,
currency:’RUB’,
order_number:”,
description: ‘Тариф’},
function(order) { showSuccessfulPurchase(order) },
function(order) { showFailurefulPurchase(order) })”

class="btn btn-xs btn-outline btn-primary">Купить

Мне необходимо это сделать с условием. В зависимости от выбора в форме регистрации, после нажатия на кнопку “Отправить” выходило окно с оплатой и ценой тарифного плана, выбранного в :

Тариф “Теория”
Тариф “Практикум”

Есть понимание что это делается при помощи if и else, но как не понимаю.

Create post request with data from html table rows and save each row separately Order-Products

can someone give me tip how to slove problem. Am building Order Managment System app using PHP, MYSQL, HTML and JS.
Order information is stored in one db table and
Order Products is sotred in second db table which cointains two foreign key (order_id and product_id). Order can have many products!

What is problem

The problem is that I don’t know how to get html table rows and put that rows in array, and that array i need to send via ajax to php where i will process.

I was thinking the following:

  1. When the user selects a product from the drop-down list, enters the quantity and presses the “ADD PRODUCT” button.

  2. In javascript, I create an event for a button (‘click’) where after event is triggered I will dynamically create a new row in the table using js insertRow().

  3. In the columns of the rows I saved the values ​​in the form fields. Maybe I was wrong there.
    `id.innerHTML = ‘<input type=”text” value=”‘+data[0][‘id’]+'” id=”id-‘+data[0][‘id’]+'”;

  4. Products is successfully added as rows with values ​​to the table.

I’m not asking you to do my job. I just want you to advise me how it should be done in the right way.

HTML

<table id="document_items_table">
   <thead class="table-light">
       <tr>
         <th width="10%">#</th>
         <th>Šifra</th>
         <th>Naziv</th>
         <th>Količina</th>
         <th>JM</th>
        </tr>
   </thead>                      
   <tbody></tbody>
</table>

JavaScript

 // add item to document
$("#btn_add_document_item").on('click', function(e) {

     var data = $('#select2-proizvodi').select2('data');

     // add table row

     var table = document.getElementById('document_items_table');
     var row = table.insertRow(-1);

     var id = row.insertCell(0);
     var code = row.insertCell(1);
     var name = row.insertCell(2);
     var qty = row.insertCell(3);
           

    row.setAttribute('id', 'row-'+table.rows.length);

    id.innerHTML = '<input type="text" value="'+data[0]['id']+'" id="id-'+data[0]['id']+'"  name="item[]["id"]" ;
    code.innerHTML = '<input type="text" value="'+data[0]['code']+'" name="item[]["code"]";
   name.innerHTML = '<input type="text" value="'+data[0]['text']+'"  name="item[]["name]";
  qty.innerHTML = '<input type="text" class="form-input"  value="'+$("#kolicina_input").val()+'" name="kolicina[]["kolicina"]" ;
           
});

PHP is not a problem.

Check image

enter image description here

Memoize object lazily so that first attempt to access it would load it

Is there some npm package for memoizing object lazily, so that the first attempt to access it would load it?

The problem:

// service

class Service {
  private readonly pathMap = {
    user: process.env.USER_PATH,
    post: process.env.POST_PATH,
    page: process.env.PAGE_PATH,
  }
  
  getPath(entityType: EntityType) {
    return this.pathMap[entityType];
  }
}

export const service = new Service();

// service.spec.ts

import { service } from './service';
import { loadEnvVars } from '@app/loadEnvVars';

describe('service', () => { 
  beforeAll(loadEnvVars);

  it('should return path', () => {
    expect(service.getPath('user')).toBe(process.env.USER_PATH);
    expect(service.getPath('post')).toBe(process.env.POST_PATH);
    expect(service.getPath('page')).toBe(process.env.PAGE_PATH);
  });
 });

The tests will fail because the singleton service will load before the loadEnvVars due to the import of the service (before the beforeAll), which means the env vars will be set to undefined in the service pathMap.

The proposed solution:

I know there are several ways to fix it, but IMO the best solution would be to somehow lazy load the pathMap object so that the first attempt to get something from it will actually init the variable’s value.

Here’s a function I wrote to tackle this (Typescript):

export function lazy<T extends (...args: any[]) => any>(factory: T): ReturnType<T> {
  let obj: ReturnType<T> | undefined;
  const proxy = new Proxy(
    {},
    {
      get(_, key) {
        if (!obj) {
          obj = factory();
        }
        return obj[key];
      }
    }
  );
  return proxy as ReturnType<T>;
}

Now the service will look like this instead:

class Service {
  private readonly pathMap = lazy(() => ({
    user: process.env.USER_PATH,
    post: process.env.POST_PATH,
    page: process.env.PAGE_PATH,
  }));
  
  getPath(entityType: EntityType) {
    return this.pathMap[entityType];
  }
}

export const service = new Service();

Now the tests will pass.

Note: In this solution lazy returns a read-only object. It can be changed of course.

The question:

Is there some NPM library out there that provides something like that already? Cause if not I think I might publish it myself.

How can I change a message pop up?

A B2B that shows this default message when the customer tries to order too much of a certain product. I want to change that message to something like “you can’t order more than the available qty”

I’ve tried

.error-msg {content: 'you can't order more than the available qty' ;

But this just adds to the default message.

I can’t find where this default message comes from

Why is 0.00002 * 100000000 != 2000 in javascript? [duplicate]

I am passing a string to node.js and then using parseFloat to turn it into a float:

const amountToSend = parseFloat(process.argv[3]);  // gives me 0.00002

If I then do this:

const satoshiToSend = amountToSend * 100000000;
console.log(satoshiToSend);

The console.log gives me:

2000.0000000000002

At what point am I not converting or casting correctly so as to get the correct value of 2000 at this point? And where, pray do tell, is the 0.0000000000002 coming from?

how can i pass a updated state to a function as argument in functional react

I have state that when dispatch an action,state was increament or deacreament,I use it for a scale to zoomIn or zoomOut on a picture.when onClick on button dispatched an action and getstate with useSelector and pass it to a function as argument,I log state in function,but state value is not updated state,
how can I at first get updated state and pass it to a callback function as argument?
I now this problem solve with useEffect,but I want now is there any way to solve this issue?

for example default state vlaue is 0,when despatched increament value state is 1,but log in callback function is 0 and so on.

const Tools = () => {
    
    const scale = useSelector(state => state.scale);//default scale is 0

    //this is my callback function
    const handleScale = () => {      
       sendScale(scale);
    }
    return ( 
        <Fragment>
            <div className='w-100 mt-1 tools-container'>
                <div className='w-100 d-flex mb-3'>
                    <div className='scale-wrapper'>
                        <Button variant='light' onClick={() => {
                            dispatch(decreamentScale());
                            handleScale();
                        }}><i class="bi bi-zoom-out"></i></Button>
                        <Button className='ms-2' variant='light' onClick={() => {
                            dispatch(increamentScale());
                            handleScale();
                        }}><i class="bi bi-zoom-in"></i></Button>
                    </div>
                </div>
            </div>
        </Fragment>
     );
}
 
export default Tools;
//my action,i use reduxThunk
export const increamentScale  = () => {
    return async (dispatch) => {
        await dispatch({type:"INCREAMENT_SCALE"});
    }
}

export const decreamentScale  = () => {
    return async (dispatch) => {
        await dispatch({type:"DECREAMENT_SCALE"});
    }
}

Dynamically updating Django template with new data

I am creating a cricket website which shows the live scores of cricket matches using Django.
Below I have shown the sample views.py for my website:

Views.py

def livescores():
    # generates livescores and returns a dict containing live scores
    return scores

def display_scores(request):
    # calls the livescores function and gets the dict and 
    #passes it to django template for rendering purposes
    scores = livescores()
    return render(request, 'LiveScores/display_scores.html', scores)

Here is the Django template to which it passes that dict:

    <!DOCTYPE html>
<html>
    <head>
        <title>{{MatchName}}</title>
        {% load static %}
        <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-kjU+l4N0Yf4ZOJErLsIcvOU2qSb74wXpOhqTvwVx3OElZRweTnQ6d31fXEoRD1Jy" crossorigin="anonymous"></script>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <link href="{% static 'LiveScores/style.css'%}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <header>
            <nav class="navbar">
            <div class="container-fluid">
              <a class="navbar-brand" href="#"><h1>Live Cricket Scores</h1></a>
              <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
              </button>
              <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                  <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="#">Home</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="#">About Us</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link">Contact Us</a>
                  </li>
                  <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                      More
                    </a>
                    <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                      <li><a class="dropdown-item" href="#">Live Matches</a></li>
                      <li><a class="dropdown-item" href="#">Terms & Services</a></li>
                      <li><hr class="dropdown-divider"></li>
                      <li><a class="dropdown-item" href="#">Sources</a></li>
                    </ul>
                  </li>
                  
                </ul>
                <form class="d-flex" role="search">
                  <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                  <button class="btn btn-outline-success" type="submit">Search</button>
                </form>
              </div>
            </div>
          </nav>
        </header>
        <section class="container" id="main-content">
            <div class="row">
                <div class="col-sm-4">
                  <div class="card">
                    <div class="card-body">
                      <h5 class="card-title">{{Team1}}</h5>
                      <p class="card-text">{{RunRate}}</p>
                    </div>
                  </div>
                </div>
                <div class="col-sm-4">
                    <div class="card">
                      <div class="card-body">
                        <h5 class="card-title">{{result}}</h5>
                        <p class="card-text">{{situation}}</p>
                      </div>
                    </div>
                  </div>
                <div class="col-sm-4">
                  <div class="card">
                    <div class="card-body">
                      <h5 class="card-title">{{Team2}}</h5>
                      <p class="card-text">* LIVE</p>
                    </div>
                  </div>
                </div>
            </div>
        </section>
    </body>
</html>

Problem

Now comes the problem:
Actually I want that template to update its content in (section id=’main-content’) dynamically and I don’t know how to do it. I have followed some answers on stackoverflow.com and google regarding the use of Ajax for the purpose but it did me no help! Some answers caused the navbar to duplicate when the content was updated and others just populated the tag with unnecessary things like ‘Bootstrap CDN links’, ‘title tag’ etc…
Any help is appreciated!

Can’t compose correctly query objection.js

I can’t correctly compose a query where I need to find the required field from the table by client id and tower id and, if successful, assign tower id to my variable ‘tower’. (commented out line) table custumer_address

const queryBuilder = Customer.query()
    .alias('customer')
    .select('*')
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id`) as `orders_count`'))
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id` AND `type`=' + ORDER_TYPE.RESTAURANT_DELIVERY + ') as orders_rd_count'))
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id` AND `type`=' + ORDER_TYPE.GROCER_DELIVERY + ') as orders_gd_count'))
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id` AND `type`=' + ORDER_TYPE.PHARMACY_DELIVERY + ') as orders_pd_count'))
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id` AND `type`=' + ORDER_TYPE.LAUNDRY_DELIVERY + ') as orders_ld_count'))
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id` AND `type`=' + ORDER_TYPE.FLOWERS_DELIVERY + ') as orders_fd_count'))
    .select(raw('(SELECT COUNT(*) FROM `order` WHERE `customer_id`=`customer`.`id` AND `type`=' + ORDER_TYPE.ASSISTANT_HELP + ') as orders_ah_count'))
    // .select(raw('(SELECT * FROM `customer-address` WHERE `customer_id`=`customer`.`id` AND `tower_id`=' + parseFilter.tower + ') as tower'))
    .select(raw('(SELECT MAX(`created_at`) FROM `order` WHERE `customer_id`=`customer`.`id`) as `last_order_at`'))
    .where('deleted', false);

Javascript Regular Expression and not match some words

Helo

How do I use regex to not match words without the span tags.

var str = '<p><span style="background-color: rgb(230, 0, 0">@Jack johson</span>&nbsp;@John Return&nbsp;dsdfsdsf @Daniel&nbsp;</p></p>';
    
var matchstr = str.match(/(?!>)@w+s?w+/g);

My Expected Result should be only
@John Return
@Daniel

Thank you.

Unable to fetch date data in HTml from database

I have a input box in HTML

<label>Holiday</label>
<input type="date"  class="form-control" asp-for="HolidayDate" >

In this field I want data from my Database in sqlserver. For this I used the code on button click

code for javascript

<script>`javascript`
  $(".btnGet").click(function () {
            var origin = window.location.origin;
            $.post(origin + "/HolidayMaster/Edit //my controller page
                { Id: $(this).attr("data-id") }, //id for fetching data
                function (response) {
                    $("#HolidayMasterId").val(response.holidayMasterId)`primary key`
                   $("#HolidayDate").val(response.holidayDate)
                  
                }
            );
        });

</script>

Here HolidayMaster is my controller

My question is I am unable to bring date in form control but Function(response) fetch data from Database.