HTMX afterSwap and afterRequest events not raised on swapped content

A list of items with a “load more” button; the response will contain more items and a new button:

<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>

<!-- ... -->

<div id="more">
  <button hx-get="/load-items?page=2"
          hx-on:htmx:after-swap="alert('swapped!')"
          hx-target="#more"
          hx-swap="outerHTML"
  >Load more<button>
</div>

The afterSwap and afterRequest events are not raised / handled. I assume that’s because it removes the original content?

How can I raise and handle the event despite the swap?

Angular CDK drag & drop cdk: Items change with animation

In angular 18 I have implemented a simple component using Angular drag & drop cdk (u can see better examples here):

import {Component} from '@angular/core';
import {
  CdkDrag,
  CdkDragDrop,
  CdkDragPlaceholder,
  CdkDropList,
  moveItemInArray,
} from '@angular/cdk/drag-drop';

@Component({
  standalone: true,
  selector: 'cdk-drag-drop-custom-placeholder-example',
  template: `<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
  @for (movie of movies; track movie) {
    <button (click)="moveUp(movie)">Up</button>
    <button (click)="moveDown(movie)">Down</button>
    <div class="example-box" cdkDrag>
      <div class="example-custom-placeholder" *cdkDragPlaceholder></div>
      {{movie}}
    </div>
  }
</div>`,
  styleUrl: 'cdk-drag-drop-custom-placeholder-example.css',
  imports: [CdkDropList, CdkDrag, CdkDragPlaceholder],
})
export class CdkDragDropCustomPlaceholderExampleComponent {
  movies = [
    'Episode I - The Phantom Menace',
    'Episode II - Attack of the Clones',
    'Episode III - Revenge of the Sith',
    'Episode IV - A New Hope',
    'Episode V - The Empire Strikes Back',
  ];

  moveUp(item: string) {
    const index = this.movies.indexOf(item);
    moveItemInArray(this.movies, index, index - 1);
  }

  moveDown(item: string) {
    const index = this.movies.indexOf(item);
    moveItemInArray(this.movies, index, index + 1);
  }

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
  }
}

this simple code works and when dragging the movies around then there is animation which is moving them in the array,

The problem starts when using the buttons up/down to move the items,
they are switching places but instantly and with no animation at all.

I would love to know how to enable the animation when changing the array manually.
Thanks!

Unhandled Promise Rejection: TypeError: Spread syntax requires …iterable not be null or undefined [closed]

There is an array. Using the forEach() function, I want to list all the elements of this array, and then use the push() method to add other elements to it. However, why does the error “Unhandled Promise Rejection: TypeError: Spread syntax requires …iterable not be null or undefined” appear? Please tell me what I’m doing wrong.

const townList = computed(() => {
    const items: Town[] = [];
    filtredList.value.forEach((group) => {
      items.push(...group.towns);
    });
    return items;
});

When checking the array, Postman outputs the data.

Sequelize Model Not Creating Table in MySQL Database (TypeError: Cannot read properties of undefined (reading ‘define’))

I’m working on a Node.js project using Sequelize with MySQL. The database connection is established successfully, and sequelize.sync({ alter: true }) runs without errors, but my users table is not being created.

Additionally, I’m getting the following error when requiring my model:

TypeError: Cannot read properties of undefined (reading 'define')
at Object.<anonymous> (B:BuildsReact-Expressnakargoserverconfigmodelsuser.models.js:4:29)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Object..js (node:internal/modules/cjs/loader:1689:10)
at Module.load (node:internal/modules/cjs/loader:1318:32)
at Function._load (node:internal/modules/cjs/loader:1128:12)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
at Module.require (node:internal/modules/cjs/loader:1340:12)
at require (node:internal/modules/helpers:141:16)
at Object.<anonymous> (B:BuildsReact-ExpressnakargoserverconfigdbdbConnection.js:24:19)

Here’s my setup:

