Ajax filter for categories in WordPress

I’m building a site with WordPress. I’ve created a filter with the default category to display the posts. The filter uses checkboxes, so the user can select one or multiple categories.

The issue is, when I select a category it displays all the posts. I’m not sure from where comes the problem, the Ajax handler or the Javascript.

I would also like that when none of the category is selected, it displays all the posts.

The PHP filter:

<?php
if( $terms = get_terms( array( 'taxonomy' => 'category', 'parent' => 0, 'hide_empty' => true ) ) ) :

    echo '
    <form data-ajax-url="'. get_site_url()  .'/wp-admin/admin-ajax.php" method="POST" id="filter" class="js-filter">
        <ul class="js-filter-list">';

            foreach( $terms as $term ) :

                $term_id = $term->term_id;
                $term_name = $term->name;
                $term_slug = $term->slug;

                $term_color = get_term_meta( $term_id, 'post-category-settings__color', true );

                echo '
                <li class="js-filter-item js-filter-term" data-slug="'. esc_attr( $term_slug ) .'">
                    <input type="checkbox" class="c-filter__check" id="' . esc_attr($term_id) . '" name="' . esc_attr($term_id) . '" />
                    <label class="semi-medium" for="' . esc_attr($term_id) . '"><span></span>' . esc_html($term_name) . '</label>
                </li>';
            endforeach;

    echo '
        </ul>
        <input type="hidden" name="action" value="filterpost">
    </form>';
endif;
?>

<div class="js-container"></div>

The JS:

if (document.querySelector('.js-filter')) {
    const ajax_url = document.querySelector(".js-filter").dataset.ajaxUrl;
    let filterBtn = document.querySelectorAll('.js-filter-term');

    var i;
    for( i = 0; i < filterBtn.length; i++ ){
        filterBtn[i].addEventListener('change', function(){

            const containerTerm = document.querySelector(".js-container");
            const data = new FormData();

            let term_slug = this.dataset.slug;

            data.append( 'action', 'filterpost' );
            data.append( 'category', term_slug );

            fetch(ajax_url, {
            method: "POST",
            body: data
            })
            .then((response) => response.text())
            .then((data) => {
            if (data) {
                containerTerm.innerHTML=data;
            }
            })
            .catch((error) => {

            });
        });
    };
}

The AJAX handler:

<?php
function site_filter_post() {

    if( $terms = get_terms( array( 'taxonomy' => 'category' ) ) ) :
        $terms_list = array();

        foreach( $terms as $term ) {
        if( isset( $_POST[$term->term_id ] ) && $_POST[$term->term_id] == 'on' )
         $terms_list[] = $term->slug;
        }
    endif;

    $tax_query = array( 'relation' => 'AND' );
  
    if ( ! empty( $terms_list ) ) {
        $tax_query[] = array(
            array(
            'taxonomy'      => 'category',
            'field'         => 'slug',
            'terms'         => $terms_list,
            )
        );
    }
  
    $args = array(
        'post_type'         => 'post',
        'posts_per_page'    => -1,
        'post_status'       => 'publish',
        'orderby'           => 'date',
        'tax_query' => array(
            $tax_query
        )
    );

    $query = new WP_Query( $args );
  
    if($query->have_posts()) {

        while($query->have_posts()) : $query->the_post();

            get_template_part( 'template-parts/content', 'archive' );
  
        endwhile;
  
    } else {

        echo 'No result.';

    }
  
    exit;
}
add_action('wp_ajax_filterpost', 'site_filter_post');
add_action('wp_ajax_nopriv_filterpost', 'site_filter_post');
?>

Thank you.

Why use a createElement-like function in vanilla JavaScript instead of innerHTML or insertAdjacentHTML? [duplicate]

I’m working on a project with vanilla JavaScript and am wondering about the best way to dynamically create and manage DOM elements.

I know that in libraries like React, JSX is transformed into React.createElement calls behind the scenes, which generates elements using something like this:

React.createElement("div", { className: "my-class" }, "Hello World")
In vanilla JavaScript, I could write a similar function to create DOM elements programmatically. However, I’m wondering why I should bother doing this when I can just use innerHTML or insertAdjacentHTML with template literals for a much simpler approach.

For example:
document.body.innerHTML = Hello World;

What are the advantages of using a createElement-like function over innerHTML or insertAdjacentHTML for DOM manipulation? Is there a performance benefit, security reason, or best practice for larger applications that I should be aware of?

How to track the values of variables in JavaScript recursion

Good day. I have a challenge when it comes to tracking how parameter values change in JavaScript recursion. Attached is a JavaScript function “createPartitions()” that determines the possible combinations of the sum of integers that make up a particular number (e.g. 4 => 1111, 121, 22, 13, 4). The code is succinct but I have added console.log() at specific points to capture how the parameter values change for every cycle.

