Inline edit save not working in multiple repeater

The code is just a simple widget. Here just i added two repeaters with a text control which i want to edit in inline. Now in the widget inline editing is working fine but it can’t saved.
But when i use one repeater only then it’s perfectly working the inline edit and save.
Now I used this add_inline_editing_attributes for inline editing. So to save the inline edit text for two repeaters what should i do?

protected function register_controls() {
    $this->start_controls_section(
        'content_section',
        [
            'label' => esc_html__( 'Test Plugin', 'test-plugin-td' ),
            'tab' => ElementorControls_Manager::TAB_CONTENT,
        ]
    );

    $repeater = new Repeater();
    $repeater->add_control(
        'text',
        [
            'label' => __( 'Business Hour', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::TEXT,
            'label_block' => true,
            'placeholder' => __( 'First Name', 'test-plugin-td' ),
            'default' => __( 'First Name', 'test-plugin-td' ),
            'dynamic' => [
                'active' => true,
            ],
        ]
    );
    $this->add_control(
        'business_hours',
        [
            'label' => __( 'Test Plugin', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::REPEATER,
            'fields' => $repeater->get_controls(),
            'default' => [
                [
                    'text' => __( 'First Name', 'test-plugin-td' ),
                ],
                [
                    'text' => __( 'Last Name', 'test-plugin-td' ),
                ],
            ],
            'title_field' => '{{{ text }}}',
        ]
    );

    $this->end_controls_section();


    $this->start_controls_section(
        'content_2section',
        [
            'label' => esc_html__( 'Test Plugin', 'test-plugin-td' ),
            'tab' => ElementorControls_Manager::TAB_CONTENT,
        ]
    );

    $repeskeater = new Repeater();
    $repeskeater->add_control(
        'text2',
        [
            'label' => __( 'Business Hour', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::TEXT,
            'label_block' => true,
            'placeholder' => __( 'First Name', 'test-plugin-td' ),
            'default' => __( 'First Name', 'test-plugin-td' ),
            'dynamic' => [
                'active' => true,
            ],
        ]
    );
    $this->add_control(
        'business_2hours',
        [
            'label' => __( 'Test Plugin', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::REPEATER,
            'fields' => $repeskeater->get_controls(),
            'default' => [
                [
                    'text' => __( 'First Name', 'test-plugin-td' ),
                ],
                [
                    'text' => __( 'Last Name', 'test-plugin-td' ),
                ],
            ],
            'title_field' => '{{{ text2 }}}',
        ]
    );

    $this->end_controls_section();
}

protected function render() {
    $settings = $this->get_settings_for_display();
    echo '<ul class="test-plugin-td">';
    foreach ( $settings['business_hours'] as $index => $item ) :
        $text_key = $this->get_repeater_setting_key( 'text', 'business_hours', $index );
        $this->add_inline_editing_attributes( $text_key );
        ?>
        <li class="business-hour-item">
            <span <?php $this->print_render_attribute_string( $text_key ); ?>>
                <?php echo esc_html( $item['text'] ); ?>
            </span>
        </li>
        <?php
    endforeach;
    echo '</ul>';

    echo '<ul class="test-plugin-td">';
    foreach ( $settings['business_2hours'] as $index => $item ) :
        $text_key = $this->get_repeater_setting_key( 'text2', 'business_2hours', $index );
        $this->add_inline_editing_attributes( $text_key );
        ?>
        <li class="business-hour-item">
            <span <?php $this->print_render_attribute_string( $text_key ); ?>>
                <?php echo esc_html( $item['text2'] ); ?>
            </span>
        </li>
        <?php
    endforeach;
    echo '</ul>';
}

Datatable – Javascript – delete all rows is not working

I have a datatable inside a bootstrap modal. I am able to add/update/delete individual rows. But I am not able to clear all the rows. It does nothing.

HTML code:

<table class="table table-bordred" 
   id="tbl_outputdetail" name="tbl_outputdetail">
  <thead>
    <tr>
      <th>By Product</th>
      <th>Quantity Produced</th>
      <th></th>
      <th class="hide_column"></th>
    </tr>
    <tr>
      <th>
        <select style="width:300px;" class="form-control m-input"
           id="outputitem" name="outputitem">
        </select>
      </th>
      <th>
        <input type="text" class="form-control m-input" 
           id="outputqty" name="outputqty">
      </th>
      <th>
        <a href="#" id="output-add" name="output-add">
          <i class="la la-check"></i>
        </a>
        &nbsp;
        <a href="#" id="output-clear" name="output-clear">
          <i class="la la-close"></i>
        </a>
      </th>
      <th></th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

DataTable Definition:

tablew4 = $("#tbl_outputdetail").DataTable({
searching: false,
paging: false,            
serverSide:false,
ordering:false,
scrollX: true,
info:false,
columnDefs:[
{targets: [ 0 ], width: '400px'}, {targets: [ 1 ], width: '400px'},
{targets: [ 2 ], width: '100px'}, {targets: [ 3 ],   className: "hide_column"} 
],
"order": []
});

Code to delete the rows:

tablew4.clear().draw();
tablew4.rows().remove().draw();

Both methods do not clear the rows.

Treat Variables as single entities for deletion in a Text Box Using JavaScript

I have a text box field in my simple HTML/JavaScript-based form where users can insert variables, as shown in the example below:

The name of the product is ${productName}

When the user submits the form, a JavaScript function replaces the variable with its actual product value.

I’d like to implement a feature where, if the user places their cursor to the right of the variable ${productName} and presses the backspace key, the entire variable is deleted in one go, instead of deleting each character one at a time. Essentially, I want the variable to behave as a single, indivisible entity in the text box.

I’m unsure what the technical term for this feature is or how to start researching it. What’s the most efficient way to implement this behaviour?

Bun.js Packet losses in Websocket

I created a Websocket server using Bun.serve(). In this server, when a new client connects, I send it 1 million packets with a for loop. But these packets are interrupted. Hundreds of thousands of packets are not sent to the client. I used the ws package from NPM instead of Bun’s Websocket and the problem is solved. How can Bun, which claims to be a much faster Websocket server than ws, experience packet loss? Is there a solution to this or should I use ws until this problem is noticed?

server.js

const Bun = require("bun");

Bun.serve({
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("Only WebSocket connections are supported.", {status: 400});
  },

  websocket: {
    open(socket) {
      const start = performance.now();

      for (let i = 0; i < 1_000_000; i++) socket.send(JSON.stringify({"type": "MESSAGE_CREATE", "data": {"content": i}}));

      const end = performance.now();
      const duration = end - start;

      console.log(duration.toFixed(2) + " ms");
    },

    close(socket) {
      console.log("Client disconnected");
    },

    error(socket, error) {
      console.error("WebSocket error:", error);
    }
  },

  port: 8080,
  reusePort: true
});

client.js

const WebSocket = require("ws");
const ws = new WebSocket("ws://localhost:8080");

var count = 0;
var start_date;

ws.on("message", message => {
  count++;
  if (count === 1) console.log(message.toString() + " 0 ms"), start_date = Date.now();
  if (count >= 999_990) console.log(message.toString() + " " + (Date.now() - start_date) + " ms");
});

setInterval(() => console.log(count), 5000);

Solution without packet loss but with ws library.

server.js

const http = require("http");
const WebSocket = require("ws");
const Server = http.createServer();
const ws = new WebSocket.Server({server: Server});

ws.on("connection", socket => {
    const start = performance.now();

    for (let i = 0; i < 1_000_000; i++) socket.send(JSON.stringify({"type": "MESSAGE_CREATE", "data": {"content": i}}));

    const end = performance.now();
    const duration = end - start;

    console.log(duration.toFixed(2) + " ms");
})

Server.listen(8080);

Changing display property dynamically with Javascript and If

I want to change the display property of a div tag based on its current display property.

When display = “None”, it should switch to “flex” by clicking on it and viseversa.

I wrote the following js code:

window.onload = function showHideSideMenuMyFolders() {

    var test = document.getElementById("sideMenuLowerPartFolders_MyFolders");
    
    if (test.style.display === "Flex") {
        test.style.display = "None";
    }
    else {
        test.style.display = "Flex";
    }
}

It should activate by clicking on a span element in the DOM.

<span id="showSideMenuMyFolders" onclick="showHideSideMenuMyFolders()">

However, it is not working.

Can somebody see my mistake?

Strange scrolling behavior on ios mobile

I have a three.js landing page on my WordPress site. Once the animation stops the user swipes right or left. On that view the user is to swipe up or down to scroll, this is where we are experiencing some strange behavior. On android mobile the swipe up and down to scroll works fine. On ios mobile, you cannot initially swipe down (the page refreshes rather than scrolls). You can, however, swipe up and scrolling works as normal. Strangely, once you swipe up, swipe down then begins working. Any help on fixing this issue would be appreciated. site is https://everyrep.com

I set these to the scroll container with no luck:

      overscroll-behavior-x: none;
      overscroll-behavior-y: none;

Javascript Upload Image [closed]

After about two weeks reading you, I am at the end of upploding. Acutally I can do

  1. display and delete images before sending to the server
  2. send and backup image to server
  3. animate progress bar

Probleme: I use a formData which is association of the image name and blob
which I use in ajax succes`

 for (var pair of blobs.entries())
{
   if( pair[0] == img ) // image name is id of my ImgDiv
   {
      console.log("Find it : " + img);
      document.getElementById(img).remove("ImgDiv");
      DisplayOff(img);
   }
 }

`
Why this code juste liberate the last image

thanks

When i reload the page on the browser some variables do not populate properly

In React, everytime i reload the page i receive correctly the json from the backend, then i put this array into a function to delete all the key that contain null values. If i console.log the variable is always an empty. The strange thing is that if i modify something about some file and save them, when i switch again into the browser without reloading the page, it populate properly all the variables, this issue come up only when i reload the page.

This is a sample of the json that i receive from the backend:

    [
    {date:01/01/2024, categorieEntrate: lavoro, categorieUscite: spesa, account: banca},
    {date:01/02/2024, categorieEntrate: lavoro, categorieUscite: spesa, account: banca},
    {date:01/03/2024, categorieEntrate: lavoro, categorieUscite: spesa, account: banca},
    {date:01/05/2024, categorieEntrate: null, categorieUscite: spesa, account: banca},
    {date:01/07/2024, categorieEntrate: null, categorieUscite: spesa, account: null},
    {date:01/10/2024, categorieEntrate: null, categorieUscite: spesa, account: null},
    {date:01/12/2024, categorieEntrate: null, categorieUscite: spesa, account: null},
    ]

Below the code:

    const [mesePerMese, setMesePerMese] = useState([]);
    const [annoPerAnno, setAnnoPerAnno] = useState([]);
    const [categorie, setCategorie] = useState([]);       

 useEffect(() => {

        fetch("http://localhost:3000/impostazioni")
            .then(res => res.json())
            .then(data => {
                let a = data["data"];
                console.log("ciao")
                console.log(a);

                let estratto = estraiCategorieEntrateUscite(a);
                setCategorie(estratto);
                console.log(categorie) //when I console.log here the array is empty
            });


        fetch("http://localhost:3000/transazioni")
            .then(res => res.json())
            .then(data => {
                let dati = data["data"];
                const formattato = ISOitaliano(dati);
                const ordinato = ordinaDate(formattato);

                let b = new Statistiche(categorie[0], categorie[1]);

                ordinato.map(rigo => {
                    b.aggiungiTransazione(rigo);
                })
                setMesePerMese(b.ottieniMesePerMese());
                setAnnoPerAnno(b.ottieniAnnoPerAnno());
                console.log("anno per anno")
                console.log(annoPerAnno);
                console.log("mese per mese");
                console.log(mesePerMese);


            });


    }, [])


export function estraiCategorieEntrateUscite(array) {

    let categorieEntrate = [], categorieUscite = [];
    
    array.forEach((item, index) => {
        if (item["categorieEntrate"] !== null && item["categorieEntrate"] !== undefined) {
            categorieEntrate.push(item["categorieEntrate"]);
        }
        if (item["categorieUscite"] !== null && item["categorieUscite"] !== undefined) {
            categorieUscite.push(item["categorieUscite"]);
        }
    });

console.log(categorieEntrate); //i console.log here and the array is fine
console.log(categorieUscite); //i console.log here and the array is fine



    return [categorieEntrate, categorieUscite];
}

Scrollable element selecting

can anybody help me with creation scrollable choice in timer like in Apple (example on screenshot)? At the end it should be component in React, but I can’t understand logic how it should works, I will be pleasured if somebody share with me with some article, code or just explain logic how i should works, better if it will be some js or react code.
enter image description here

At the moment I tried some my ideas, but it failed

Why iframe enforce the parent page’s Content Security Policy instead of its own

I’m working with an iframe and attempting to define its own Content Security Policy (CSP) using the csp attribute and the sandbox attribute. Here’s the HTML structure of my iframe:

<iframe
  sandbox="allow-scripts"
  csp="default-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline';"
  srcdoc="...myContent"
></iframe>

The issue is that scripts and styles within the iframe are still being blocked based on the CSP of the parent page, even though I explicitly define a csp attribute in the iframe itself. For example, the following script fails to load with an error:

Refused to load the script 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js' because it violates the following Content Security Policy directive: "script-src 'nonce-m5JxllYLAaAYeolMNX0mQg==' 'strict-dynamic'".

This restriction ('nonce-m5JxllYLAaAYeolMNX0mQg==' and 'strict-dynamic') is from the CSP of the parent page, not the iframe. My understanding is that the csp attribute on the iframe should allow it to enforce its own CSP rules and ignore the parent page’s CSP.

Questions:

  1. Why is the iframe still enforcing the parent page’s CSP instead of its own?
  2. Is there a way to fully isolate the iframe’s CSP so it loads resources according to the policies defined in the csp attribute?
  3. Is this behavior expected, or is it a bug or limitation in modern browsers?

Additional Context:

  • The iframe includes the sandbox="allow-scripts" attribute to isolate its context.
  • I am dynamically injecting content into the iframe using srcdoc and the csp attribute.

Minimax not returning best moves for tic-tac-toe (Javascript)

This JS minimax code for playing tic-tac-toe isn’t finding the best moves, even when there is a win in one move. What is wrong with it?

/** 
 * Return a list of possible moves on the board. 
 * 
 * @param {string[]} board - The board.
 * @returns {number[]}
 */
function actions(board) {
    const acts = [];
    for (let i = 0; i < board.length; i++) {
        if(board[i] == " ") {
            acts.push(i);
        }
    }
    return acts;
}

/** 
 * Return number of occupied squares on the board. 
 * 
 * @param {string[]} board - The board.
 * @returns {number}
 */
function occupied(board) {
    return board.filter((pos) => pos != " ").length;
}

/** 
 * Decide whether the game is over. 
 * 
 * @param {string[]} board - The board.
 * @returns {boolean} - true if there is a winner or all cells are occupied, otherwise false.
 */
export function terminal(board) {
    return getWinner(board) ||  occupied(board) === 9;
}

/** 
 * Calculate the winner, if any. 
 * 
 * @param {string[]} board - The board.
 * @returns {string} - The name of the winner, or null.
 */
export function getWinner(board) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];
    let winner = null;
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (board[a] != " " && board[a] == board[b] && board[a] == board[c]) {
            winner = board[a];
            break;
        }
    }
    return winner; 
}

