Creating and passing an array from JavaScript to PHP page

I am creating this dynamic table in one PHP page. The length of the table will be determined by the number of products in the MYSQL product table:

<code>

<code>
<code>
<code>
<code> Photo
<code> Name
<code> Price
<code> Qty
<code>

<code> <?php

<code> $row = $result -> fetch_assoc();
<code> foreach($result as $row) {
<code> $pic = $row[‘photolink’];
<code> $name = $row[‘name’];
<code> $price= $row[‘price’];
<code> ?>
<code>
<code> <img src= width=”30″
<code>
<code>
<code> <input type=”text” name=”qty” placeholder=”Qty” id=”qty” <code>style=”width: 50px;” > `=”qtyvalue()”–>
<code>

<code> <?php

<code> $cycle = $cycle + 1;
<code> }
<code> ?>
<code>
<code>
<code> `bottom:5px;” onclick =”qtyvalue()” >Add To Cart
<code> `

I then want to send the quantity and associated product to another PHP page. I can successfully pass one combination but not all of the combinations. I have read many solutions but I cannot get any to work. How do I fix the JavaScript below?

<code> <script <code>src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”><code>
<code>
<code> function qtyvalue() {
<code> var numqty = “”;
<code> var r=1;
<code> var x= [];
<code> while( r < numqty+1){
<code> var x = <code>document.getElementById(“prodtab”).rows[r].cells[3].getElementsByTagName(‘input’) <code>[0].value;

<code> // document.write(‘numqty’);
<code> // document.write(‘x’);
<code> // document.write(‘r’);
<code> // window.location.href = “https://trump.tgsconsultinginc.com/php-<code>includes/addtocart.php?x=” + x +”&r=” + r + “&numqty=” + numqty;
<code> r++;
<code> }
<code> alert(x.toString());
<code> }

If I change the “r” in rows to a valid number , I get the correct pairing and it transfers to the PHP page. I have tried many variations of making x and r arrays but nothing works. The href statement is commented out here as I was trying to just get the alert to work.

Get link from an tag href=”JavaScript:void(0)”

I am trying to Web Scrapp a Web page using python with selenium.
The main problem is that i need to get an link on href of a tag and when i got this data i realized that it was not an link but ‘href=”JavaScript:void(0)”‘.
When I click in this link, it downloads an excel file, i really need to do it, pls help me guys!

I am trying to Web Scrapp a Web page using python with selenium.
The main problem is that i need to get an link on href of a tag and when i got this data i realized that it was not an link but ‘href=”JavaScript:void(0)”‘.
When I click in this link, it downloads an excel file, i really need to do it, pls help me guys

Severe technical issue

I was up late last night running red lights, an d wheN i got home I accidertnally hit my computer. It fell, and the screen keyboard and that gru thing all exploded out. I managed to catcj most of it, and held the keys in teh air — that’s actually how I’m typing right now. Is there anybody here that knows a good place to get a car wash in Montana?

I’ve already tried downloading more ram, but I can’t seem to get it working again. My car, not the computer.
Thanks

When passing variables, two instances of React component are alive. How to delete the old one?

I encouter some really weird behavior with my React component. I am completely new to React. I have one page on which the user can configure some toasts that will be displayed. I am making us of the react-hot-toast package. The user fills in a google place id whereafter toasts with reviews will be displayed. Everything is working fine until the following point:

When I clicked apply for the first time, the first toasts are showing up fine. However, when I then edit some variables like the position of the toast, the new toasts show up, but the old toasts (with the old position) are still showing up! It seems like when I click apply for the second time, two instances of the PopTrustToast component are alive, since console.log("position", position); is printing bottom-left and also top-right for example.

When I click apply, I want the old PopTrustToast component to be deleted and start with a fresh one. ChatGPT unfortunately could not help me with this. If anyone can, this would be extremely helpful for me!

Dashboard -> page.tsx

"use client";
import ButtonAccount from "@/components/ButtonAccount";
import config from "@/config";
import logo from "@/app/icon.png";
import Image from "next/image";
import { CodeBlock, CopyBlock, dracula } from 'react-code-blocks';
import React, { useEffect, useState } from 'react';
import Footer from "@/components/Footer";
import PopTrustToast from "@/components/PopTrustToast";
import { ToastPosition } from "react-hot-toast";

export const dynamic = "force-dynamic";

export default function Dashboard() {

  useEffect(() => {
    const handleClickOutside = () => {
      document.querySelectorAll('.dropdown').forEach(function (dropdown) {
        // Click was outside the dropdown, close it
        (dropdown as HTMLDetailsElement).open = false;
      });
    };

    // Attach the event listener to window
    window.addEventListener('click', handleClickOutside);

    // Cleanup the event listener on component unmount
    return () => window.removeEventListener('click', handleClickOutside);
  }, []);


  const [placeId, setPlaceId] = useState('');

  const [shouldFetch, setShouldFetch] = useState(false);
  const [toastPosition, setToastPosition] = useState<ToastPosition>('bottom-right'); // default position
  const [isOpen, setIsOpen] = useState(false); // State to control dropdown open status
  const [initialWaitTime, setInitialWaitTime] = useState(2); // State for initial wait time
  const [frequencyTime, setFrequencyTime] = useState(6); // State for frequency time
  const [durationTime, setDurationTime] = useState(8); // State for duration time
  const [minRating, setMinRating] = useState(5); // State for minimum rating
  const [key, setKey] = useState(0); // State to force re-render


  const handlePlaceIdChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
    console.log(event.target.value);
    setPlaceId(event.target.value);
  };

  const handleApplyClick = () => {
    setShouldFetch(true);
    setKey(prevKey => prevKey + 1); // Increment key to force re-render
  };

  const formatPositionText = (position: string): string => {
    return position.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  };


  return (
    <>
      <main className="p-8 mb-20">
        <section className="max-w-3xl mx-auto space-y-8 ">
          <nav className="container flex items-center justify-between px-0 py-4 mx-auto" aria-label="Global">
            <div className="flex lg:flex-1 items-center">
              <Image
                src={logo}
                alt={`${config.appName} logo`}
                priority={true}
                width={32}
                height={32}
              />
              <span className="font-extrabold text-lg">{config.appName}</span>
            </div>
            <div className="flex-grow"></div>
            <ButtonAccount />
          </nav>
          <div className="flex flex-col items-center justify-center text-center">
            <h2 className="font-bold text-6xl md:text-2xl tracking-tight mb-2">Reviews popup configuration</h2>
            <p className="label-text mb-6 text-gray-400">Your popups will be displayed on this screen to showcase them</p>

            <div className="flex flex-wrap justify-center gap-10">
              {/* First column */}
              <div>
                <div className="form-control w-full max-w-xs mb-4">
                  <div className="label">
                    <span className="label-text">Google Maps Place ID</span>
                    <a href="https://developers.google.com/maps/documentation/places/web-service/place-id#:~:text=Are%20you%20looking%20for%20the%20place%20ID%20of%20a%20specific%20place%3F%20Use%20the%20place%20ID%20finder%20below%20to%20search%20for%20a%20place%20and%20get%20its%20ID%3A" target="_blank" rel="noopener noreferrer" className="underline text-gray-500 ml-2">
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h1m0-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </a>
                  </div>
                  <input type="text" value={placeId} onChange={handlePlaceIdChange} placeholder="ChIJN0uYIOqwxUcR6qshtf23qiA" className="input input-bordered w-full max-w-xs" />
                  {/* <div className="mt-2 flex items-center text-sm">
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h1m0-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <a href="https://www.vendasta.com/blog/gbp-url/#:~:text=are%20being%20shared.-,How%20to%20find%20the%20Google%20Business%20Profile%20URL,-By%20following%20these" target="_blank" rel="noopener noreferrer" className="underline text-gray-500 ml-2">
                    Where do I find this?
                  </a>
                </div> */}
                </div>
                <div className="w-full max-w-xs text-left">
                  <div className="label">
                    <span className="label-text">Position</span>
                  </div>
                </div>
                <details className="dropdown w-full max-w-xs mb-4" style={{ zIndex: 2 }} open={isOpen} >
                  <summary className="btn w-full">{formatPositionText(toastPosition)}</summary>
                  <ul className="p-2 shadow menu dropdown-content bg-base-100 rounded-box w-52">
                    {['top-left', 'top-right', 'bottom-left', 'bottom-right'].map(position => (
                      <li key={position} onClick={() => {
                        setToastPosition(position as ToastPosition);
                      }}>
                        <a>{formatPositionText(position)}</a>
                      </li>
                    ))}
                  </ul>
                </details>
                <div className="w-full max-w-xs text-left">
                  <div className="label">
                    <span className="label-text">Theme (style)</span>
                  </div>
                </div>
                <details className="dropdown w-full max-w-xs mb-4 z" style={{ zIndex: 1 }}>
                  <summary className="btn w-full">Light</summary>
                  <ul className="p-2 shadow menu dropdown-content bg-base-100 rounded-box w-52">
                    <li><a>Light</a></li>
                    <li><a>Dark</a></li>
                  </ul>
                </details>
                <div className="w-full max-w-xs text-left">
                  <div className="label">
                    <span className="label-text">Reviews sorting</span>
                  </div>
                </div>
                <details className="dropdown w-full max-w-xs mb-4 z" style={{ zIndex: 1 }}>
                  <summary className="btn w-full">Most recent first</summary>
                  <ul className="p-2 shadow menu dropdown-content bg-base-100 rounded-box w-52">
                    <li><a>Most recent first</a></li>
                    <li><a>Random</a></li>
                  </ul>
                </details>
              </div>

              {/* Second column */}
              <div>
                <div className="w-full max-w-xs text-left">
                  <div className="label">
                    <span className="label-text">Minimum rating</span>
                  </div>
                </div>
                <details className="dropdown w-full max-w-xs mb-4 z" style={{ zIndex: 1 }}>
                  <summary className="btn w-full">{minRating} stars</summary>
                  <ul className="p-2 shadow menu dropdown-content bg-base-100 rounded-box w-52">
                    {[1, 2, 3, 4, 5].map(star => (
                      <li key={star} onClick={() => setMinRating(star)}>
                        <a>{star} star{star > 1 ? 's' : ''}</a>
                      </li>
                    ))}
                  </ul>
                </details>
                <div className="form-control w-full max-w-xs mb-4">
                  <div className="label">
                    <span className="label-text">Displaying first popup after (seconds)</span>
                  </div>
                  <input type="number" value={initialWaitTime} onChange={e => setInitialWaitTime(parseInt(e.target.value, 10))} placeholder="2" className="input input-bordered w-full max-w-xs" />
                </div>
                <div className="form-control w-full max-w-xs mb-4">
                  <div className="label">
                    <span className="label-text">Show popup every (seconds)</span>
                  </div>
                  <input type="number" placeholder="6" value={frequencyTime} onChange={e => setFrequencyTime(parseInt(e.target.value, 10))} className="input input-bordered w-full max-w-xs" />
                </div>
                <div className="form-control w-full max-w-xs">
                  <div className="label">
                    <span className="label-text">Duration of popup (seconds)</span>
                  </div>
                  <input type="number" placeholder="8" value={durationTime} onChange={e => setDurationTime(parseInt(e.target.value, 10))} className="input input-bordered w-full max-w-xs" />
                </div>

              </div>

            </div>
            <div className="w-full max-w-xl flex justify-center mt-4 px-3">
              <button onClick={handleApplyClick} disabled={shouldFetch} className="btn w-full max-w-4xl bg-orange text-white">Apply</button>
            </div>
            <dialog id="my_modal_1" className="modal">
              <div className="modal-box">
                <h3 className="font-bold text-lg">Hello!</h3>
                <p className="py-4">Press ESC key or click the button below to close</p>
                <div className="modal-action">
                  <form method="dialog">
                    {/* if there is a button in form, it will close the modal */}
                    <button className="btn">Close</button>
                  </form>
                </div>
              </div>
            </dialog>
          </div>
        </section>
        <PopTrustToast key={key} placeId={placeId} shouldFetch={shouldFetch} setShouldFetch={setShouldFetch}
          position={toastPosition} initialWaitTime={initialWaitTime} frequencyTime={frequencyTime} durationTime={durationTime} minRating={minRating} />
      </main>
      <Footer />
    </>
  );
}

PopTrustToast.tsx

"use client";
import React, { ReactEventHandler, use, useEffect, useState } from 'react';
import './PopTrustToast.css';
import toast, { ToastPosition } from 'react-hot-toast';
import { formatDistance } from 'date-fns';

const PopTrustToast = ({ placeId, shouldFetch, setShouldFetch, position, initialWaitTime, frequencyTime, durationTime, minRating }:
  {
    placeId: string, shouldFetch: boolean, setShouldFetch: (value: boolean) => void, position: ToastPosition,
    initialWaitTime: number, frequencyTime: number, durationTime: number, minRating: number
  }) => {
  const [toastIndex, setToastIndex] = useState(0);
  const [allowToasts, setAllowToasts] = useState(true); // New state to control toast display
  const [messages, setMessages] = useState([]); // State to hold fetched messages

  const epochToRelativeTime = (epoch: number) => {
    const date = new Date(epoch * 1000); // Convert epoch to milliseconds
    const now = new Date();
    return formatDistance(date, now, { addSuffix: true });
  };

  const checkReviewStatus = async (placeId: String) => {
    if (!placeId) return null;
    const response = await fetch('http://localhost:3001/proxy?placeId=' + placeId, {
    });
    const data = await response.json();
    return data;
  };



  const fetchReviews = async (placeId: String) => {
    if (!placeId) return [];
    try {
      const response = await fetch(`api.xxxxx/reviews?uris%5B%5D=${placeId}&with_text_only=1&min_rating=${minRating}&page_length=50&order=random`);
      const data = await response.json();
      return data.result.data.map((review: { text: any; reviewer_name: any; reviewer_picture_url: any; id: { toString: () => any; }; rating: any; url: any; published_at: any }) => ({
        text: review.text,
        author: review.reviewer_name,
        timeAgo: epochToRelativeTime(review.published_at),
        src: review.reviewer_picture_url,
        id: review.id.toString(),
        stars: review.rating,
        url: review.url
      }));
    } catch (error) {
      console.error('Failed to fetch messages:', error);
      return [];
    }
  };

  // Fetch messages from API
  useEffect(() => {
    if (!placeId || !shouldFetch) return;
    toast.dismiss(); // Dismiss all toasts before fetching new messages
    setAllowToasts(false); // Prevent further toasts
    setMessages([]); // Clear messages
    toast.loading('Fetching reviews... This can take up to a minute', { duration: 9999999, position: 'bottom-center', style: { position: 'relative', bottom: '1rem' } });
    const interval = setInterval(async () => {
      const status = await checkReviewStatus(placeId);
      const isComplete = status?.result?.data?.some((item: { profile_state: Object[]; }) => item.profile_state[0] === "complete" && item.profile_state[1] === 100);
      if (isComplete) {
        setAllowToasts(true);
        setShouldFetch(false); // Set shouldFetch to false
        toast.dismiss();
        toast.success('Fetched reviews succesfully!', { position: 'bottom-center', style: { position: 'relative', bottom: '1rem' } })
        clearInterval(interval);
        fetchReviews(placeId).then(setMessages);
      }
    }, 3000);

    return () => clearInterval(interval);
  }, [placeId, shouldFetch]);

  //First toast
  useEffect(() => {
    if (messages.length === 0) return;
    const timeout = setTimeout(() => {
      if (allowToasts) {
        sendNotification(0);
      }
    }, initialWaitTime * 1000);
    return () => clearTimeout(timeout);
  }, [allowToasts, messages]);

  let recurringInterval: NodeJS.Timeout;

  useEffect(() => {
    if (messages.length === 0) return;
    // Dismiss all toasts when the location changes
    toast.dismiss();

    // Clear recurring interval
    clearInterval(recurringInterval);

    let toastIndex = 1;
    const timeout = setTimeout(() => {
      recurringInterval = setInterval(() => {
        if (toastIndex < messages.length && allowToasts) {
          sendNotification(toastIndex);
          toastIndex++;
        } else {
          clearInterval(recurringInterval);
        }
      }, frequencyTime * 1000);
      return () => clearInterval(recurringInterval);
    }, initialWaitTime * 1000);
    return () => clearTimeout(timeout);
  }, [allowToasts, messages]);



  const sendNotification = (toastIndex: number) => {
    console.log("sending notification", toastIndex);
    const message = messages[toastIndex];
    console.log("position", position);

    toast.custom((t) => <Message message={message} t={t} position={position} />, {
      duration: durationTime * 1000,
      position: position as ToastPosition,
      id: toastIndex.toString(),

    });

    setToastIndex((prev) => prev + 1);
  };

  return <></>;
};

const Message = ({ message, t, position }: { message: any, t: any, position: ToastPosition }) => {

  // Do some stuff
  return (

    // Toast HTML
  );
};


export default PopTrustToast;

Filter object from nested json array at any level retaining the parent array hierarchy

I have a multi-level nested array similar to the below structure.
What I’m trying to do is to filter for list of cases whose has a 'flag' value of 'Gold'.
Only nodes with type = 'Model' or type = 'Project' will have direct children cases with type = 'Case' having flag value.

const models = [
    {
        "name": "Group1",
        "type": "Group",
        "cases": [
            {
                "name": "Model1",
                "type": "Model",
                "cases": [
                    {
                        "name": "Case1",
                        "type": "Case",
                        "flag": "Gold",
                        "cases": []
                    }
                ]
            },
            {
                "name": "Model2",
                "type": "Model",
                "cases": [
                    {
                        "name": "Project1",
                        "type": "Project",
                        "cases": [
                            {
                                "name": "Project2",
                                "type": "Project",
                                "cases": [
                                    {
                                        "name": "Case2",
                                        "type": "Case",
                                        "flag": "Gold",
                                        "cases": []
                                    },
                                    {
                                        "name": "Case3",
                                        "type": "Case",
                                        "flag": "Silver",
                                        "cases": []
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "name": "Case4",
                        "type": "Case",
                        "flag": "Gold",
                        "cases": []
                    }
                ]
            },
        ]
    },
    {
        "name": "Group2",
        "type": "Group",
        "cases": [
            {
                "name": "Model3",
                "type": "Model",
                "cases": [
                    {
                        "name": "Case5",
                        "type": "Case",
                        "flag": "Gold",
                        "cases": []
                    }
                ]
            }
        ]
    }
]

For example, if I want to filter only for list of cases which flag = 'Gold' the result would like the below.

Group1
    ...Model1
         { Case1 }
    ...Model2
        ...Project1
             ...Project2
                 { Case2 }
        { Case4 }
Group2
    ...Model3
        { Case5 }

I tried the below two approaches but not getting the expected result.
Using filter option.

 private getFilteredList(models: any[], term: string): any[] {
        const filterList = (data, term) => {
            data.filter((e) => {
                if (e.type === "Model" || e.type === "Project") {
                    e.cases = e.cases.filter(c => c.flag === term);
                }
                else if (e.cases) {
                    filterList(e.cases, term);
                }
            });
        }
        filterList(models, term);

        return models;
    }

Using the reduce function. This piece of code results in infinite loop.

private getFilteredList(models: any[], term: string): any[] {
        return models.reduce((list, item) => {
            if (item.flag === term) {
                list.push(item);
            } else if (item.cases && item.cases.length > 0) {
                const caseList = this.getFilteredList(item.cases, term);

                if (caseList.length > 0) {
                    list.push({ name: item.name, cases: caseList });
                }
            }

            return list;
        }, []);
    }

Any help appreciated.

Property ‘keys’ does not exist on type ‘{}’. const { keys } = data;

I get the error mentioned in the title for the following typescript middleware: (target: es6, module commonjs)

    try {
        const response = await fetch(URL);
        if (response.status !== 200) {
            throw 'request not successful'
        }
        const data = await response.json();
        const { keys } = data;
        for (let i = 0; i < keys.length; i++) {
            const key_id = keys[i].kid;
            const modulus = keys[i].n;
            const exponent = keys[i].e;
            const key_type = keys[i].kty;
            const jwk = { kty: key_type, n: modulus, e: exponent };
            const pem = jwkToPem(jwk);
            pems[key_id] = pem;
        }
        console.log("got PEMS")
    } catch (error) {
        console.log(error)
        console.log('Error! Unable to download JWKs');
    }
}

Where ive defined this globally let pems: { [key: string]: string } = {}, not sure exactly where my issue lies any help would be appreciated

Followed the exact tutorial to this however still stuck on this one error message, possibly the tutorial was outdated im not exactly sure

Partial Data Migration inside IndexedDB onupgradeneeded

I’m updating objects in an IndexedDB ObjectStore to convert a property from a base64-encoded string to Blobs. However, the operation seems to only succeed partially even though the database’s version gets updated, leaving a half-finished conversion.

Here’s the gist of what I’m doing.

databaseRequest.onupgradeneeded = (event) => {
   
  // [Code to get the objectStore, etc. goes here]

  if (event.oldVersion < 2) {  
    objectStore.openCursor().onsuccess = function(cursorEvent) {
      let cursor = cursorEvent.target.result;
      if (cursor) {
         let value = cursor.value;
         value.data = convertToBlob(value.data); // Note: convertToBlob is synchronous
         cursor.update(value);
         cursor.continue();
      }
    }
  }
}

Since this update, it appears that some users’ objectStores have not been fully converted. Their database version is up-to-date, but many of their older records are still in the base64 format. What’s worse, since the version number of the database still gets set to the latest, the data resides in this inconsistent format.

I’m curious what I might have done wrong. Is my convertToBlob() too expensive to be done inside onupgradeneeded? (Admittedly, the blobs are large, around 5mb each, so it can take a bit to convert.)

Are using cursors inside onupgradeneeded recommended? I wonder if they’re asynchronous and therefore the version gets updated even if it fails?

Any help is appreciated!

Icons and Click Events with Google Maps API Advanced Marker Elements

I am looking to convert some legacy Google Maps markers to Advanced Marker Elements. I am a bit lost and the documentation is limited. There is a lot of custom behavior in the code around these markers. First do you have any general advice for converting?

More specifically, here is a bit of code that shows how I am using the markers.

let marker = new google.maps.marker.AdvancedMarkerElement({
      position: { lat: value.LATITUDE, lng: value.LONGITUDE },
      map: serviceLaunchPage.map,
            icon: {
                url: $('#current_url_root').val() + icon,
                scaledSize: new google.maps.Size(32, 32),
                size: new google.maps.Size(32, 32)
            },
      // Custom properties.
      buildingId: value.BUILDINGID,
      infoWindowContent: infoWindowContent,
  });


  function handleMarkerClick(marker) {
      // Close current info window if it exists
      if (serviceLaunchPage.mapCurrentInfoWindow)
          serviceLaunchPage.mapCurrentInfoWindow.close();
      // Create info window
      let infoWindow = new google.maps.InfoWindow({
          content: marker.infoWindowContent,
      });

   // Set current info window to new info window
serviceLaunchPage.mapCurrentInfoWindow = infoWindow;

   // Open new info window
      infoWindow.open({
          anchor: marker,
          map: serviceLaunchPage.map,
          shouldFocus: false,
      });
  }

  // When the marker is clicked.
  marker.addEventListener('gmp-click', () => handleMarkerClick(marker));

  serviceLaunchPage.mapMarkers.push(marker);

How are the icons and click events handled in the Advanced Marker Elements?

jQuery scroll function working in chrome, but not safari on WordPress website

I’ve just started working in a new website, built by someone else but now I’m taking over. For the header menu, there is a jquery event that when the user scrolls down, new classes are added to the header menu, and new styles are applied. It’s working perfectly fine in chrome, but it’s not working at all in safari. The event isn’t triggering on scroll, no classes are being added. It’s a wordpress website. Here is the code:

// Header menu tricks

jQuery(document).ready(function () {
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 100) {
jQuery('.header-area, .homepage-popup, #desktop-mini-cart').addClass('tight departed');
} else {
jQuery('.header-area, .homepage-popup, #desktop-mini-cart').removeClass('tight');
}
});
});

jQuery(document).ready(function () {
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 100) {
jQuery('.menu-display-area').addClass('tight');
} else {
jQuery('.menu-display-area').removeClass('tight');
}
});
});

Does anyone know why this would be working in chrome, and not safari? IF you want to see for yourself, here is the website: https://www.ashleybottendesign.com/

Why does the simple python server / javascript socketio communication fail?

I have a simple flask-socketio server that emits a stream of floats and serves an html file with a javascript socket.io listener. The initial connection appears to immediately disconnect, the server does continue to emit messages (I monitored using Wireshark), but nothing appears on the webpage.

Versions:

  • OS: Windows 11
  • python: 3.11.9
  • Flask 3.0.3
  • Werkzeug 3.0.2
  • python-socketio: 5.11.2
  • python-engineio: 4.9.0
  • simple-websocket: 1.0.0
  • javascript socket.io: 4.0.1
  • Browser: Chrome Version 123.0.6312.122 (Official Build) (64-bit)

I tried with earlier socketio / engineio and Javascript socket.io releases because in the docs https://python-socketio.readthedocs.io/en/latest/intro.html#version-compatibility docs it says below the compatibility table: “Can connect to other Socket.IO servers that are compatible with the JavaScript Socket.IO 1.x and 2.x releases. Work to support release 3.x is in progress.” No valid version combination works with my program, however.

Here is the server code:

from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_cors import CORS

import threading
import time
import random

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
CORS(app)
socketio = SocketIO(app,logger=True, engineio_logger=True)
socketio.on("connection", print("Connected "));
socketio.on("connect_error", lambda err: print("connect_error due to " + err.message));
socketio.on("disconnect", print("Disconnected"));

def emit_floats():
    while True:
        time.sleep(1)  # Emit a float every second. Adjust the timing as needed.
        float_value = random.random()  
        socketio.emit("new_float", {"value": float_value}, namespace="/test")
        print(f"Emitted {float_value}")  #

@app.route('/')
def index():
    return render_template('index.html') 

if __name__ == '__main__':
    # Start the thread that emits floats.
    threading.Thread(target=emit_floats, daemon=True).start()
    socketio.run(app,debug=True)

Here is the html/javascript file:

<!DOCTYPE html>
<html>
<head>
    <title>Flask SocketIO Test</title>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" referrer="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
        var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
        console.log(document.domain + ':' + location.port)
        
        socket.on('connect', function() {
            console.log('Websocket connected!');
        });
        
        socket.on("new_float", function(msg) {
            console.log('Received float: ' + msg.value);
            document.getElementById("floatValue").innerHTML = "Latest Float: " + msg.value;
        });
    </script>
</head>
<body>
    <h1>Flask-SocketIO Float Emitter</h1>
    <div id="floatValue">Latest Float: Waiting for data...</div>
</body>
</html>

The server console says this upon starting up:

$ python server.py
Server initialized for eventlet.
Connected
Disconnected
 * Restarting with stat
Server initialized for eventlet.
Connected
Disconnected
 * Debugger is active!
 * Debugger PIN: 951-349-505
(5132) wsgi starting up on http://127.0.0.1:5000
(5132) accepted ('127.0.0.1', 62020)
gLMwdIe6pi1wsgCJAAAA: Sending packet OPEN data {'sid': 'gLMwdIe6pi1wsgCJAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
127.0.0.1 - - [16/Apr/2024 13:05:42] "GET /socket.io/?EIO=4&transport=polling&t=OxeW-QN HTTP/1.1" 200 278 0.000000
gLMwdIe6pi1wsgCJAAAA: Received packet MESSAGE data 0/test,
gLMwdIe6pi1wsgCJAAAA: Sending packet MESSAGE data 4/test,"Unable to connect"
127.0.0.1 - - [16/Apr/2024 13:05:42] "POST /socket.io/?EIO=4&transport=polling&t=OxeW-ZH&sid=gLMwdIe6pi1wsgCJAAAA HTTP/1.1" 200 219 0.000000
127.0.0.1 - - [16/Apr/2024 13:05:42] "GET /socket.io/?EIO=4&transport=polling&t=OxeW-ZL&sid=gLMwdIe6pi1wsgCJAAAA HTTP/1.1" 200 208 0.001004
emitting event "new_float" to all [/test]
Emitted 0.19877135766801945
(5132) accepted ('127.0.0.1', 62019)
(5132) accepted ('127.0.0.1', 62023)
(5132) accepted ('127.0.0.1', 62024)
gLMwdIe6pi1wsgCJAAAA: Received request to upgrade to websocket
127.0.0.1 - - [16/Apr/2024 13:05:43] "GET /socket.io/?EIO=4&transport=polling&t=OxeW-ZQ&sid=gLMwdIe6pi1wsgCJAAAA HTTP/1.1" 200 181 0.302727
gLMwdIe6pi1wsgCJAAAA: Upgrade to websocket successful
emitting event "new_float" to all [/test]
Emitted 0.7647208741003735
emitting event "new_float" to all [/test]
Emitted 0.004322528800467906

The webpage (localhost:5000) shows this:

localhost:5000

The Network tab on the browser console says (interestingly):

  • First “OK”
  • Then: “44/test,”Unable to connect”
  • Then: “6”
  • Then: Last console->Network message

It appears the request to switch protocols is still “pending”.

I read a post that says Chrome needs wss instead of ws websocket protocol and that I should create a self-signed X.509 certificate and add it to the application, but on the other hand I have a simple node.js/javascript two-way chat program that works just fine with Chrome and no certificate.

So where am I going wrong?

Is there a way to have headers not span the entire row?

I have a Tabulator table that requires six column headers, four of which are in one of two column groups. The remaining two headers do not belong to a column group. I would like to have the two independent column headers be vertically aligned with the other four column headers, but they vertically stretch to match the height of the other headers plus their column group titles.

Here is an image of how I would like the table to look, with the two group headings on their own row:

Image of expected table

This is what I end up with:

Image of actual table

I have read the documentation for column grouping, and looked at the examples provided for their implementation. I have also tried setting CSS styles to reflect what I am hoping to achieve here. I have tried both cell formatters for the header, as well as a row formatter, but to no avail. It seems that Tabulator doesn’t like having any elements outside of the boundaries of a squared-off table.

I am able to add independent HTML elements above the table to mimic this behaviour, but that isn’t the ideal solution. I would rather be able to set some property either at the column level or table level to identify a header row that doesn’t necessarily span the width of the table.

Shopify: How do I edit JavaScript link reference for a button

I’m trying to make some changes to a Request Price button that a previous dev implemented. I’m not a dev myself, just a somewhat savvy user helping out.

The button is supposed to link to the contact page, but has an incorrect preview domain “https://gmcyye5s15ty7xgl-25700171839.shopifypreview.com”. I’m trying to edit this to the correct website domain so that the button functions correctly – see “product_url” and “window.location.replace”.

When I make the changes in the .liquid file the changes are not made live, probably because with JS it has to be recompiled and deployed before it updates. Not sure how to do that in the context of Shopify – usually I click “Save” and whatever I change goes live, so this is a new experience for me.

This is the code in the .liquid file that matches what I see when I “Inspect Element” the button I’m trying to fix.

{% comment %}{%- render ‘product-meta’, product: product, show_description: true -%}{% endcomment %}
{%- render ‘product-meta-ask’, product: product, show_description: true -%}
Request Price

jQuery( document ).ready(function() {
jQuery(‘#set_local_metas’).click(function(){
console.log(“hit”);
localStorage.setItem(“product_name”, “{{ product.title }}”);
localStorage.setItem(“product_url”, “”https://gmcyye5s15ty7xgl-25700171839.shopifypreview.com/products/patek-philippe-minute-repeater-perpetual-calendar-tourbillon-platinum-5316-50p-001″{{ product.url }}”);
setTimeout(function(){
window.location.replace(‘https://gmcyye5s15ty7xgl-25700171839.shopifypreview.com/pages/contact-us’);
}, 2000);
});
});

I tried to edit (in the corresponding .liquid file) the links for “product_url” and “window.location.replace” to use the correct domain name. I expected this to update on the live website, and upon button click, direct the user to the correct Contact Us page instead of https://gmcyye5s15ty7xgl-25700171839.shopifypreview.com/pages/contact-us

I think that if I reloaded the javascript, it might make my changes take effect, but I’m not sure how to do that or what the implications are. This is as far as I’ve gotten, reading this but still not sure how to do it:
Shopify Section doesn’t run javascript after edit

importing jquery in app.js vs bootstrap.js, what’s the difference?

DISCLAIMER: It’s a Laravel app, so the following files are in /resources/js/.

If I do this in app.js:

import jQuery from 'jquery';
window.$ = window.jQuery = jQuery;

it works just fine!

but if I do the same thing in bootstrap.js (which is literally in the same folder as app.js), then I get this error: Could not find a declaration file for module 'jquery'.

( I’m not using typescript )

Why? What’s the difference? What’s the purpose of bootstrap.js then?

How can i add functionality to squares in a grid in JavaScript?

I’ve made a grid using HTML,CSS & JavaScript based mainly on the code on the answer to this question on Stack Overflow “Creating a 16×16 grid using JavaScript”. My problem is that I want to make classes for each individual and I’m not sure that I have done it right. So for example i want to be able to click on an individual square and it console.log what square it is.

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid v2</title>
    <!-- The line below is for CSS -->
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <div id="container">
    </div>

    <!-- The line below is for JavaScript -->
    <script src="index.js"></script>

</body>

</html>

CSS

:root {
    --grid-cols: 1;
    --grid-rows: 1;
  }
  
  #container {
    display: grid;
    grid-template-rows: repeat(var(--grid-rows), 1fr);
    grid-template-columns: repeat(var(--grid-cols), 1fr);
    width: 600px;
    height: 600px;
  }
  
  .grid-item {
    border: 1px solid #ddd;
    text-align: left;
    user-select: none;
    font-family: inter;
  }

JavaScript

:root {
    --grid-cols: 1;
    --grid-rows: 1;
  }
  
  #container {
    display: grid;
    grid-template-rows: repeat(var(--grid-rows), 1fr);
    grid-template-columns: repeat(var(--grid-cols), 1fr);
    width: 600px;
    height: 600px;
  }
  
  .grid-item {
    border: 1px solid #ddd;
    text-align: left;
    user-select: none;
    font-family: inter;
  }

I’ve tried adding the code below to JavaScript but i’m unsure if it works.

    cell.classList.add('cell');
    cell.id = 'cell-${c}'

Can’t pass JSON API Data to Chart JS

Soo i am not so good with fetching data and i am lost and strugling with this couple days now -_- if anyone can help i appreciate it.

My code fetch and read data perfectly fine and pass it to html table but i cant pass it to the Chart… i am confused)

Here is my code

function loadReport() {
    
    var dateFrom = document.getElementById("date1").value.toString();
        var dateTo = document.getElementById("date2").value.toString();
        var apiurl = "<?php echo $user->getFromTable_MyId("integration_api", "users"); ?>";
        var pubID = "<?php echo $user->getFromTable_MyId("id", "users"); ?>";
    
        $.getJSON(apiurl + '&Target=Affiliate_Report&Method=getStats&fields[]=Stat.affiliate_info1&fields[]=Stat.payout&fields[]=Stat.conversions&fields[]=Stat.clicks&filters[Stat.affiliate_info1][conditional]=EQUAL_TO&filters[Stat.affiliate_info1][values]=pop_24&filters[Stat.date][conditional]=BETWEEN&filters[Stat.date][values][]=' + dateFrom + '&filters[Stat.date][values][]=' + dateTo + '&sort[Stat.date]=desc', function(data) {
     //if you want to add more on balance just enter number in value
     
     values9=[0]
     values8=[0]
     values7=[0]
    var data, id, conversion, clicks, payout, statDate = "";
    var id = '';
        var clicks = '';
        var conversion = '';
        var payout = '';
        
    for (i in data.response.data.data) {
        
       const chartDateArr = data.response.data.data[i].Stat.date;
        const chartClicksArr = data.response.data.data[i].Stat.clicks;
        console.log(chartClicksArr);
        const chartConversionsArr = data.response.data.data[i].Stat.conversions;
        const chartPayoutArr = data.response.data.data[i].Stat.payout;
                 
        
        statDate += "<table><tr><td>" + data.response.data.data[i].Stat.date + "</td></tr></table>";
    id += "<table><tr><td>" + data.response.data.data[i].Stat.affiliate_info1 + "</td></tr></table>";
    conversion += "<table><tr><td>" + data.response.data.data[i].Stat.conversions + "</td></tr></table>";
    clicks += "<table><tr><td>" + data.response.data.data[i].Stat.clicks + "</td></tr></table>";
    
    var num9 = parseFloat(data.response.data.data[i].Stat.payout);
    var num8 = parseFloat(data.response.data.data[i].Stat.clicks);
    var num7 = parseFloat(data.response.data.data[i].Stat.conversions);
    
    //This code will use percentage from db and read it here to reduce sum
    var percent = <?php echo '.' . $user->getFromTable_MyId("rev_percentage", "users"); ?>;
    var val = num9 - (num9 * percent);
    //this pushed data to values and calculate total sum
    values9.push(val)
    values8.push(num8)
    values7.push(num7)
    let total9=values9.reduce((acc,curr)=>acc+curr)
    let total8=values8.reduce((acc,curr)=>acc+curr)
    let total7=values7.reduce((acc,curr)=>acc+curr)
    document.getElementById("onLoadConversions").textContent=total7;
    document.getElementById("onLoadClicks").textContent=total8;
    document.getElementById("onLoadsum").textContent='u20AC ' + total9.toFixed(2);
    //#
    //#
    //#
    payout += "<table><tr><td> &euro; " + val.toFixed(2) + "</td></tr></table>";
    
    document.getElementById("statDate").innerHTML = statDate;
    document.getElementById("id_name").innerHTML = id;
    document.getElementById("conversion_name").innerHTML = conversion;
    document.getElementById("clicks_name").innerHTML = clicks;
    document.getElementById("payout_name").innerHTML = payout;
    
    //Chart code START
    if (myChart3) myChart3.destroy(); //this line will avoid chart error when calling  function again
var ctx3 = $("#line-chart").get(0).getContext("2d");
var myChart3 = new Chart(ctx3, {
    type: "line",
    data: {
        labels: chartDateArr,
        datasets: [{
            label: "Revenue",
            fill: false,
            backgroundColor: "rgba(40, 153, 51, .3)",
            borderColor: "rgba(40, 153, 51, .7)",
            data: chartPayoutArr
        },
        {
            label: "Clicks",
            fill: false,
            backgroundColor: "rgba(0, 0, 0, .3)",
            borderColor: "rgba(0, 0, 0, .7)",
            data: chartClicksArr
        },
        {
            label: "Conversion",
            fill: false,
            backgroundColor: "rgba(161, 21, 21, .3)",
            borderColor: "rgba(161, 21, 21, .7)",
            data: chartConversionsArr
        }]
    },
    options: {
        responsive: true
    }
});

//Chart code END
    
};
});
    
    
    
}

Here is SS of results outputs:
chart

table

console