The first 8 cycles are pretty straightforward with maxValue decreasing by 1 and then target later reducing by 1. The challenge for me starts from the 10th line (where target begins to increase by 1), all the way to the end. Please try to shed light on how the arguments target and maxValue change values in the recursion

let i=0;
function createPartitions(target, maxValue, suffix, partitions) {
  i++;
  if (target == 0) {
    console.log("A :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
    partitions.push(suffix);
  } else {
    if (maxValue > 1) {
      console.log("B :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
      createPartitions(target, maxValue-1, suffix, partitions);
    }
    if (maxValue <= target) {
      console.log("C :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
      createPartitions(target-maxValue, maxValue, [maxValue, ...suffix], partitions);
    }
    console.log("D :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
  }
  console.log("E : " + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
}

const partitions = [];
createPartitions(4, 4, [], partitions);
console.log(partitions);
// console.log(i);

Here are the screenshots of the log. The 10th line (marked by red border) is where it starts to get tricky for me.

enter image description here

enter image description here

Inconsistent PCM audio data captured from the same video using AudioWorkletNode

I’m trying to capture audio data from a YouTube video using the Web Audio API. My goal is to save the raw audio in PCM format while the video is playing. However, I’m noticing inconsistencies in the captured audio data across different runs for the same video. While most of the audio data remains consistent, certain sections (e.g., the beginning, middle, or end) show differences, even when no changes are made to the video playback.

Interestingly, when these audio files are played, there is no perceptible difference in the listening experience. However, the binary data of the captured audio differs across runs, and this is causing issues for my use case where consistency in raw data is critical.

What I’m Doing:
I’m using an AudioContext, an AudioWorkletNode, and a MediaStreamDestination to capture the audio

Environment
Browser: Chrome
Audio API: Web Audio API
PCM Format: Float32, mono channel

I have developed a browser extension with simple start and stop buttons for recording. Additionally, the recording automatically stops when the video finishes playing.

content.js

let audioContext;
let audioWorkletNode;
let audioChunks = [];
let isRecording = false;

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
 
  if (message.type === 'start-recording') {
   startRecording();
  }
  if (message.type === 'stop-recording') {
    stopRecording();
    console.log('Recording stopped.');
  }
});

async function startRecording() {
    try {
        // Select the video element
        const videoElement = document.querySelector('video');
        audioChunks = [];
        monitorVideo(videoElement);
        if (!videoElement) {
            throw new Error('No video element found!');
        }

        // Capture the audio stream
        const stream = videoElement.captureStream();
        if (!stream) {
            throw new Error('Failed to capture audio stream!');
        }

        // Initialize AudioContext
        audioContext = new AudioContext();

        // Add an AudioWorkletProcessor for audio processing
        await audioContext.audioWorklet.addModule(chrome.runtime.getURL('processor.js'));

        // Create an AudioWorkletNode
        audioWorkletNode = new AudioWorkletNode(audioContext, 'audio-processor');

        // Connect the audio stream to the AudioContext
        const source = audioContext.createMediaStreamSource(stream);
        source.connect(audioWorkletNode).connect(audioContext.destination);

        // Collect audio chunks from AudioWorkletProcessor
        audioWorkletNode.port.onmessage = (event) => {
            if (event.data.type === 'chunk') {
                audioChunks.push(event.data.chunk);
            }
        };

        // Start the AudioContext
        await audioContext.resume();
        isRecording = true;

        console.log('Recording started...');
    } catch (error) {
        console.error('Failed to start recording:', error);
    }
    
function stopRecording() {
    if (!isRecording) {
        console.warn('No recording in progress.');
        return;
    }
    isRecording = false;

    // Stop the audio context
    if (audioWorkletNode) {
      audioWorkletNode.disconnect();
      audioContext.close();
  }
   
    if (audioChunks.length > 0) {    
      savePCMFile(audioChunks);
      console.log('Recording stopped and saved');
  }

  

    console.log('Recording stopped and file saved.');
}

// Function to save PCM data as a binary file
function savePCMFile(pcmBuffer) {
   // Flatten the chunks into one Float32Array
   const totalLength = pcmBuffer.reduce((sum, chunk) => sum + chunk.length, 0);
   const combinedArray = new Float32Array(totalLength);

   let offset = 0;
   for (const chunk of pcmBuffer) {
       combinedArray.set(chunk, offset);
       offset += chunk.length;
   }

   // Create a Blob from the combined Float32Array
   const blob = new Blob([combinedArray.buffer], { type: 'application/octet-stream' });
   const url = URL.createObjectURL(blob);

   // Trigger download
   const a = document.createElement('a');
   a.href = url;
   a.download = 'audio.pcm';
   a.click();
}``

audio-processor.js

class AudioProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.audioChunks = [];
}

    process(inputs, outputs, parameters) {
        const input = inputs[0]; // Get the first channel's input
        if (input && input.length > 0) {
            const channelData = input[0]; // First channel's audio data
            this.port.postMessage({
                type: 'chunk',
                chunk: channelData.slice(0), // Copy the audio data
            });
        }
    
        // Return true to keep processing
        return true;
    }

}

registerProcessor('audio-processor', AudioProcessor);

Beyond Hex Compare

How to catch all errors that are thrown asyncronously in a Promise

The problem I am facing is that somewhere in the code I am working with there is an error that I cannot catch. The simplest example of this would be the code below:

try {
    new Promise((res, rej) => rej(new Error('You cannot catch me. Haha')));
} catch (err) {
    conosle.error(err);
}

Result in the console

I don’t want to alter the code much. I want to be able to catch and ignore some errors like that. I am trying to replace Promise by wrapping it so that i can catch all errors of that sort.

I have tried asking ChatGPT and it doesn’t help much, so Googling will most probably not help also.

Please Help me with Aligning the Site Content with the NavBar

I hope that you all are having a beautiful day.

I am trying to design a portfolio website using HTML/CSS and JS. I am done with the animations, switching to a navigation bar, and the website’s general design. When I wanted to add some content to my website as text, I saw that the div with the website content expanded to the top of the webpage and went through the navbar.

How I want it to behave is that the div will always start aligned centered and below the navbar itself. I know I have to do something with the relative positioning, but I am unsure how. At the same time, my div should expand down as much as needed so that I can scroll through the website. While trying to fix this, the div became scrollable rather than covering the whole page and making it scrollable.

I hope that someone can help me with this. Thank you so much.

Best wishes.

This is my current code:
https://codepen.io/dderingezgin/pen/LEPBNLj?editors=1000

This might be the specific problematic part

.sub-section {
            display: none;
            position: relative;
            top: 40%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80%;
            background-color: transparent;
            color: inherit;
            padding: 2rem;
            box-sizing: border-box;
            text-align: center;
            border: 1px solid currentColor;
            opacity: 0;
        }

.sub-section.active {
            display: block;
            animation: fade-in 0.8s ease forwards;
        }

I tried to make the div scrollable –> It ‘literally’ made the div scrollable not expand it.
I tried to make the div go behind the nav-bar –> it literally went behind it, but not completely scrollable.

How to loop over tags and messages while maintaining a single WebSocket connection?

I am trying to set up WebSocket connections in a way where I only connect to the WebSocket URL once and loop over my tags, uid, and messages. However, my current implementation doesn’t work as expected.

Here is my current code:

 setupWebSockets() {
    const baseConfig = {
     url: CONFIG.WS_URL,
     ...CONFIG.WS_MESSAGE
    };

    this.tags.forEach(tag => {
     const uid =generateUID(); 
     const wsClient = new WebSocketClient(baseConfig.url, {
      ...baseConfig,
      uid,
      tag
     });
     wsClient.setOnMessageCallback((event) => this.handleWebSocketMessage(event, tag));
     wsClient.connect();
     this.wsClients[tag] = wsClient;
    });
}

handleWebSocketMessage(event, tag) {
    try {
        const receivedData = JSON.parse(event.data);
        console.log(`Received WebSocket data for ${tag}:`, receivedData);

        if (receivedData.measurements && receivedData.measurements.length > 0) {
            const formattedMeasurements = receivedData.measurements.map(measurement => ({
                time: this.wsClients[tag].convertTimestamp(measurement.time),
                value: measurement.value
            }));
            this.lineChart.updateData(formattedMeasurements, tag);
        }
    } catch (error) {
        console.error(`Error parsing received message for ${tag}:`, error);
    }
}

What I’m Trying to Achieve

  • I want to connect to the WebSocket URL (CONFIG.WS_URL) only once.

  • I need to handle multiple tags and uids and process their corresponding messages

    Issue

    When I attempt to connect to the WebSocket URL only once and loop over the tags, uid, and messages, it doesn’t work as expected. Each tag needs its own unique uid and message processing, but I want to avoid opening multiple WebSocket connections.

    What I’ve Tried

    • Creating one wsClient and looping through the tags, but I couldn’t find a way to associate the uid and tag with the incoming messages correctly.

    • Opening a WebSocket connection for each tag (as shown in the code), which works but isn’t efficient.

    Question

    How can I restructure my code to use a single WebSocket connection and efficiently handle messages for multiple tags, each with its own uid?

    Any suggestions or best practices for handling this scenario would be appreciated.

TypeScript issues when dynamic loading

I have a file with icons being exported from images.ts:

export { default as SvgArrow } from './arrow.svg';
export { default as SvgCopy } from './copy.svg';
...
export { default as SvgWater } from './water.svg';

That’s a part of a design system library.

Then my Icon component imports the icons:

import * as Icons from '../images';

and within render sets the current icon:

const CurrentIcon = Icons[iconName];

With such implementation all the components in a library using <Icon /> had all the svgs in the build bundle. Because of that the bundle was very big – around 6mb.

I implemented the dynamic loading of the current icon.

const [IconComponent, setIconComponent] = useState<React.ElementType | null>(
  null,
);

useEffect(() => {
  const loadIcon = async () => {
    const icons = await import('../icons');

    setIconComponent(() => icons[iconName]);
  };
  loadIcon();
}, [iconName]);

The thing is that, although it worked in a way that bundle is no 700kB instead of 6mb, the TypeScript fails – meaning that in my consuming app I’m getting tons of errors, mostly like :

You may need an appropriate loader to handle this file type, currently
no loaders are configured to process this file. See
https://webpack.js.org/concepts#loaders

The dynamic loading was the only change. Right when I revert it all works in my app, but in the same time the build is again at 6mb.

I’ve tried many solutions – webpack magic comments, JS eval (which worked, but that’s not the right approach), better typings for the useEffect. None of them worked, still same TS errors.

My tsconfig is:

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es2020",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "declaration": true,
    "outDir": "./dist",
    "rootDir": ".",
    "declarationDir": "./dist",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "es2020",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "sourceMap": true,
    "declarationMap": true,
    "jsx": "react-jsx",
    "incremental": false,
    "paths": {
      "components/*": ["components/*"],
      "utils/*": ["utils/*"],
    },
    "plugins": []
  },
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules", "dist"]
}