/** 
 * Calculate the value of a board. 
 * 
 * @param {string[]} board - The board.
 * @returns {number} - 1 if the board is won by X, -1 if the board is won by O, otherwise 0.
 */
function utility(board) {
    const w =   getWinner(board);
    if (w == 'X') {
        return 1;
    } else if (w == 'O') {
        return -1;
    } else {
        return 0;
    }
}

/** 
 * Return the board that results from taking a move. 
 * 
 * @param {string[]} board - The board.
 * @returns {string[0]} - The new board.
 */
function result(board, move) {
    const result = board.slice();
    result[move] =  player(board);
    return result;
}

/** 
 * Calculate whose move it is. 
 * 
 * @param {string[]} board - The board.
 * @returns {string} - The name of the next player.
 */
function player(board) {
    return  occupied(board) % 2 == 0 ? 'X' : 'O';
}

/** 
 * Implementation of the Minimax algorithm. 
 * 
 * @param {string[]} board - The board.
 * @param {boolean} xIsNext - true if X is next.
 * @returns {number} - The best move to take for the current player.
 */
export function minimax(board, isMaximizingPlayer) {
    if (terminal(board)) {
      return [utility(board), null]; // Return utility and null move for terminal states
    }
  
    let bestValue = isMaximizingPlayer ? -Infinity : Infinity;
    let bestMove = null;
  
    actions(board).forEach((move) => {
      let newBoard = result(board, move);
      let [value, _] = minimax(newBoard, !isMaximizingPlayer);
  
      if (isMaximizingPlayer) {
        if (value > bestValue) {
          bestValue = value;
          bestMove = move;
        }
      } else {
        if (value < bestValue) {
          bestValue = value;
          bestMove = move;
        }
      }
    });
  
    return [bestValue, bestMove];
  }