user.models.js file

const { Sequelize, DataTypes } = require("sequelize");
const { sequelize } = require("../db/dbConnection");

const userModel = sequelize.define(
  "User",
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: Sequelize.UUIDV4,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true,
      },
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  {
    tableName: "users", // ✅ Explicit table name
    timestamps: true,
  }
);

module.exports = userModel; // ✅ Ensure model is exported correctly

db/dbConnection.js file

const { Sequelize } = require("sequelize");
const {
  DATABASE_NAME,
  DATABASE_USER,
  DATABASE_PASSWORD,
  DATABASE_HOST,
  DATABASE_PORT,
} = require("../envExports");

const sequelize = new Sequelize(
  DATABASE_NAME,
  DATABASE_USER,
  DATABASE_PASSWORD,
  {
    host: DATABASE_HOST,
    port: DATABASE_PORT,
    dialect: "mysql",
    logging: console.log, 
  }
);


const userModel = require("../models/user.models"); 

// Function to test database connection
const initializeDB = async () => {
  try {
    await sequelize.authenticate();
    console.log("✅ Database connection established successfully.");

    await sequelize.sync({ alter: true }); 
    console.log("✅ All models were synchronized successfully.");
  } catch (error) {
    console.error("❌ Failed to connect to the database:", error.message);
    process.exit(1); // Exit on critical failure
  }
};

// Function to clean up the connection
const disconnectDB = async () => {
  try {
    await sequelize.close();
    console.log("✅ Database connection closed successfully.");
  } catch (error) {
    console.error(
      "❌ Error while closing the database connection:",
      error.message
    );
  }
};

module.exports = { sequelize, initializeDB, disconnectDB, userModel }; 

Issue:

  • sequelize.authenticate() works fine, and I see “✅ Database connection established successfully.”
  • sequelize.sync({ alter: true }) runs without errors, and “✅ All models were synchronized successfully.” appears in the logs.
  • However, the users table is not being created in MySQL. Running SHOW TABLES; in MySQL does not list users.
  • I have also tried sequelize.sync({ force: true }), but no table is created.

What I Have Tried:

  • Verified that MySQL is running and connected.
  • Checked Sequelize logs (logging: console.log)—no CREATE TABLE statement appears.
  • Restarted nodemon after every change.
  • Manually checked MySQL with SHOW TABLES;.
  • Tried explicitly calling userModel.sync({ force: true }).

Question:

  • Why is my Sequelize model not creating a table in MySQL, and how can I fix the TypeError: Cannot read properties of undefined (reading 'define') error?
  • Any insights would be greatly appreciated!

Upload excel file to Javascript NOT WORKING, NOT PROCESSING

Basically, my code is should allow the user to upload a data file (excel csv file), then use the data inside that uploaded file to create and plot charts and graphs. I have successfully created the upload file button, but once I upload the csv file, nothing is being drawn. I have a feeling there is something wrong in “this.handleFile = function(file)”, and the file is not being read or processed properly, but I’m not sure exactly what it is that’s causing this error.

This is the error I am getting on console:
enter image description here

FYI: The drawing and plotting part of the code is all working fine, since I have tested it out on another file, where the data file being used was a very specific File.

this.setup = function() 
  {
      this.fileInput = createFileInput(this.handleFile.bind(this));
      this.fileInput.position(width/2, 10);
        
      if (!this.loaded) 
      {
          console.log('Data not yet loaded');
          return;
      };

    this.select = createSelect();
    this.select.position(1080,42);

    var sd = this.data.columns;
    for(var i = 1; i < 8; i++)
        {
            this.select.option(sd[i]);
        };
  };
 
    
this.handleFile = function(file) 
{
    if (file.type === 'text') 
    {
        this.data = loadTable(file.data, 'csv', 'header', 
                              function(table) 
                              {
            self.loaded = true;
        });
    }
    return;
};