I tried all the solutions for this question, but non of them worked – apart from JS eval which is generally considered a bad practice for security and performance reasons.

I’m also using @svgr/webpack in webpack, without dynamic loading my package for the design system works without any issues, also icons.

Even now, with all the TS errors, the consuming app works if I do:

{
  test: /.d.ts$/,
  loader: 'ignore-loader',
},

but that’s not what I want. I want my design system package to work out of the box without any TS issues and with the dynamic import of the icons.

Why does Array.map with String.replace only process the first element in Google Apps Script? [closed]

I am working with a string array in Google Apps Script and encountering an issue when using Array.map with String.replace. Here’s my code:

function testProcessing() {
  const solCheck = sh.getRange("A1").getValue().flat();
  const removePrefixes = option => option.replace(/^[a-d])s*/, "").trim();
  const solChoices = solCheck.map(removePrefixes);

  Logger.log(solChoices);
}

In which the value in cell A1 is:
a) Vật dao động điều hòa., b) Biên độ dao động bằng 10 cm., d) Pha dao động bằng π/2.
I want the solChoices array to look like this after processing:

[
  Vật dao động điều hòa.,
  Biên độ dao động bằng 10 cm.,
  Tần số dao động bằng 1 Hz.
]

Only the first element gets processed correctly, while the others remain unchanged:

[
  Vật dao động điều hòa.,
  b) Biên độ dao động bằng 10 cm.,
  c) Tần số dao động bằng 1 Hz.
]

Why does Array.map combined with String.replace only process the first element in Google Apps Script?
How can I fix this so that all elements in the array are processed as expected?

VS Code Unable to resolve path to module error on non-relative paths

I have a JavaScript Next.js project configured to treat “@” as root, and the auto-import configured to write the imports as @/folder1/folder2.

ESLint does not show an import error on relative paths (like ./folder1/folder2) but it does for @/folder1/folder2.

What should I change to make VS Code or ESLint treat the non-relative path properly and not show an error when non-relative paths are used?

Converting Javascript to Golang code discrepancy

I’m using CyberSource as a payment processor and I want to convert the JS hashing code to Golang. I attempted to do it but the output of the Go is not matching that of the JS. Where am I messing up? The Golang code runs and spits out a long string about the same length as the JS, but not the same.

Correct JS

"use strict";
import crypto from 'crypto';


export const CardTypes = {
  Visa: '001',
  MasterCard: '002',
  AmericanExpress: '003',
  Discover: '004',
  Diners: '005',
  JCB: '007',
  Maestro: '042',
  ChinaUnionPay: '062',
};


export const generateKey = (crypto) => crypto.subtle.generateKey({
  name: 'AES-GCM',
  length: 256
}, true, ['encrypt']);


export const _encrypt = async (crypto, payload, key, header, iv) => {
  const algorithm = {
      name: 'AES-GCM',
      iv,
      additionalData: stringToArrayBuffer(replace(JSON.stringify(header))),
      tagLength: 128
  };
  const buffer = await crypto.subtle.encrypt(algorithm, key, stringToArrayBuffer(JSON.stringify(payload)));
  return [buffer, key];
};


export const importKey = (crypto, jsonWebKey) => crypto.subtle.importKey('jwk', jsonWebKey, {
  name: 'RSA-OAEP',
  hash: {
      name: 'SHA-1'
  }
}, false, ['wrapKey']);


export const wrapKey = async (crypto, key, jsonWebKey) => {
  const wrappingKey = await importKey(crypto, jsonWebKey);
  const params = {
      name: 'RSA-OAEP',
      hash: {
          name: 'SHA-1'
      }
  };
  return crypto.subtle.wrapKey('raw', key, wrappingKey, params);
};