I can’t approve or cancel the order if there’s only one order inserted in my database

When there is only one order present in my database, the “Approve” and “Cancel” buttons do not function as expected. However, if there are multiple orders in the database, these buttons work properly

java script

function fetchOrders(status) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'fetch_pending_orders.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
      if (xhr.status === 200) {
        // Insert fetched orders as cards into the orderCards container
        document.getElementById('orderCards').innerHTML = xhr.responseText;
      }
    };
    xhr.send('product_status=' + status);
  }
back end

$status = $_POST['product_status'] ?? 'Pending';

if ($status == 'all') {
    $sql = "SELECT *,
               IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
        FROM tbl_orders
        WHERE payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
} elseif ($status == 'To Pay') {
    $sql = "SELECT *, 
                   IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
            FROM tbl_orders 
            WHERE (product_status IS NULL OR product_status = '') AND payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
} elseif ($status == 'To Deliver') {
    $sql = "SELECT *, 
                   IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
            FROM tbl_orders 
            WHERE product_status = 'Approved' AND order_type = 'To Deliver' AND payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
}  elseif ($status == 'To Pickup') {
    $sql = "SELECT *, 
                   IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
            FROM tbl_orders 
            WHERE product_status = 'Approved' AND order_type = 'To Pickup' AND payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
} elseif ($status == 'Completed') {
    $sql = "SELECT *, 
                   IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
            FROM tbl_orders 
            WHERE product_status = 'Completed' AND payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
} elseif ($status == 'Cancelled') {
    $sql = "SELECT *, 
                   IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
            FROM tbl_orders 
            WHERE product_status = 'Cancelled' AND payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
} else {
    $sql = "SELECT *, 
                   IF(product_status IS NULL OR product_status = '', 'Pending', product_status) AS computed_status
            FROM tbl_orders 
            WHERE order_type = ? AND payment_method IS NOT NULL AND payment_method != ''";
    $stmt = $db->prepare($sql);
    $stmt->bind_param('s', $status);
}