I’ve played around with the parameters of loadTable, removed the last parameter after header, I’ve tried calling setup in this.handleFile to let the code run again from setup after the data file is loaded.

The excel file NEEDS to be read and the data inside processed to draw things

Redirect to main page when user confirms refresh in React JS

How can I redirect the user to the main page when the user click on this green confirm button (it’s in french btw) :photo of the green confirm button when user clicks on reload button (it's in chrome)

I already have this in the app.js main component but when I try to use the useNavigate() with the navigate function it doesn’t work in the “handleBeforeUnload”. I also tried window.location.href = “/” but still doesn’t work.
Also, it’s a multiplayer game so I use socket.js to connect the client to a server (I don’t know if it changes anything, maybe it helps)

const handleBeforeUnload = (event) => {
        event.preventDefault();
        event.returnValue = ""; // Affiche une confirmation
    };

    useEffect(() => {
        window.addEventListener("beforeunload", handleBeforeUnload)

        return () => {
            window.removeEventListener("beforeunload", handleBeforeUnload)
        }
    }, [])

Second setTimeout lost with autofill Input fields

I have this standard form with User name / password.

enter image description here

When I go to my webpage with the browser I end up in this form and it’s empty. When I click the Name field it will autofill with a suggested option. So far so good.

On the input fields there is an oninputinput () handler function that calls the backend in PHP with jquery $.ajax in tophp (POST).

This is the issue. Both Name and Password are set with autofill but only the password ends up at the backend PHP. To be stored in the session. The request that will store the Name is lost. So when submitting this form the session doesn’t find the Name and it will give an error.

I find that the $.ajax call with the value for the Name input field is not fired. It’s lost somewhere and I don’t know why. Here is my code:

enter image description here

And here is the console.log after the autofill takes place. The first call is added to the timeout variable but never fires.

enter image description here

Any clue as to why the request is lost? This happens when I load the page. When I manually type Name and login, then logoff and use autofill, it will work accordingly. Both requests are written into the session.

Laravel Interverntion arabic text from left to right no matter what

im using laravel 11. and laravel intervention with imagick driver.
when i save an image with arabic text. in my localhost it writes from right to left.
but somehow on my ubuntu server its from left to right.
used all arabic fonts they are displayed and connected but not RTL

i tried all deffrent types of fonts tried to align right with intervention didnt work. nothing is working my server

Track the connection status from the backend?

I am Working on a Chat Application developed By laravel (Laravel Reverb) and reactjs.

Two Projects are developed separately and also i am configuring with Laravel Passport.

The Backend basically serve the Api and Chat server where the frontend configuring the chat server and implementing Apis.

For Tracking User Activity (Online or Offline Status) I am Configuring Presence Channel.

Previously, my task was, when a user connected to the channel A User History Saved on Redis. Which Perfectly Work without any issue.

Now I am trying to configure user disconnected system. When a user is disconnected from the channel it will remove that user history from Redis.

Now Every where i am founding calling a api from frontend so that it can remove that entity.

But I need to Determine the user disconnection from Backend cause When connection stablish i can see Connection stablish message on debug panel and also connection closed message inside debug console.

So I think i can track the connection and disconnection from the server side rather than implementing something on frontend.

So is there a way to track the connection status from the backend side? I can’t Handel The Laravel Reverb Disconnect When Tab is closed

I am giving you the whole code. So that any one can understand what is doing and what to do next.

<?php

namespace AppListeners;

use AppEventsUserStatus;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesRedis;

class UserStatusListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(UserStatus $event): void
    {
        $user_id = $event->user_id;
        $status = $event->status;

        Log::info("User Status Changed: User ID {$user_id} is now {$status}");

        if ($status === "connected") {
            // Store user as online in Redis
            Redis::setex("user:online:{$user_id}", 300, json_encode([
                'user_id' => $user_id,
                'status' => 'online',
                'last_seen' => now()->toDateTimeString(),
            ]));
        } elseif ($status === "disconnected") {
            // Remove user from Redis (user disconnected)
            Redis::del("user:online:{$user_id}");
        }
    }
}