export const buildEncryptedData = async (crypto, buffer, key, iv, header, jsonWebKey) => {
  const u = buffer.byteLength - ((128 + 7) >> 3);
  const keyBuffer = await wrapKey(crypto, key, jsonWebKey);
  return [
      replace(JSON.stringify(header)),
      replace(arrayBufferToString(keyBuffer)),
      replace(arrayBufferToString(iv)),
      replace(arrayBufferToString(buffer.slice(0, u))),
      replace(arrayBufferToString(buffer.slice(u)))
  ].join('.');
};


export const arrayBufferToString = (buf) => String.fromCharCode.apply(null, new Uint8Array(buf));


export const stringToArrayBuffer = (str) => {
  const buffer = new ArrayBuffer(str.length);
  const array = new Uint8Array(buffer);
  const { length } = str;
  for (let r = 0; r < length; r += 1) {
      array[r] = str.charCodeAt(r);
  }
  return buffer;
};


// Replaced base64 encoding function
export const replace = (str) => btoa(str).replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');


// JWT decoding function
function decodeJwt(token) {
  try {
      const payload = token.split('.')[1]; // Extract the payload part of the JWT
      const decoded = Buffer.from(payload, 'base64').toString('utf-8'); // Decode base64-encoded string
      return JSON.parse(decoded); // Parse the JSON string
  } catch (error) {
      console.log(error);
      throw new Error('Invalid JWT token');
  }
}


// Encryption function
export const encrypt = async (data, context, index = 0) => {
  const keyId = decodeJwt(context);
  const header = {
      kid: keyId.flx.jwk.kid,
      alg: 'RSA-OAEP',
      enc: 'A256GCM'
  };
  const payload = {
      data,
      context,
      index
  };


  const iv = crypto.randomBytes(12); // Generate a random initialization vector (12 bytes for AES-GCM)


  return generateKey(crypto)
      .then((key) => _encrypt(crypto, payload, key, header, iv))
      .then((data) => {
          const [buffer, key] = data;
          return buildEncryptedData(crypto, buffer, key, iv, header, keyId.flx.jwk);
      });
};



// Example use

const context = "eyJraWQiOiJ3ZiIsImFsZyI6IlJTM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29tIiwiaHR0cHM6Ly90ZXN0LnBva2Vtb25jZW50ZXIuY29tIiwiaHR0cDovL2xvY2FsaG9zdDozMDAwIl0sIm1mT3JpZ2luIjoiaHR0cHM6Ly9mbGV4LmN5YmVyc291cmNlLmNvbSJ9LCJ0eXBlIjoibWYtMS4wLjAifV0sImlzcyI6IkZsZXggQVBJIiwiZXhwIjoxNzMxNzQzMjQ5LCJpYXQiOjE3MzE3NDIzNDksImp0aSI6IkloRmhQS0ZJYklodFJlSnUifQ.NXO01kzfvAVqs-iZY2r7dKL_0enRa3snbAe0kpwCs-rrLDbwITAYw--sfX1rC0CLBxeFubaT52y0hxCf88-MmcQetSchswCka9MBl7zLnmncsToES1rd7VaDbv_DlgaHBwREb1NR3l-6rmclcgOswK_kuAgFRWes-QOLWgtSqoBfhOC87w1ZInNMDwcJk__74o8vBgsVB7UDHfyjDaRMRrxOZRiX3TTmizOZtuN0TvmL7rwJHgTxlAdwcuxA4Ja2hBLA0zvqLgDg5cPZCNIpQvGYTdzJFSSc-nmhYlzf4eqZ3V-eD3qK9u1q44ZWAl8dS9x56XrsIkvYMo9VJ3namQ";


const data = {
number: "5102778094092647",
securityCode: "813",
expirationMonth: "01",
expirationYear: "2025",
type: "002",
};


const encrypted = await encrypt(data, context);

Golang

package Captcha

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha1"
    "encoding/base64"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "math/big"
    "strings"
)

var CardTypes = map[string]string{
    "Visa":            "001",
    "MasterCard":      "002",
    "AmericanExpress": "003",
    "Discover":        "004",
    "Diners":          "005",
    "JCB":             "007",
    "Maestro":         "042",
    "ChinaUnionPay":   "062",
}

func decodeJwt(token string) (map[string]interface{}, error) {
    parts := strings.Split(token, ".")
    if len(parts) < 2 {
        return nil, errors.New("invalid JWT token: missing segments")
    }

    payload := parts[1]

    decoded, err := base64.RawURLEncoding.DecodeString(padBase64(payload))
    if err != nil {
        decodedStd, errStd := base64.StdEncoding.DecodeString(padBase64(payload))
        if errStd != nil {
            return nil, fmt.Errorf("failed to decode base64 payload: %w", err)
        }
        decoded = decodedStd
    }

    var result map[string]interface{}
    if err := json.Unmarshal(decoded, &result); err != nil {
        return nil, fmt.Errorf("failed to unmarshal payload JSON: %w", err)
    }

    return result, nil
}