// Execute the statement and fetch results
$stmt->execute();
$result = $stmt->get_result();

$output = '';
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
    $order_id = $row['order_id'];
    
    $output .= '<div class="order-card" style="display: flex; align-items: center; justify-content: space-between; padding: 20px; border: 1px solid #ddd; margin-bottom: 10px;">';

    // Product Image
    $output .= '<div class="product-image" style="flex: 1;">';
    $output .= '<img src="../variety_pictures/' . htmlspecialchars($row['variety_image']) . '" alt="Product Image" style="width: 100%;">';
    $output .= '</div>';

    // Product Details
    $output .= '<div class="order-info" style="flex: 2; padding-left: 20px;">';
    $output .= '<h2 style="margin: 0 0 10px 0;">' . htmlspecialchars($row['variety_name']) . '</h2>';
    $output .= '<p>Quantity: ' . htmlspecialchars($row['quantity']) . '</p>';
    $output .= '<p>Order Total: ₱ ' . number_format($row['total_price'], 2) . '</p>';
    $output .= '<p>Product Status: <strong>' . 
    (!empty($row['computed_status']) ? htmlspecialchars($row['computed_status']) : 'Pending') . 
    '</strong></p>';

    $output .= '<p>Payment Method: ' . htmlspecialchars($row['payment_method']) . '</p>';
    $output .= '<p>Order Option: ' . htmlspecialchars($row['order_type']) . '</p>';
    $output .= '</div>';

    // Receiver and Actions
    $output .= '<div class="order-actions" style="flex: 1; text-align: left;">';
    $output .= '<p>Order ID: ' . htmlspecialchars($row['order_id']) . '</p>';
    $output .= '<p>Receiver Name: ' . $receiver_name . '</p>';
    $output .= '<p>Contact: ' . htmlspecialchars($row['phoneNumber']) . '</p>';
    $output .= '<p>Address: ' . htmlspecialchars($row['address']) . '</p>';
    
    // Show "View Payment" button only if payment_method is "Online Payment"
    if ($row['payment_method'] === 'Online Payment') {
      $output .= '<button type="button" class="btn btn-secondary w-100 mb-3" onclick="viewPayment(' . $row['order_id'] . ')">View Payment</button>';
    }

    if ($row['product_status'] == 'Completed') {
      // Display only the "Completed" status without buttons
      $output .= '<p><strong>Order Status:</strong> Completed</p>';
    } elseif ($row['product_status'] == 'Cancelled') {
      // Display only the "Cancelled" status without buttons
      $output .= '<p><strong>Order Status:</strong> Cancelled</p>';
    } else {
      // Approve and Deny Buttons for other statuses
      $output .= '<form method="POST" action="update_order_status.php">';
      $output .= '<input type="hidden" name="order_id" value="' . $row['order_id'] . '">';
      $output .= '<button type="submit" class="btn btn-success w-100 mb-3 ml" name="product_status" value="Approved">Approve</button><br>';
      $output .= '<button type="submit" class="btn btn-danger w-100 ml" name="product_status" value="Cancelled">Deny</button>';
        $output .= '</form>';
    }

    $output .= '</div>';
    $output .= '</div>';
}