This is my UserStatusListner Where I am determining the User Connected status and store this inside Redis.

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateContractsBroadcastingShouldBroadcastNow;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;


class UserStatus implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $user_id;
    public $status;

    /**
     * Create a new event instance.
     */
    public function __construct($user_id, $status)
    {
        $this->user_id = $user_id;
        $this->status = $status;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, IlluminateBroadcastingChannel>
     */
    public function broadcastOn()
    {
        return new PresenceChannel('presence-user-status-'.$this->user_id);
    }

    public function broadcastAs()
    {
        return 'user.status'; // Custom event name
    }
}

This is my UserStatus Event Where i called when a Presence Channel is successfully connected.

Broadcast::channel('presence-user-status-{user_id}', function ($user, $user_id) {
    // Check the authenticated user from multiple guards
    $staffUser = Auth::guard('staff_users')->user();
    $businessUser = Auth::guard('business_users')->user();
    $normalUser = Auth::guard('users')->user();

    $userData = [];
    if ($normalUser && (int) $normalUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $normalUser->user_id,
            'type' => "user"
        ];

    }

    if ($businessUser && (int) $businessUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $businessUser->user_id,
            'type' => "business"
        ];
    }

    if ($staffUser && (int) $staffUser->staff_id === (int) $user_id) {
        $userData = [
            'user_id' => $staffUser->staff_id,
            'type' => "staff"
        ];
        
    }

    if (!empty($userData)) {
        Redis::setex("user:online:{$user_id}", 300, json_encode([
            'user_id' => $userData['user_id'],
            'type' => $userData['type'],
            'last_seen' => now()->toDateTimeString(),
        ]));
        
        // Fire the UserStatus event for tracking
        event(new UserStatus($userData['user_id'], 'connected'));
        return $userData;
    }

    return false; 
});

This is my channel Code of the Presence Channel inside routes/channels

Here When user is online i can store the data into Redis but when a user is disconnect i can’t track that. Anyone have any advise or any way to resolve this issue?

N.B – I am Using Laravel 10 Version.

How to get all elements inside body with PHP DomDocument [duplicate]

I’m trying to parse an Html string that may contain any valid html tags. I used this code to parse the string:

$doc = new DOMDocument();
$doc->loadHTML($product['description']); // comes from db
$els = $doc->getElementsByTagName('*');
foreach ($els as $node) {
    o($node->nodeName.' '.$node->nodeValue);
}

This does print my tags but the first two tags are html and body. I want to ignore those. The string from the db does not contain html or body tags. Here’s an example:

<p>This is a paragraph</p>
<ol>
    <li>This is a list</li>
</ol>

I was wondering if there’s a way to iterate over tags inside the body only. I tried these

$els = $doc->getElementsByTagName('body *');

$body = $doc->getElementsByTagName('body');
$els = $body->getElementsByTagName('*');

Both don’t work. I have seen others use xpath but that gives me headaches. Can it be done with DomDocument?

How can I with implement ajax based numbered pagination to posts which are displayed via ajax?

What I’m trying to accomplish is producing numbered pagination for posts which are loaded via an ajax function. I have to make the numbered pagination work via ajax as well. Explanation of each code block below:

This function produces taxonomy terms which currently have posts assigned. Code resides in functions.php.

<?php
    function ee_event_categories() {
      $event_cats = get_terms( array(
        'taxonomy' => 'tribe_events_cat',
        'hide_empty' => true,
      ) );
    ?>
        <div class="filter-column category-block">
          <?php foreach ( $event_cats as $event_cat ) : ?>
            <button 
              data-taxonomy="<?php echo $event_cat->taxonomy; ?>" 
              data-slug="<?php echo $event_cat->slug; ?>"
              data-term-id="<?php echo $event_cat->term_id; ?>">
              <?php echo $event_cat->name; ?>
            </button>
          <?php endforeach; ?>
        </div>
    <?php
      $cat = ob_get_clean();
      return $cat;
    }
    add_shortcode( 'ee_event_categories', 'ee_event_categories' );