func padBase64(s string) string {
    switch len(s) % 4 {
    case 2:
        s += "=="
    case 3:
        s += "="
    }
    return s
}

func generateKey() ([]byte, error) {
    key := make([]byte, 32) // 256 bits
    _, err := rand.Read(key)
    if err != nil {
        return nil, err
    }
    return key, nil
}

func stringToBytes(str string) []byte {
    return []byte(str)
}

func bytesToString(buf []byte) string {
    return string(buf)
}

func replace(str string) string {
    return base64.RawURLEncoding.EncodeToString([]byte(str))
}

func _encrypt(payload interface{}, key []byte, header interface{}, iv []byte) ([]byte, []byte, error) {
    // Prepare the additionalData from the header
    headerJSON, err := json.Marshal(header)
    if err != nil {
        return nil, nil, err
    }
    additionalData := stringToBytes(replace(string(headerJSON)))

    // Convert payload to JSON
    payloadBytes, err := json.Marshal(payload)
    if err != nil {
        return nil, nil, err
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, nil, err
    }

    aesGCM, err := cipher.NewGCM(block)
    if err != nil {
        return nil, nil, err
    }

    // Encrypt
    // GCM output = ciphertext + tag appended
    cipherText := aesGCM.Seal(nil, iv, payloadBytes, additionalData)

    // Return the combined ciphertext+tag, along with key
    return cipherText, key, nil
}

type jwkRSA struct {
    Kty string `json:"kty"`
    N   string `json:"n"`   // base64url
    E   string `json:"e"`   // base64url
    Kid string `json:"kid"` // optional
    Use string `json:"use"` // e.g. "enc"
    Alg string `json:"alg"` // e.g. "RSA-OAEP"
}

func wrapKey(aesKey []byte, jwk map[string]interface{}) ([]byte, error) {
    // Convert the relevant JWK portion to a jwkRSA struct
    var keyData jwkRSA
    b, err := json.Marshal(jwk)
    if err != nil {
        return nil, err
    }
    if err := json.Unmarshal(b, &keyData); err != nil {
        return nil, err
    }

    // Decode base64 URL n and e
    nBytes, err := base64.RawURLEncoding.DecodeString(keyData.N)
    if err != nil {
        return nil, fmt.Errorf("failed to decode n: %w", err)
    }
    eBytes, err := base64.RawURLEncoding.DecodeString(keyData.E)
    if err != nil {
        return nil, fmt.Errorf("failed to decode e: %w", err)
    }

    // Convert big-endian bytes to big.Int
    n := new(big.Int).SetBytes(nBytes)
    e := new(big.Int).SetBytes(eBytes)

    // If e is small, interpret it properly
    // (Often e is 65537)
    pubKey := &rsa.PublicKey{
        N: n,
        E: int(e.Int64()),
    }

    // For RSA-OAEP with SHA1
    hash := sha1.New()

    // Encrypt (wrap) the AES key
    wrapped, err := rsa.EncryptOAEP(hash, rand.Reader, pubKey, aesKey, nil)
    if err != nil {
        return nil, err
    }
    return wrapped, nil
}

func buildEncryptedData(
    cipherText []byte,
    aesKey []byte,
    iv []byte,
    header interface{},
    jwk map[string]interface{},
) (string, error) {

    // GCM uses a 128-bit (16-byte) tag
    tagLength := 16

    // ciphertext length minus 16 bytes
    if len(cipherText) < tagLength {
        return "", errors.New("ciphertext too short for GCM tag")
    }
    u := len(cipherText) - tagLength

    // Wrap the AES key
    wrappedKey, err := wrapKey(aesKey, jwk)
    if err != nil {
        return "", err
    }

    // Convert everything to base64-URL strings
    headerJSON, _ := json.Marshal(header)
    partHeader := replace(string(headerJSON))
    partKey := replace(bytesToString(wrappedKey))
    partIV := replace(bytesToString(iv))
    partCipher := replace(bytesToString(cipherText[:u]))
    partTag := replace(bytesToString(cipherText[u:]))

    return strings.Join([]string{
        partHeader,
        partKey,
        partIV,
        partCipher,
        partTag,
    }, "."), nil
}