echo $output;

} else {
    $output = '<p>No orders found for ' . htmlspecialchars($status) . '</p>';
}
<?php
require '../config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = $_POST['order_id'] ?? null;
    $product_status = $_POST['product_status'] ?? null;

    if (in_array($product_status, ['Approved', 'Cancelled'], true)) {
        $sql = "UPDATE tbl_orders SET product_status = ? WHERE order_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->bind_param('si', $product_status, $order_id);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Order status updated successfully.']);
            header('location: pending.php');
            exit();
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update order status.']);
            header('location: pending.php');
            exit();
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid status value.']);
    }
}

?>

Even if there is only one order present in the database, I expect the “Approve” and “Cancel” buttons to function correctly, just as they do when multiple orders are present.

Qualtrics – Auto-Populate Field in Drill Down Group Using JavaScript

I need help automating responses within a drill-down question in Qualtrics. Specifically, I have three groups in the drill-down question:

  1. Group 1: Income in 2023 (answer options: income ranges).
  2. Group 2: Whether income has changed in 2024 compared to 2023 (answer options: Yes/No).
  3. Group 3: Income in 2024 (answer options: income ranges).

Sample question

I want to automatically populate Group 3 with the same value as Group 1 if the respondent selects “No” for Group 2. For example, in my picture, the field for 2024 will be automatically display “Less than €12,189” if the answer for changes is “No”. This would save respondents from having to manually select the same value again in Group 3. I am completely new to JavaScript and would really appreciate your help! Thank you so much!