?>

Upon clicking on the resulting buttons from the previous function, a custom WP_Query runs and displays posts that match the criteria in the function below. This function resides in functions.php. I think I have to pass the $paged variable from the load_events_by_category() function into the javascript code. Unfortunately, I’m at a loss as to how to do it. Maybe the $paged variable needs to be applied as a second key / value pair in the wp_localize_script() declaration? Now I’m thinking out loud.

<?php
function load_events_by_category() {
  $paged = ($_POST['paged']) ? $_POST['paged'] : 1;
  $taxonomy = $_POST['taxonomy'];
  $slug = $_POST['slug'];
  $term_id = intval($_POST['term_id']);
    $category_events_args = array(
      'post_type'       => 'tribe_events',
      'posts_per_page'  => 4,
      'post_status'     => 'publish',
      'eventDisplay'    => 'custom',
      'order'           => 'ASC',
      'paged'           => $paged,
      'tax_query' => array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field'    => 'term_id',
          'terms'    => $term_id
        )
      )
    );
    $catquery = new WP_Query( $category_events_args );
    ob_start(); 
    if( $catquery->have_posts() ) : ?>
      <div class="this-weeks-events">
        <div class="featured-events-grid">
          <?php while ( $catquery->have_posts() ) : $catquery->the_post(); ?>
            <div class="featured-events-grid-child">
              <div class="event-date"
                data-taxonomy="<?php echo $taxonomy ?>"
                data-slug="<?php echo $slug; ?>" 
                data-term-id="<?php echo $term_id; ?>" 
                style="background:<?php echo the_field('event_category_background', $taxonomy . '_' . $term_id ); ?>"
              >
                <p class="event-day"><?php echo tribe_get_start_date( $event_id, false, 'D' ); ?></p>
                <p class="event-start-date" style="color:<?php echo the_field('event_date_color', $taxonomy . '_' . $term_id ); ?>"><?php echo tribe_get_start_date( $event_id, false, 'j' ); ?></p>
                <p class="event-month"><?php echo tribe_get_start_date( $event_id, false, 'F' ); ?></p>
              </div><!-- end div event-date -->

              <?php if( has_post_thumbnail() ) : ?>
                <div class="featured-image">
                  <a href="<?php echo the_permalink(); ?>"><?php the_post_thumbnail( 'full' ); ?></a>
                </div><!-- end div featured-image -->
              <?php endif; ?>
              <div class="featured-events-details-grid">
                <div><h2><a href="<?php echo the_permalink(); ?>"><?php the_title(); ?></a></h2></div>
                <div>
                  <i class="far fa-clock" aria-hidden="true"></i>
                  <?php echo tribe_get_start_time( $event_id ); ?>
                  -
                  <?php echo tribe_get_end_time( $event_id ); ?>
                  <?php if( tribe_is_recurring_event() ) : ?>
                    <p class="event-recurring"><img src="<?php echo get_stylesheet_directory_uri() . '/images/arrows-rotate.webp' ?>" alt="rotating arrow icon for weekly events" width="20" height="20" /> Weekly Event</p>
                  <?php endif; ?>
                </div>
              </div><!-- end div featured-events-details-grid -->
            </div><!-- end div featured-events-grid-child -->
          <?php endwhile; ?>
        </div><!--end featured events grid -->        
        <?php
          $nextpage = $paged+1;
          $previouspage = $paged-1;
          $total = $catquery->max_num_pages;
          $pagination_args = array(
            'base'                => '%_%',
            'format'              => '?paged=%#%',
            'total'               => $total,
            'current'             => $paged,
            'show_all'            => false,
            'end_size'            => 1,
            'mid_size'            => 2,
            'prev_next'           => true,
            'prev_text'           => __('<span class="prev" data-attr="'.$previouspage.'">&laquo;</span>'),
            'next_text'           => __('<span class="next" data-attr="'.$nextpage.'">&raquo;</span>'),
            'type'                => 'plain',
            'add_args'            => false,
            'add_fragment'        => '',
            'before_page_number'  => '',
            'after_page_number'   => ''
          );
          $paginate_links = paginate_links($pagination_args);

          if ($paginate_links) : ?>
            <div id='pagination' class='pagination'>
              <?php echo $paginate_links; ?>
            </div>
          <?php endif; ?>
      </div><!-- end div this weeks events -->
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
    <?php
      $content = ob_get_clean();
      echo $content;
      die();
}
add_action( 'wp_ajax_load_events_by_category', 'load_events_by_category' );
add_action( 'wp_ajax_nopriv_load_events_by_category', 'load_events_by_category' );
?>