func Encrypt(data interface{}, context string, index int) (string, string, error) {
    // 1) Decode the JWT to get the kid + JWK
    decoded, err := decodeJwt(context)
    if err != nil {
        return "", "", err
    }

    flxRaw, ok := decoded["flx"]
    if !ok {
        return "", "", errors.New("flx field not found in JWT payload")
    }
    flxMap, ok := flxRaw.(map[string]interface{})
    if !ok {
        return "", "", errors.New("invalid flx field")
    }
    jwkRaw, ok := flxMap["jwk"]
    if !ok {
        return "", "", errors.New("jwk field not found in flx")
    }
    jwkMap, ok := jwkRaw.(map[string]interface{})
    if !ok {
        return "", "", errors.New("invalid jwk field")
    }

    kidRaw, ok := jwkMap["kid"]
    if !ok {
        return "", "", errors.New("kid field not found in jwk")
    }
    kid, _ := kidRaw.(string)
    fmt.Println("key id is: " + kid)

    // 2) Build the header
    header := map[string]string{
        "kid": kid,
        "alg": "RSA-OAEP",
        "enc": "A256GCM",
    }

    // 3) The actual payload
    payload := map[string]interface{}{
        "data":    data,
        "context": context,
        "index":   index,
    }

    // 4) Generate a random IV (12 bytes for GCM)
    iv := make([]byte, 12)
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return "", "", err
    }

    // 5) Generate the AES key
    aesKey, err := generateKey()
    if err != nil {
        return "", "", err
    }

    // 6) Encrypt with AES-GCM
    cipherText, realKey, err := _encrypt(payload, aesKey, header, iv)
    if err != nil {
        return "", "", err
    }

    // 7) Build final encrypted data string
    encrypted, err := buildEncryptedData(cipherText, realKey, iv, header, jwkMap)
    if err != nil {
        return "", "", err
    }

    return encrypted, kid, nil
}

// Example use
func main() {
    context := "eyJraWQiOiJ3ZiIsImFsZyI6IlJTMjU2In0.eyJmbHgiOnsicGF0aCI6Ii9mbGV4L3YyL3Rva2VucyIsImRhdGEiOiIvUVJ1QjF1dGJVQXd3OXp0ekovZG1oQUFFTlB3VFVZR2dtVTh1eDBiZnNocWpFNmlEU09VNWxJd0dFZGNNWG1nSlp5WGlrWDA0RXVDNmlrOXJPaXNZZW5XRm1ZK0ZUSGw4dW9UYWkvOVhRNEZ6SDFPOE4rekxkaEkzblN3QllwQmsyWWYiLCJvcmlnaW4iOiJodHRwczovL2ZsZXguY3liZXJzb3VyY2UuY29tIiwiandrIjp7Imt0eSI6IlJTQSIsImUiOiJBUUFCIiwidXNlIjoiZW5jIiwibiI6InNfbHhBLUJXc1Bab1pRR0lKN0JwdjNfNkF5U0VYZXV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-6rmclcgOswK_kuAgFRWes-QOLWgtSqoBfhOC87w1ZInNMDwcJk__74o8vBgsVB7UDHfyjDaRMRrxOZRiX3TTmizOZtuN0TvmL7rwJHgTxlAdwcuxA4Ja2hBLA0zvqLgDg5cPZCNIpQvGYTdzJFSSc-nmhYlzf4eqZ3V-eD3qK9u1q44ZWAl8dS9x56XrsIkvYMo9VJ3namQ"

    data := map[string]string{
        "number":           "5102778094092647",
        "securityCode":     "813",
        "expirationMonth":  "01",
        "expirationYear":   "2025",
        "type":             "002",
    }

    encryptedData, kid, err := Captcha.Encrypt(data, context, 0)
}

Index.tsx file isn’t rendering in expo route

I can’t seem to get the index.tsx file to render in the (location) directory.
The _layout.tsx component renders with the header but nothing else.

I have checked the sitemap and index.tsx is recognised, so not sure why it won’t render?

here is my app structure

app/
├── (location)/
|   ├── _layout.tsx
|   ├── index.tsx
├── (stores)/
|   ├── _layout.tsx
|   ├── index.tsx
├── _layout.tsx
├── index.tsx
├── searchStores.tsx

from searchStores.tsx you can navigate to (location) with:

router.push(`/(location)`);

Here is my _layout.tsx component:

import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import { useRouter } from "expo-router";
import { Ionicons } from "@expo/vector-icons";