I’ve tried to use default choices, but is not meeting my need.

API call from NextJS app throws a 403 if call is from client component, but not from server component

Like the title says, when I make a request to an external API from my client side component, I get a 403, but if I make it from a server component, it works just fine.

The reason I need to make the call from client side is because the user makes a selection and the request made depends on the selection, so useState() is used to manage the selection. The user selects a sector, and then the call to get industries by sector id is made.

The relevant client component code:

const { data: session } = useSession();
  const [sector, setSector] = useState<Sector | null>(null);
  const [industries, setIndustries] = useState<Industry[]>([]);
  const [industry, setIndustry] = useState<Industry | null>(null);

  const handleSectorSelection = (event: React.ChangeEvent<{}>, value: Sector | null) => {
    setSector(value);
  };
  const handleIndustrySelection = (event: React.ChangeEvent<{}>, value: Industry | null) => {
    setIndustry(value);
  };

  useEffect(() => {
    const getIndustries = async (sectorId: number) => {
      const response = await getIndustriesBySectorId(sectorId, session?.jwt);
      setIndustries(response.result as Industry[]);
    };
    if (sector && sector.id != null) {
      getIndustries(sector.id);
    } else {
      setIndustries([]);
    }
  }, [sector, session?.jwt]);
return (...
     <SectorSelectDropdown
            options={sectors}
            onChange={handleSectorSelection}
            renderInput={(params) => <TextField {...params} label="Search" variant="outlined" />}
          />
          {industries && industries.length > 0 ? (
            <IndustrySelectDropdown
              options={industries}
              onChange={handleIndustrySelection}
              renderInput={(params) => <TextField {...params} label="Search" variant="outlined" />}
            />
          ) : null} ...)