I’m not sure if this is important but I’ll include it anyway. It’s how I’m using wp_localize_script, also located in functions.php.

<?php wp_enqueue_script( 'ajax-load-category-events', get_stylesheet_directory_uri() . '/dist/ajax-category-events.js', array( 'jquery' ), '1.0', true ); 
wp_localize_script( 'ajax-load-category-events', 'categoryevents', array(
  'ajaxurl'   => admin_url( 'admin-ajax.php' )
));
?>

And finally, here’s the code in above javascript file.

(function ($) {
  $(".category-block button").on('click', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: categoryevents.ajaxurl,
      data: {
        action: 'load_events_by_category',
        taxonomy: $(this).data('taxonomy'),
        slug: $(this).data('slug'),
        term_id: $(this).data('term-id')
      },
      success: function (html) {
        $('#fl-main-content').find('#event_results .fl-rich-text').empty();
        $('#event_results .fl-rich-text').append(html);
      },
      error: function (error) {
        console.log("Error: ", error)
      }
    })
  });
})(jQuery);

I actually did try passing the $paged variable into the script vars of the wp_localize_script declaration. I thought that would at least make the javascript “aware” of what page of results were showing.

wp_localize_script( 'ajax-load-category-events', 'categoryevents', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'paged' => $_POST['paged'] ? $_POST['paged'] : 1; ));

I also spent hours upon hours reviewing similar SO questions and looking for tutorials on how to solve this problem. I’ll be darned but it doesn’t seem using ajax pagination inside ajax produced content is much of a thing.

Calculating Distance Between Colours Using PHP

I am converting an image to use a specific colour palette using PHP. My code is successfully looping through each colour in the source image, and comparing it to the colour palette, and finding the closets colour. However, sometimes I get some odd matches.

I have found many colour distance equations on StackOverflow (and other resources) but none are returning better matches.

Here is the palette I’m using:

enter image description here

Here is the palette n a PHP array:

$colours = array(
    '#B3D7D1',
    '#DD982E',
    '#AD6140',
    '#c01111',
    '#F47B30',
    '#E0E0E0',
    '#184632',
    '#A0BCAC',
    '#923978',
    '#F785B1',
    '#61AFFF'
);

And here is a testing image I am converting:

enter image description here

However, a few of the greens are being matched to the dark purple, here is my result:

enter image description here

And here is the equation I’m using to calculate colour distance:

$distance = sqrt($delta_r * $delta_r + $delta_g * $delta_g + $delta_b * $delta_b);

Here is the RGB of the colour I’m trying to find a match for and the one my code matches it with:

Array ( [0] => 116 [1] => 136 [2] => 115 )
Array ( [0] => 146 [1] => 57 [2] => 120 )

Which returns a distance of 85.

Just a note, the green that I was expecting to get matched gets a distance of 88.