const Header = ({
  title,
  onBackPress,
}: {
  title: string,
  onBackPress: () => void,
}) => {
  return (
    <View style={styles.header}>
      <TouchableOpacity onPress={onBackPress} style={styles.backButton}>
        <Ionicons name="arrow-back" size={30} color="black" />
      </TouchableOpacity>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
};

export default function Layout() {
  const router = useRouter();
  const handleBackPress = () => {
    router.navigate("/searchStores");
  };

  return <Header title="Location" onBackPress={handleBackPress} />;
}

const styles = StyleSheet.create({
  header: {
    flexDirection: "row",
    alignItems: "center",
    padding: 10,
    backgroundColor: "#f8f8f8",
  },
  backButton: {
    marginRight: 50,
    marginLeft: 10,
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
  },
});

Here is the index.tsx file i am trying to render:

import { View, Text } from "react-native";

const Index = () => {
  return (
    <View>
      <Text>test screen</Text>
    </View>
  );
};

export default Index;

Unable to load sibiling component after taking build in nextjs

I have took a build file in nextjs. While running the index.html from build. Can’t load the peer components through routing. Even css isnt loading. Help me to understand this problem.

Uncaught Error: Minified React error #418; visit https://react.dev/errors/418?args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at rv (framework-a4ddb9b21624b39b.js:1:30568)
    at ot (framework-a4ddb9b21624b39b.js:1:75177)
    at ua (framework-a4ddb9b21624b39b.js:1:111832)
    at framework-a4ddb9b21624b39b.js:1:111677
    at ul (framework-a4ddb9b21624b39b.js:1:111685)
    at i3 (framework-a4ddb9b21624b39b.js:1:108046)
    at uT (framework-a4ddb9b21624b39b.js:1:128652)
    at MessagePort.z (framework-a4ddb9b21624b39b.js:1:179469)Understand this errorAI
image:1 
        
        
       Failed to load resource: the server responded with a status of 404 (Not Found)

errors in console. Cant create a proper build file.
Anybody could explain what does it says?

JSON response is not getting bound in HTML Table via Jquery Datatable

I have a response coming from DB, for which I want to bind those data in HTML table. So for that I have written below code. But with below jquery datatable logic the data is not getting bound

function loadCMPWiseData() {
    var CMP;
    showLoading();
    try {    
        
        CMP = $("#ddlCMPSignOff option:selected").text();

        //if (validRequest() == true) {
            var Values = { "CIRCLE": CMP};
            $.ajax({
                type: "POST",
                url: AppConfig.PrefixURL + "App/GetMPFTTXData",
                data: JSON.stringify(Values),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (response) {
                    $("#fttxPanWiseDatatable").hide();
                    $("#fttxCmpWiseDatatable").show();
                    $('#fttxCmpWiseDatatable').dataTable({
                        data: response,
                        "columns": [
                        { "CIRCLE": "CIRCLE" },
                        { "FSA": "FSA" },
                        { "TotalKM": "TotalKM" },
                        { "UGKM": "UGKM" },
                        { "AerialKM": "AerialKM" },
                        { "MDUKM": "MDUKM" }
                        ]
                    });
                },
                error: function (response) {
                    hideLoading();
                },
                complete: function (response) {
                    if (CurrentGroupName != UserGrouop.NHQPMO && response.responseJSON.length > 0) {
                       // $("#btnExportPDFFTTX").show();
                    } else {
                       // $("#btnExportPDFFTTX").hide();
                    }
                    hideLoading();
                }
            });

      //  } else {
            //jAlert("All fields are mandatory!", "Alert");
            hideLoading();
        //}
    } catch (e) {
        hideLoading();
    }
}
<table id="fttxCmpWiseDatatable" class="table sodTable table-bordered nowrap pageResize dataTable" style="width: 100%;">
                    </table>

Also see the response:

[
    {
        "CIRCLE": "Tirupati",
        "FSA": 1,
        "TotalKM": 11.88,
        "UGKM": 0.35,
        "AerialKM": 11.53,
        "MDUKM": 0
    },
    {
        "CIRCLE": "Vishakhapatnam",
        "FSA": 2,
        "TotalKM": 0,
        "UGKM": 0,
        "AerialKM": 0,
        "MDUKM": 0
    },
    {
        "CIRCLE": "Kakinada",
        "FSA": 1,
        "TotalKM": 0,
        "UGKM": 0,
        "AerialKM": 0,
        "MDUKM": 0
    },
    {
        "CIRCLE": "Rajahmundry",
        "FSA": 2,
        "TotalKM": 0,
        "UGKM": 0,
        "AerialKM": 0,
        "MDUKM": 0
    },
    {
        "CIRCLE": "Kurnool",
        "FSA": 1,
        "TotalKM": 0,
        "UGKM": 0,
        "AerialKM": 0,
        "MDUKM": 0
    },
    {
        "CIRCLE": "Vijaywada",
        "FSA": 2,
        "TotalKM": 13.39,
        "UGKM": 13.12,
        "AerialKM": 0.26,
        "MDUKM": 0
    },
    {
        "CIRCLE": "Anantapur",
        "FSA": 1,
        "TotalKM": 0.04,
        "UGKM": 0,
        "AerialKM": 0,
        "MDUKM": 0.04
    }
]

Update after C3roe statement

Here is the final try what I did

function loadCMPWiseData() {
var CMP;
showLoading();

CMP = $("#ddlCMPSignOff option:selected").text();

$('#fttxCmpWiseDatatable').DataTable({
    ajax: {
        type: "POST",
        url: AppConfig.PrefixURL + "App/GetMPFTTXData",
        data: JSON.stringify(Values),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false
    },
    columns: [
    { data: "CIRCLE" },
    { data: "FSA" },
    { data: "TotalKM" }
    ]
} );

}