The sectors property is passed down from the parent component
The API call:

export async function getIndustriesBySectorId(sectorId: number, jwt?: string) {
  let result = null,
    error = null;
  if (!jwt) {
    throw new Error("Session JWT token not found.");
  }

  try {
    console.log(jwt);
    result = await fetch(`${process.env.NEXT_PUBLIC_POSITIONS_SERVICE_URL!}/industries/sector/${sectorId}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Cookie: `Authentication=${jwt}`,
      },
      credentials: "include",
    });
    if (!result.ok) {
      throw new Error(`Failed to fetch industry: ${result.statusText}`);
    }

    const data: Industry[] = await result.json();

    return { result: data, error: null };
  } catch (e) {
    error = e;
    return { result: {}, error: error };
  }
}

If I make the call from a server component, I would change things up within this file and get the session data directly (instead of passing them in) like this:

export async function getPositions() {
  const session = await getServerSession(authOptions);
  let result = null,
    error = null;

  if (!session?.jwt) {
    throw new Error("Session JWT token not found.");
  }...

So, is there a way to accomplish what I need to do with the current setup? Or is there a way to make my current client side component a server side component? I am new to NextJS, so perhaps my entire setup is wrong?

Code shows up on Codepen but not on my Website

I am completely new to coding and this is my first project, so please help me out with a very simple answer.

I have created a map in Codepen which does very nicely what I want her to do. Once I add it to my website it does not even show up. I have checked with F12, but my issue is, I do not understand the error messages. Here the particular post: https://agora-tours.com/get-to-know-all-visitor-sites-of-the-galapagos-islands-2/

And how I added it for now:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Galapagos Visitor Sites</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css" rel="stylesheet" />
<style>
body {
    margin: 0;
    font-family: "Montserrat", Arial, sans-serif;
}

#map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
}

#sidebar {
    position: absolute;
    top: 0;
    left: 0;
    width: 33%;
    height: 100%;
    background-color: #5e95c2;
    z-index: 2;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

#sidebar.hidden {
    display: none;
}

#sidebar img {
    width: 100%;
    object-fit: cover;
}

#sidebar h2,
#sidebar h3,
#sidebar h4 {
    color: #fff;
    text-align: left;
}

#sidebar h2 {
    text-transform: uppercase;
    font-size: 18px;
    margin: 10px 0;
}

#sidebar h3 {
    font-size: 18px;
}

#sidebar h4 {
    font-size: 18px;
    margin: 10px 0 5px;
}

#sidebar p {
    color: #fff;
    font-size: 18px;
    text-align: left;
}

hr {
    border: none;
    border-top: 1px solid #fff;
    margin: 10px 0;
    width: 100%;
}

#close-sidebar {
    align-self: flex-start;
    background-color: #2b4e6e;
    color: #fff;
    border: none;
    padding: 5px 10px;
    font-size: 18px;
    cursor: pointer;
    margin-bottom: 20px;
    border-radius: 4px;
}

.marker-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: block;
    background-color: #000;
    z-index: 1;
}

.marker-dot.active {
    background-color: #000;
}

.cruise {
    background-color: #ff8000;
}
.day-tour {
    background-color: #5e95c2;
}
.day-tour-diving {
    background-color: #2b4e6e;
}
.liveaboard {
    background-color: #f9b233;
}
</style>
</head>

<body>
    <div id="sidebar" class="hidden">
        <button id="close-sidebar">×</button>
        <div id="sidebar-content">
            <img id="sidebar-image" src="placeholder.jpg" data-image-url="" alt="Visitor Sites of the Galapagos Islands">
            <h2 id="site-name"></h2>
            <p id="site-description"> </p>
            <hr />
            <h4>Island</h4>
            <p id="site-island"></p>
            <hr />
            <h4>Accessibility via</h4>
            <p id="site-accessibility"></p>
            <hr />
            <h4>Activities</h4>
            <p id="site-activity"></p>
        </div>

        <div class="marker-dot cruise"></div>
        <div class="marker-dot day-tour"></div>
        <div class="marker-dot day-tour-diving"></div>
        <div class="marker-dot liveaboard"></div>

    </div>
    <div id="map"></div>
<script>
/* jshint esversion: 6 */

mapboxgl.accessToken =
    "pk.eyJ1IjoiYWdvcmE5OCIsImEiOiJjbTBsY3VoZTkwNDRvMmtweWFraGxoZG1zIn0.swUOxThaoMCZLt4h9yq4lQ";
const map = new mapboxgl.Map({
    container: "map",
    style: "mapbox://styles/mapbox/streets-v11",
    center: [-90.9, -0.5],
    zoom: 7
});

// Define category colors
const categoryColors = {
    Cruise: "cruise",
    "Day Tour": "day-tour",
    "Day Tour Diving": "day-tour-diving",
    Liveaboard: "liveaboard"
};

// List of destinations
const destinations = [
    {
        name: "Las Tintoreras",
        island: "Isabela",
        accessibility: "Day Tour, Day Tour Diving & Cruise",
        activity: "Snorkeling, Walking & Kayaking",
        description:
            'Las Tintoreras is a group of small islets located just off the coast of Puerto Villamil on Isabela Island, known for their stunning volcanic landscapes and abundant wildlife. Accessible by kayak or a short boat ride, this site offers a unique opportunity to observe white-tip reef sharks (locally called "tintoreras") resting in calm lava channels. Visitors can also spot sea turtles, marine iguanas, and Galapagos penguins. The islets are also home to vibrant birdlife, including blue-footed boobies and pelicans.',
        coordinates: [-90.9596, -0.9689],
        image: "https://agora-tours.com/wp-content/uploads/2024/12/IMG_7758-1-scaled.jpg",
        category: "Day Tour"
        }
];
const sidebar = document.getElementById("sidebar");
const sidebarImage = document.getElementById("sidebar-image");
const siteName = document.getElementById("site-name");
const siteIsland = document.getElementById("site-island");
const siteAccessibility = document.getElementById("site-accessibility");
const siteActivity = document.getElementById("site-activity");
const siteDescription = document.getElementById("site-description");
const closeSidebarButton = document.getElementById("close-sidebar");

// Store the initial map center
let initialCenter = map.getCenter();

// Create markers and add event listeners
destinations.forEach((destination) => {
    const markerElement = document.createElement("div");
    markerElement.classList.add(
        "marker-dot",
        categoryColors[destination.category]
    );

    const marker = new mapboxgl.Marker(markerElement)
        .setLngLat(destination.coordinates)
        .addTo(map);
    markerElement.addEventListener("click", () => {
        document
            .querySelectorAll(".marker-dot")
            .forEach((dot) => dot.classList.remove("active"));

        // Add 'active' class to the clicked dot
        markerElement.classList.add("active");

        // Fly map marker location
        map.flyTo({
            center: destination.coordinates,
            zoom: 10,
            essential: true
        });

        // Show sidebar with destination details
        showSidebar(destination);
    });
});
function showSidebar(destination) {
    sidebar.classList.remove("hidden");
    sidebarImage.src = destination.image;
    siteName.textContent = destination.name;
    siteIsland.textContent = destination.island;
    siteAccessibility.textContent = destination.accessibility;
    siteActivity.textContent = destination.activity;
    siteDescription.textContent = destination.description;
}

// Close sidebar
closeSidebarButton.addEventListener("click", () => {
    sidebar.classList.add("hidden");

    // Fly the map back to default
    map.flyTo({
        center: initialCenter,
        zoom: 7,
        essential: true
    });
});
</script>
</body>
</html>

I verified my code, checked with F12 but unfortunately don’t understand the error messages or what exactly I would need to change to get the map displayed. Please help me to learn.