Mathematically the dark purple is the closet colour. But visually it’s not. Does anyone know of a better equation I can use? Maybe one that considers the overall colour instead of just the individual parts?

Full code is available here:
https://github.com/codeadamca/php-colour-palette/

Use Frdia Stalker for all threads

I want to use Frida Stalker for all the threads in the remote process.

The problem is that there are lot of threads in the process so if I tried to use Process.enumerateThreads to use Stalker.follow for each one of them the process crashed because that takes lot of time and until that the process is stop. `

I don’t want to handle the crashed (watchdog etc.) Is there another light way , maybe an API without thread id, so I can use Stalker.follow for all tids ?

Here is the example code

function StalkerExeample() 
{
    var threadIds = [];

    Process.enumerateThreads({
        onMatch: function (thread) 
        {
            threadIds.push(thread.id);
            console.log("Thread ID: " + thread.id.toString());
        },

        onComplete: function () 
        {
            
            threadIds.forEach(function (threadId) 
                {
                    Stalker.follow(threadId, 
                    {
                        events: {call: true , ret: true, exec: true ,block: true},
                    
                    onReceive: function (events)
                    {
                        console.log("onReceive called.");
                    },
                    onCallSummary: function (summary)
                    {
                        console.log("onCallSummary called.");
                    }
                });
            });
        }
    });
}


StalkerExeample();

AJAX Error on data.message return “undefined” [closed]

I am using Ajax to fetch data and send the data to google sheet.
However, the alert(data.message); is returning undefined but when I put **data.data.message it works.
**

Question: Why it is returning value if I will use data.data.message but not on data.message?

document.addEventListener('click', function(event) {
    if (event.target.classList.contains('book-now')) {
        let jobId = event.target.dataset.jobId; // Get job ID from button
        let row = event.target.closest('tr');

        fetch(jobBookingAjax.ajaxurl, { // Make sure this prints correctly in console
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'book_job',
                nonce: jobBookingAjax.nonce,
                job_id: jobId
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log(JSON.stringify(data));
            if(data.success) {
                alert(data.data.message);
                row.remove();
            }else{
                alert("Error: " + data.data.message);
            }
        })
        .catch(error => console.error('Error:', error));
    }
});

For some reason the alert(data.data.message); is working but not the data.message kind of weird.

Expected code should be alert(data.message);

Unable to get desired output for reactjs frontend project as css isn’t working while running on browser

Css for the current project my-dashboard is not working inside the browser on running the project through npm start.

I also tried installing, uninstalling, downgrading TailwindCSS multiple times. As in latest version in node_modules/tailwindcss/lib/cli.js lib folder does not existed. So current version now used is TailwindCSS v3.4.1.

package.json

{
  "name": "my-dashboard",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js",
    "postinstall": "tailwindcss init -p"
  },
  "dependencies": {
    "@fortawesome/free-solid-svg-icons": "^6.7.2",
    "@fortawesome/react-fontawesome": "^0.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.20",
    "postcss": "^8.5.2",
    "tailwindcss": "^3.4.1"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

postcss.config.css

module.exports = {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
  };

tailwind.config.js

module.exports = {
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jarvis CRM Dashboard</title>
    <link rel="stylesheet" href="%PUBLIC_URL%/index.css">
</head>
<body>
    <div id="root"></div>
</body>
</html>

Dashboard.js

import React, { useState, useEffect } from "react";
import Sidebar from "./components/Sidebar.js";
import DashboardCard from "./components/DashboardCard.js";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEnvelope, faBookmark, faUpload, faStar } from "@fortawesome/free-solid-svg-icons";
import "./index.css";

const Dashboard = () => {
    const [stats, setStats] = useState([]);
    const [currentPage, setCurrentPage] = useState("Dashboard");

    useEffect(() => {
        // Simulating API call
        setTimeout(() => {
            setStats([
                { icon: faEnvelope, label: "Messages", value: "1,410", color: "border-blue-500" },
                { icon: faBookmark, label: "Bookmarks", value: "410", color: "border-green-500" },
                { icon: faUpload, label: "Uploads", value: "13,648", color: "border-yellow-500" },
                { icon: faStar, label: "Likes", value: "93,139", color: "border-red-500" }
            ]);
        }, 1000);
    }, []);

 return (
    <div className="flex h-screen">
    {/* Sidebar */}
    <div className="w-64 bg-gray-800 text-white h-screen fixed">
        <Sidebar onMenuClick={setCurrentPage} />
    </div>
    
    {/* Main Content (Pushes aside for sidebar) */}
    <div className="flex-1 p-6 bg-gray-100 ml-64">
        <h1 className="text-xl font-bold">{currentPage}</h1>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
            {stats.map((stat, index) => (
                <DashboardCard key={index} icon={stat.icon} label={stat.label} value={stat.value} color={stat.color} />
            ))}
        </div>
    </div>
</div>


    );
};


export default Dashboard;

index.css

@import "tailwindcss/base";

@import "tailwindcss/components";

@import "tailwindcss/utilities";

/* Global Reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
}

/* Layout */
.app-container {
    display: flex;
    height: 100vh;
    background-color: #f4f4f4;
}

/* Sidebar */
.sidebar {
    width: 250px;
    background-color: #fff;
    padding: 20px;
    box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.sidebar h2 {
    font-size: 18px;
    text-align: center;
    font-weight: bold;
}

.sidebar ul {
    list-style-type: none;
    padding: 10px 0;
}

.sidebar li {
    padding: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
}

.sidebar li:hover {
    background-color: #e0e0e0;
}

/* Main Content */
.main-content {
    flex: 1;
    padding: 20px;
}

.dashboard-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.card {
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
}

.card i {
    font-size: 30px;
    margin-right: 10px;
}

index.js

import React from "react";
import ReactDOM from "react-dom";
import Dashboard from "./Dashboard";
import "./index.css";

ReactDOM.render(
    <React.StrictMode>
        <Dashboard />
    </React.StrictMode>,
    document.getElementById("root")
);

reportWebVitals.js

const reportWebVitals = onPerfEntry => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;

DashboardCard.js

import React from "react";

const DashboardCard = ({ icon, label, value, color }) => (
    <div className={`flex items-center p-4 bg-white shadow-md rounded border-t-4 ${color}`}>
        <i className={`fas fa-${icon} text-3xl mr-4`}></i>
        <div>
            <p className="text-sm text-gray-600">{label}</p>
            <p className="text-xl font-bold">{value}</p>
        </div>
    </div>
);

export default DashboardCard;

Sidebar.js

import React from "react";

const Sidebar = ({ onMenuClick }) => {
    const menuItems = [
        { name: "Dashboard", icon: "fa-home" },
        { name: "Departments", icon: "fa-building" },
        { name: "Projects", icon: "fa-folder" },
        { name: "Tasks", icon: "fa-tasks" },
        { name: "Task Status", icon: "fa-list" },
        { name: "Users", icon: "fa-users" },
        { name: "Roles", icon: "fa-user-tag" },
        { name: "Permissions", icon: "fa-lock" },
        { name: "Settings", icon: "fa-cog" },
        { name: "Activity Logs", icon: "fa-history" },
    ];

    return (
        <div className="w-64 bg-white h-full shadow-md p-4">
            <h2 className="text-center font-bold text-lg">Jarvis | A CRM</h2>
            <ul className="mt-4">
                {menuItems.map((item, index) => (
                    <li key={index} className="p-4 hover:bg-gray-200 cursor-pointer"
                     onClick={() => onMenuClick(item.name)}>
                        <i className={`fas ${item.icon} mr-3`}></i>
                        {item.name}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Sidebar;

Folder paths images and other images are as follows:

Note: This is my first React or JavaScript project