instantiation of object in Javascript by string [duplicate]

I have a bit of code in Javascript:

   class testClass {
        constructor() {
            this.getter = new window["testGetter"]();
        }
    }
    class testGetter {
        constructor() {
            console.log("success");
        }
    }
    var x = new testClass;

When I run it, I get an error “window.testGetter is not a constructor”. Why?

Explanation: This is obvioiusly a very simplified version of what I want to do. It is important to be able to hand in a string with the name, in this case “testGetter”.

I have tried to declare testGetter before testClass, but that didn’t help. Obviously, testClass is instantiated in the last line and the entire code has been loaded into memory.

How can I get my text animation to display?

I’m working on building a website for my CV and I tried to make my homepage a bit more interesting by animation the welcome message. I used https://codepen.io/alvarotrigo/pen/ZEJgqLN this codepen as a reference. When I try importing this into my own file. I get the “Uncaught ReferenceError ReferenceError: $ is not defined. Any help would be greatly appreciated.

var words = ['Welcome to my CV'],
    part,
    i = 0,
    offset = 0,
    len = words.length,
    forwards = true,
    skip_count = 0,
    skip_delay = 15,
    speed = 70;
var wordflick = function () {
  setInterval(function () {
    if (forwards) {
      if (offset >= words[i].length) {
        ++skip_count;
        if (skip_count == skip_delay) {
          forwards = false;
          skip_count = 0;
        }
      }
    }
    else {
      if (offset == 0) {
        forwards = true;
        i++;
        offset = 0;
        if (i >= len) {
          i = 0;
        }
      }
    }
    part = words[i].substr(0, offset);
    if (skip_count == 0) {
      if (forwards) {
        offset++;
      }
      else {
        offset--;
      }
    }
    $('.word').text(part);
  },speed);
};

$(document).ready(function () {
  wordflick();
});
html {
    font-family:system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

body {
    background-color: whitesmoke;
    font-size: 150%;
}

.container {
    padding: 5px;
    margin: 10px;
}

.header {
    display: grid;
}

.navbar {
    display: flex;
    flex-direction: row;
    gap: 100px;
}

.navbar-item {
    font-weight: bold;
    color: black;
}

a {
    text-decoration: none;
    color: inherit;
}

.navbar-item:hover {
    color: orange; 
    transition: 0.3s;
}

.welcome-message {
    text-align: center;
    font-size: 100px;
}

footer {
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Home</title>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>John Smith</h1>
            <div class="navbar">
                <div class="navbar-item"><a href="landing.html">Home</a></div>
                <div class="navbar-item"><a href="about.html">About me</a></div>
                <div class="navbar-item"><a href="education.html">Education</a></div>
                <div class="navbar-item"><a href="experience.html">Experience</a></div>
                <div class="navbar-item"><a href="contact.html">Contact</a></div>
            </div>
        </div>
        <div class="welcome-container">
            <div class="word"></div>
        </div>
    </div>
    <footer>John Smith Smith</footer>
    <script src="main.js"></script>
</body>
</html>

main.js: 44″

TypeScript error with multiple return types

I am using TypeScript to declare the type of some data which is returned from an api call.

If the api call succeeds the data structure looks different than if the api fails.

I declare my types as follows:

interface SubmissionDetails {
  clientAddress1: string
  clientAddress2: string
  clientCity: string
  clientContactEmail: string
  clientContactFullName: string
  clientName: string
  clientState: string
  clientZip: string
  namedInsured: string
  underwriterDisplayName: string
}

  getSubmission: (
    appTypeId: string,
    submissionId: string
  ) => Promise<SubmissionDetails | { message: string }>

So if the api succeeds we get the SubmissionDetails type and if it fails we simply get a message.

I want to set a constant equal to the message value if the api fails.

const errorMessage = submissionDetails.message

However this gives me an error stating:

Property 'message' does not exist on type 'SubmissionDetails | { message: string; }'.
  Property 'message' does not exist on type 'SubmissionDetails'.

I understand that this is telling me message doesn’t exist on SubmissionDetails.

I am wondering if there is a simple way to fix this error so that I can set errorMessage equal to the message when it exists and null or void if it doesn’t exist.

Need to represent given data in grouped bar chart using chart.js and not able to give name to each bar

I have below data sets

const javaData = [
  { name: "NASC-02", type: "Interface", value: 6, bgColor: "red" },
  { name: "NASC-03", type: "Interface", value: 7, bgColor: "green" },
  { name: "NASC-04", type: "Interface", value: 9, bgColor: "blue" },
  { name: "FUNC-01", type: "Function", value: 3, bgColor: "red" },
  { name: "FUNC-02", type: "Function", value: 10, bgColor: "green" },
  { name: "FUNC-03", type: "Function", value: 1, bgColor: "blue" },
];

I want to create a grouped bar chart using Chart.js. The x-axis should represent the type of object, which in this case are “Interface” and “Function”. Each bar’s value and color should be determined by the respective object.

I have successfully created the grouped chart using the provided data. However, I’m facing difficulty in assigning names to each bar. Specifically, I want the name of each bar in the “Interface” group to correspond to the names “NASC-02”, “NASC-03”, etc., and in the “Function” group to correspond to “FUNC-01”, “FUNC-02”, etc.

i can change the format of data from backend also in if required

    var javaData = {
  "Interface": {
    "NASC-01": 2,
    "NASC-02": 5,
    "NASC-03": 8
  },
  "Function": {
    "FUNC-01": 20,
    "FUNC-02": 25,
    "FUNC-03": 18
  }
};

below is the code i have tried using array format data given above graph is coming properly but not able to give name to each bar

    <!DOCTYPE html>
<html>
<head>
  <title>Defect Closure Duration by Type</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
</head>
<body>
  <canvas id="defectChart" width="600" height="300"></canvas>

  <script>
    var javaData = [
      { name: "NASC-02", type: "Interface", value: 6, bgColor: "red" },
      { name: "NASC-03", type: "Interface", value: 7, bgColor: "green" },
      { name: "NASC-04", type: "Interface", value: 9, bgColor: "blue" },
      { name: "FUNC-01", type: "Function", value: 3, bgColor: "red" },
      { name: "FUNC-02", type: "Function", value: 10, bgColor: "green" },
      { name: "FUNC-03", type: "Function", value: 1, bgColor: "blue" },
    ];
    

    // Group data by month
    const groupedData = javaData.reduce((acc, item) => {
      if (!acc[item.type]) {
        acc[item.type] = {};
      }
      acc[item.type][item.name] = item.value;
      return acc;
    }, {});

    // Extract labels and values for each month
    const labels = Object.keys(groupedData);
    const interfaceValues = Object.values(groupedData["Interface"]);
    const functionValues = Object.values(groupedData["Function"]);
    
    const datas = [];

   for (let i = 0; i < interfaceValues.length; i++) {
    datas.push([interfaceValues[i], functionValues[i]]);
   }

const dataset = datas.map((data, index) => {
    return {
        data: data,
        backgroundColor: index === 0 ? 'rgba(255, 99, 132, 0.2)' : 'rgba(54, 162, 235, 0.2)',
        borderColor: index === 0 ? 'rgba(255, 99, 132, 1)' : 'rgba(54, 162, 235, 1)',
        borderWidth: 1
    };
});

    var ctx = document.getElementById("defectChart").getContext("2d");
    var chart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: dataset
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  </script>
</body>
</html>

Below is the screen the way i need bar name
enter image description here

In Postman how can I edit the request name from the “Tests” tab using javascript?

I have a collection with requests. But I might have multiple requests with the same name, so I would like the ability to edit the request name from the “Tests” tab (perhaps by adding a sequence number to the beginning of the request name).

For example…

Test collection:

  • Logon
  • Clear All Subscribers
  • Create Subscriber
  • Create Subscriber
  • Logout

Then I run the collection that then executes the code in the “Tests” tab.
And now the collection looks like this…

Test collection:

  • 1 Logon
  • 2 Clear All Subscribers
  • 3 Create Subscriber
  • 4 Create Subscriber
  • 5 Logout

Now one can differentiate between the two “Create Subscriber” requests because their request names are now “3 Create Subscriber” and “4 Create Subscriber”.

I get that in this example it would be easy to just manually edit the request names. But in practice my collection will have 100’s of requests so doing it manually is not viable.

I looked at the pm.info.requestName function but it’s a read-only.

Why is my Alert component triggering multiple times?

This is my React Native code.

import React, { useState, useEffect } from 'react';
import { Alert, View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView, ImageBackground, Dimensions, TextInput } from 'react-native';
import * as Brightness from 'expo-brightness';

const {height, width} = Dimensions.get('window');

const styles = StyleSheet.create({
  //styles
});

const DisplayLogo = () => {
  const [showSeparatePage, setShowSeparatePage] = useState(false);
  const [showWeatherPage, setShowWeatherPage] = useState(false);
  const [showBuyImplementsPage, setShowBuyImplementsPage] = useState(false);
  const [showSellHarvestPage, setShowSellHarvestPage] = useState(false);
  const [showAudioPodcastsPage, setShowAudioPodcastsPage] = useState(false);
  const [showDonatePage, setShowDonatePage] = useState(false);
  const [showFeedbackPage, setShowFeedbackPage] = useState(false);
  const [showBackButton, setShowBackButton] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [contact, setContact] = useState(false);
  const [settingsMenu, setSettingsMenu] = useState(false);
  const translateY = new Animated.Value(700);
  const logoOpacity = new Animated.Value(1);
  const buttonOpacity = new Animated.Value(0);
  const backgroundColor = new Animated.Value(0);
  const showHelpDialog = () => {
    setModalVisible(true);
  };
  const hideHelpDialog = () => {
    setModalVisible(false);
    handleBackButtonPress();
  };
  const showContactDialog = () => {
    setContact(true);
  };
  const hideContactDialog = () => {
    setContact(false);
    handleBackButtonPress();
  };

  useEffect(() => {
    const logoAnimation = Animated.sequence([
      Animated.timing(translateY, {
        toValue: 250,
        duration: 1000,
        useNativeDriver: true,
        easing: Easing.inOut(Easing.ease),
      }),
      Animated.delay(2000),
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: -50,
          duration: 1000,
          useNativeDriver: true,
          easing: Easing.inOut(Easing.ease),
        }),
        Animated.timing(logoOpacity, {
          toValue: 0,
          duration: 1000,
          useNativeDriver: true,
        }),
      ]),
    ]);

    const buttonsAnimation = Animated.timing(buttonOpacity, {
      toValue: 1,
      duration: 500,
      delay: 500,
      useNativeDriver: true,
    });

    Animated.sequence([logoAnimation, buttonsAnimation]).start();

    setTimeout(() => {
      Animated.timing(backgroundColor, {
        toValue: 1,
        duration: 500,
        useNativeDriver: false,
      }).start();
    }, 3000);

    return () => {
      translateY.setValue(500);
      logoOpacity.setValue(1);
      buttonOpacity.setValue(0);
      backgroundColor.setValue(0);
    };
  }, [showSeparatePage, showWeatherPage, showBuyImplementsPage, showSellHarvestPage, showAudioPodcastsPage, showDonatePage, showFeedbackPage, modalVisible, settingsMenu, contact]);

  const handleTipsForFarmingPress = () => {
    setShowSeparatePage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleWeatherReportPress = () => {
    setShowWeatherPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleBuyImplementsPress = () => {
    setShowBuyImplementsPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleSellHarvestPress = () => {
    setShowSellHarvestPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleAudioPodcastsPress = () => {
    setShowAudioPodcastsPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleDonatePress = () => {
    setShowDonatePage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleFeedbackPress = () => {
    setShowFeedbackPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleBackButtonPress = () => {
    setShowSeparatePage(false);
    setShowWeatherPage(false);
    setShowBuyImplementsPage(false);
    setShowSellHarvestPage(false);
    setShowAudioPodcastsPage(false);
    setShowDonatePage(false);
    setShowFeedbackPage(false);
    setModalVisible(false);
    setContact(false);
    setSettingsMenu(false);
    setShowBackButton(false);
    Animated.timing(buttonOpacity, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 1,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };

  if (showSeparatePage) {
    return (
      //returns something
    );
  }
  if (showWeatherPage) {
    return (
      //returns something
    );
  }
  if (showBuyImplementsPage) {
    return (
        //returns something
    );
  }
  if (showSellHarvestPage) {
    return (
        //returns something
    );
  }
  if (showAudioPodcastsPage) {
    return (
        <//returns something
    );
  }
  if (showDonatePage) {
    return (
        //returns something
    );
  }
  if (showFeedbackPage) {
    return (
        //returns something
    );
  }
  if (modalVisible) {
    Alert.alert(
      'Help',
      "Click buttons and navigate throughout the platform.",
      [
        { text: 'OK', onPress: () => {
          hideHelpDialog();
          handleBackButtonPress();
        }}
      ],
      { cancelable: false }
    );
  }
  //The bug occurs in the below Alert component.
  if (settingsMenu) {
    console.log("Alert");
      Alert.alert("Settings","Set brightness.",
      [
        {text:"High Brightness", onPress: () => {
          Brightness.setBrightnessAsync(1);
          handleBackButtonPress();
        }},
        {text:"Medium Brightness", onPress: () => {
          Brightness.setBrightnessAsync(0.4);
          handleBackButtonPress();
        }},
        {text:"Low Brightness", onPress: () => {
          Brightness.setBrightnessAsync(0.2);
          handleBackButtonPress();
        }}
      ],
      { cancelable: false }
    );
  }
  if (contact) {
    Alert.alert(
      'Contact',
      "Call Centre Number: 1234567890",
      [
        { text: 'OK', onPress: () => {
          hideContactDialog();
          handleBackButtonPress();
        }}
      ],
      { cancelable: false }
    );
  }

  return (
    <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
      <Animated.View style={{ ...styles.container, backgroundColor: backgroundColor.interpolate({
        inputRange: [0, 1, 2],
        outputRange: ['white', 'skyblue', 'orange'],
      }) }}>
        <Animated.Image
          style={{
            ...styles.logo,
            transform: [{ translateY }],
            opacity: logoOpacity,
          }}
          source={require('./assets/Logo.png')}
        />

        <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
          {/* Yellow buttons */}
          {['Tips For Farming', 'Weather Updates', 'Buy Implements', 'Sell Harvest', 'Audio Podcasts', 'Donate'].map(
            (buttonName, index) => (
              <TouchableOpacity
                key={index}
                style={{ ...styles.button, ...styles.yellowButton }}
                onPress={() => {
                  if (buttonName==='Tips For Farming') {
                    handleTipsForFarmingPress()}
                  if (buttonName==='Weather Updates') {
                    handleWeatherReportPress()}
                  if (buttonName==='Buy Implements') {
                    handleBuyImplementsPress()}
                  if (buttonName==='Sell Harvest') {
                    handleSellHarvestPress()}
                  if (buttonName==='Audio Podcasts') {
                    handleAudioPodcastsPress()}
                  if (buttonName==='Donate') {
                    handleDonatePress()}
                  }
                }
              >
                <Text style={styles.buttonText}>{buttonName}</Text>
              </TouchableOpacity>
            )
          )}

          {/* Gray buttons */}
          <View style={{ flexDirection: 'row' }}>
            {['Help', 'Settings'].map((buttonName, index) => (
              <TouchableOpacity
                key={index}
                style={{ ...styles.button, ...styles.grayButton, marginLeft: 10 }}
                onPress={() => {
                  if (buttonName==='Help') {
                    showHelpDialog();}
                  if (buttonName==='Settings') {
                    setSettingsMenu(true);}
                }
              }
              >
                <Text style={styles.buttonText}>{buttonName}</Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Orange button */}
          <TouchableOpacity
            style={{ ...styles.button, ...styles.orangeButton }}
            onPress={() => handleFeedbackPress()}
          >
            <Text style={styles.buttonText}>Return Feedback</Text>
          </TouchableOpacity>

          {/* Green button */}
          <TouchableOpacity
            style={{ ...styles.button, ...styles.greenButton }}
            onPress={() => showContactDialog()}
          >
            <Text style={styles.buttonText}>Contact</Text>
          </TouchableOpacity>
        </Animated.View>
      </Animated.View>
    </ScrollView>
  );
};

export default DisplayLogo;

Basically, when the Settings button is clicked, a dialog box appears. When I choose an option, the dialog box reappears, sometimes twice or thrice.

This bug is not occurring with the other Alert components. Also, when a dialog box appears, the logo of my app animates in the background (which should only happen when the app starts). I don’t want the Alert component to trigger continuously. Please help.

Trying to set cookie from server side but not set on my client browser

I am trying to set cookie on my client browser from server side.
Using nodejs and express.

when I try to signup the the cookie sent properly in my response object. But it is not set on my client browser. And when I try to use my protected api which requires token then its also not sent to server automatically even it is on same site.

This si my serverside code.

const signup = async (req, res) => {
  try {
    const user_exist = await users.findOne({ username });

    if (user_exist) {
      res.status(201).json({
        code: 0,
        message: "Account already exist with this usename."
      });
      return;
    }

    const hash_password = await encrypt_password(password);

    const user = new users({
      full_name,
      username,
      password: hash_password,
      profile: gender === "Male" ? boy_profile : girl_profile,
      gender
    });

    const save = await user.save();

    const token = jwt.sign(
      {
        id: save._id,
        username: save.username,
        profile: save.profile,
        gender: save.gender
      },
      process.env.SECRET_KEY,
      { expiresIn: "30d" }
    );

    res.cookie("token", token, {
      maxAge: 30 * 24 * 60 * 60 * 1000,
      httpOnly: true,
      secure: false,
      sameSite: "Strict"
    });

    res.status(200).json({
      code: 1,
      message: "User created successfully.",
      data: save
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      code: 0,
      message: "Internal Server Error."
    });
  }
};

My response object is

enter image description here

My cookie inside dev tool

enter image description here

Unable to Preview Expo React Native in IOS/Android

Unable to resolve module ./_getAllKeys from D:GithubIT FundamentalitlearningBootcamp10front-end_akhirnode_moduleslodash_equalObjects.js:

None of these files exist:

  • node_moduleslodash_getAllKeys(.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.mjs|.native.mjs|.mjs|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json|.ios.cjs|.native.cjs|.cjs|.ios.scss|.native.scss|.scss|.ios.sass|.native.sass|.sass|.ios.css|.native.css|.css)
  • node_moduleslodash_getAllKeysindex(.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.mjs|.native.mjs|.mjs|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json|.ios.cjs|.native.cjs|.cjs|.ios.scss|.native.scss|.scss|.ios.sass|.native.sass|.sass|.ios.css|.native.css|.css)

1 | var getAllKeys = require(‘./_getAllKeys’);
| ^
2 |
3 | /** Used to compose bitmasks for value comparisons. */
4 | var COMPARE_PARTIAL_FLAG = 1;

RCTFatal
RCTConvertArrayValue
C49A5FC2-C873-3913-9603-004F5D0175E7
C49A5FC2-C873-3913-9603-004F5D0175E7
C49A5FC2-C873-3913-9603-004F5D0175E7
_dispatch_main_queue_callback_4CF
5A6C1F41-BF70-32F6-A1D6-5B894DD21362
5A6C1F41-BF70-32F6-A1D6-5B894DD21362
CFRunLoopRunSpecific
GSEventRunModal
6398DDD4-EA36-31CD-B849-2F6217205BED
UIApplicationMain
main
28D6D2C1-46CE-3D58-B744-B06A6C573888

I just wanna to load preview in IOS/Android using Expo, but end up only able to load in Web

Zustand store is not updated on URL change

I have a Zustand store connected to the URL. Look at the code below.

import { create } from "zustand";
import { persist, StateStorage, createJSONStorage } from "zustand/middleware";

const pathStorage: StateStorage = {
  getItem: (key): string => {
    const pathname = window.location.pathname;
    const p = pathname.split("/").filter(Boolean)[3];
    return p;
  },
  setItem: (key, newValue): void => {
    const slug = JSON.parse(newValue).state.tab;
    const oldSlug = window.location.pathname.split("/").filter(Boolean)[3];
    const newUrl = `/fsd/sdet/class-structure/${slug}`;
    if (oldSlug) {
      window.history.replaceState(null, "", newUrl);
    } else {
      window.history.pushState(null, "", newUrl);
    }
  },
  removeItem: (key): void => {
  },
};

export const useStore = create<{
  tab: string;
  setTab: (tab: string) => void;
}>()(
  persist(
    (set, get) => ({
      tab: "",
      setTab: (tab: string) => set({ tab }),
    }),
    {
      name: "tab-storage",
      storage: createJSONStorage(() => pathStorage),
    },
  ),
);

When I use browser back/forward buttons, the URL is changed, but store is not updated automatically.

Anyone who can help? I use Next.js 14, React 18 and Zustand 4.5.

Multiple select box not working in dynamically appended HTML using jQuery

I’m encountering an issue with dynamically appending HTML content containing a multiple select box using jQuery. While my multiple select box works fine in static HTML, it fails to function correctly when added dynamically.

I have a scenario where I’m dynamically appending HTML content to my page using jQuery. This content includes a element with the multiple attribute to enable multiple selections. However, despite using the appropriate jQuery plugin (selectpicker), the multiple select box fails to work as expected when appended dynamically.

$(document).ready(function() {
var i = 10000;
$('.add_nested_fields').on('click', function() {
    var appendHtml = '';
    appendHtml += '<div class="col-12 col-md-6 pl-md-1 col-xl-6 pl-xl-1">';
    appendHtml += '<label style="font-family: "Axiforma", sans-serif;" class="control-label bill-lable d-inline-block" for="vehicle_category">';
    appendHtml += 'Vehicle Category';
    appendHtml += '<span class="contactsvg">';
    appendHtml += '<svg xmlns="http://www.w3.org/2000/svg" width="14.259" height="10.091" viewBox="0 0 14.259 10.091" style="margin-top: 2px;">';
    // SVG code truncated for brevity
    appendHtml += '</select>';
    appendHtml += '</div>';

    // Appending the HTML content
    // [Insert code for appending here]
});

});

I’ve verified that the selectpicker plugin is correctly loaded and applied to existing select boxes in the static HTML.
The car_types variable in the PHP loop is correctly populated with data.
I suspect there might be an issue with initializing the selectpicker plugin on dynamically appended HTML elements.

I’ve verified that the selectpicker plugin is correctly loaded and applied to existing select boxes in the static HTML.
The car_types variable in the PHP loop is correctly populated with data.
I suspect there might be an issue with initializing the selectpicker plugin on dynamically appended HTML elements.

What I’ve Tried:

I’ve tried manually refreshing the selectpicker plugin using the refreshSelectpicker function after appending the HTML content, but it didn’t resolve the issue.
I’ve also ensured that the necessary CSS and JavaScript files for the selectpicker plugin are included in the page.

Request for Assistance:

I’m seeking guidance on how to ensure that the selectpicker plugin works correctly on dynamically appended HTML elements. Any insights or suggestions would be greatly appreciated.

Thank you!

How to Identify and Compare Changed Fields in TypeScript Objects with Nested Structures?

I’m working on a TypeScript project where I need to compare two objects with potentially nested structures and identify the fields that have changed between them. For instance, consider an old object oldObject with fields like name, age, city, friends (an array), and possibly nested objects within. Now, I have a new object newObject with the same structure, but with potentially updated values for some fields.

Here’s an example:

const oldObject = { name: 'John', age: 30, city: 'New York', friends: ['ali', 'qasim'], def: { 'a': 1, 'b': 2 } };
const newObject = { name: 'John', age: 35, city: 'New York', friends: ['ali', 'haider'] };

In this scenario, I need to be able to identify and extract the changed fields between oldObject and newObject, along with their new values, retaining the nested structure.

I’ve attempted a comparison function, but it’s not correctly handling nested structures and arrays. How can I implement a solution in TypeScript that accurately identifies the changed fields while preserving the nested structure of the objects?

  • I’m looking for a TypeScript function or approach that can accurately identify changed fields between two objects with nested structures.
  • The function should correctly handle nested objects and arrays, identifying changes within them.
  • The solution should be efficient and scalable for objects of varying sizes and complexities.
  • Any insights or improvements on the provided sample function would be greatly appreciated.
  • Clear explanations and examples would be helpful for better understanding and implementation.

In a WordPress installation, JQuery simple script does not seem to work

I have a wordpress website and i want to add a class “myclass” to all anchor elements with JQuery.
This wordpress installation does not have any plugin enabled, so its a default installation.

I enqueue TEST.js file with the following command at the bottom of the functions.php file of my theme (Hello Elementor)

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script('jquery'); // Explicitly telling wordpress to load jquery
    wp_enqueue_script(
        'fixamea', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/TEST.js', // this is the location of your script file
        array('jquery')
    );
}

And the file TEST.js is the following

jQuery(document).ready(function($){
    
    $('a').addClass('myclass');
    console.log("running");


})

The console log “running” appears but the class ‘myclass’ is not added to any Anchor elements.
What could be wrong?

How to preload an image wrapped in a v-if statement?

I have a dialog wrapped in a v-if statement. Inside of this v-if, there is an image.
The problem is that when the dialog opens, it retrieves the image. I would like to preload the image when the page opens, so there is no request when I open the dialog.

How can I preload this image (I do not want to use a v-show)?

Example:

<template>
  <div v-if="toggled">
    <img :src="~/assets/icons/close.svg" alt="Close" height="20" />
  </div>
</template>

php server returns error status 500 when performing SQL Insert Statements not when performing SQL SELECT statement

I have created the backend with php, it uses GET to receive an action (tells the server which query to run) and data (any data that is used in the SQL statements). This is connected to a react native front end where the data is then displayed.

When I do the SELECT statemetns it works fine, however when I do UPDATE or INSERT statements the server returns error status 500 and I cannot figure out why. I suspect it is something to do with the error handling but if the the SQL query returns nothing why does it return an error rather than just returning nothing?

I have tried chaning the error handling on both the backend php server as well as how errors are handled on the front end.

php code:

<?php

include "databaseConnect.php";
$connected = mysqli_connect($servername, $username, $password, $dbname);

if (!$connected) {
    die("Connection failed: " . mysqli_connect_error());
}

$sqlQueryData = array();

$inputWord = $_GET['action'];
$data = $_GET['data'];

try {
    if ($inputWord == "reminders") {
        $query = "SELECT * FROM reminders WHERE reminderCompleted = '0' ORDER BY reminderDueDate DESC";
    } else if ($inputWord == "completedReminders") {
        $query = "SELECT * FROM reminders WHERE reminderCompleted = '1' ORDER BY reminderDueDate DESC";
    } else if ($inputWord == "fieldBlockCheck") {
        $query = "SELECT fieldBlock FROM fields WHERE fieldName = '{$data}'";
    } else if ($inputWord == "addReminder"){
        $decodedData = json_decode($data, true);
        $query = "INSERT INTO reminders (reminderTitle, reminderDueDate, reminderFieldBlock, reminderCompleted, reminderCreatedBy, reminderCompletedBy)
        VALUES ('{$decodedData['reminderTitle']}','{$decodedData['reminderDueDate']}','{$decodedData['reminderFieldBlock']}','0','{$decodedData['userLoggedIn']}','n/a')";
    } else if ($inputWord == "fieldList"){    
        $query = "SELECT fieldName FROM fields";
    } else if ($inputWord == "markReminderAsDone") {
        $decodedData = json_decode($data, true);
        $query = "UPDATE reminders SET reminderCompleted = '1', reminderCompletedBy = '{$decodedData['userLoggedIn']}' WHERE reminderId = '{$decodedData['reminderId']}'";
    } else  { 
        $query = "SELECT * FROM reminders WHERE reminderCompletedBy = 'Harry'";
    }

    $result = mysqli_query($connected, $query);

    if ($result) {
        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $sqlQueryData[] = $row;
            }
        }

        echo json_encode($sqlQueryData);
    } else {

        http_response_code(500);
        echo json_encode(["error" => "Query failed: " . mysqli_error($connected)]);
    }
} catch (Exception $e) {

    http_response_code(500);
    echo json_encode(["error" => "Internal Server Error: " . $e->getMessage()]);
} finally {
    mysqli_close($connected);
}
?>

connection to the front end in react native:

export const fetchData = async (query, data) => {
  let urlWithParams; 
  try {
      const apiUrl = 'server url';
      const queryParams = `action=${encodeURIComponent(query)}&data=${encodeURIComponent(data)}`;
      urlWithParams = `${apiUrl}?${queryParams}`;  

      console.log("Query " + query);
      console.log("Data " + data);
      
      const response = await fetch(urlWithParams);
      if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
      }
      const result = await response.json();
      console.log("What comes back", typeof result);
      return result;

  } catch (error) {
      console.error(`Error fetching data from ${urlWithParams}:`, error);
      throw error;
  }
};