Not getting data from jquery in codeigniter controller

500Getting Error like 500 (Internal Server Error)

jquery-3.6.0.js:10109 POST http://localhost/Banner_module/public/index.php/delete 500 (Internal Server Error)

HTML code:

  • <td><button type="button" value="<?= $row['bid'];?>" class="cd btn btn-outline-danger">Delete</button></td>

jquery Code:

$.ajax({
          type: "POST",
          url: "<?= site_url('delete') ?>",
           data: {"bid": bid}
         })

Routes :

$routes->post('delete','Home::delete');

controller:

public function delete(){

    

$user = new Bmodel();

    //$bid = $this->input->post('uid',true);
    $bid = $this->input->post('bid');
 
    // $data = array(
    //     'uid'  => $this->input->post('uid')
    //     );
    // $uid= json_encode($data);

    $data['user'] = $user->where('bid', $bid)->delete($bid);
   
    $response = ['status'=> "Deleted", 'status_text'=>'Deleted','status_icon'=>'success'];
    return $this->response->setJSON($response);
       }

Automate layer publishing in Geoserver

I have my shapefiles stored in the PostGIS table. now, I need to automate the process of publishing these tables on GeoServer. the overall process is that I am getting geojson from a remote server and storing it in the PostgreSQL database. this is being done using HTML, javascript, and PHP on button click event. now I want to create another functionality to publish newly added tables on GeoServer. I have created a workspace and data store in GeoServer and a bat file to publish these tables. but I want to do it on a button click event. Is there a way to execute the bat file in JavaScript? or any other workaround for the whole functionality?

the curl (.bat file) I am using is (http://www.snippetbymatt.com/2017/03/publish-postgis-layers-in-geoserver.html):

for /f %%a in (<list of tables you want to publish>.txt) do  curl -v
 -u <username>:<password>  -XPOST -H "Content-type: text/xml" -d "<featureType><name>%%a</name></featureType>"
 http://localhost:8080/geoserver/rest/workspaces/<name of
 workspace>/datastores/<name of store>/featuretypes pause

how to add cells to specific column in html

i added into table using .append in jquery and i need to add last colum with its cells

OR i need to add linkes into “PDF Files Link” column

<table class="table">
  <thead>
    <tr>

      <th scope="col">thumbnails</th>
      <th scope="col">Title</th>
      <th scope="col">authr</th>
      <th scope="col">PDF Files link</th>
    </tr>
  </thead>
  <tbody id="employee_table">

    </tr>
  </tbody>
</table>

and this my jquery code

    var videode='<tr><td><div class="video vidEle" style="width:42%;height:108px;" data-id="'+vid_id+'" ><a href="#top"><img class="v-img" style="width:79%;height:92px;" src="'+vid_thumb+'"/><i class="play-btn fa fa-play" style"top:72% !important"></i></a></div></td><td><div class=""data-id="'+vid_id+'" ><a href="#top"><div class="v-title">'+vid_title+'</div></a></div></td><td><p>'+channelTitle+'</p></td></tr>'
$('#employee_table').append(videode);

finally need to add linkes into “PDF Files Link” column

how can I hide parent div if all the children are “display:none”

I have this HTML block

 <div class="abc">
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: none;">xyz</div>
    </div>
    <div class="abc">
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: block;">xyz</div>
       <div class="xyz" style="display: block;">xyz</div>
     </div>

I want to hide all the parent div if it contains all the “display:none” div else I want to show parent div..

Page Auto Reloads, When I Write/Append File on Websocket

Whenever i try to run this code. All works fine, Writing is done correctly in the file as well, but everytime append runs, the page reloads for some reason…. any way to stop that reload? I have tried Using SetTimeout… But that just delays reloading. does not acutally stop the reload error…. This is my first question here as well. Any Help would be appreciated

//server side JS -----------------------------------

const http = require('http').createServer();
const fs = require('fs');

const io = require('socket.io')(http, {
    cors: { origin : "*" }
});


io.on('connection', socket => {

    console.log('A User Connected!');

    socket.on('message', message => {

        console.log(message);
        let display = `${socket.id.substr(0,2)} Says:  ${message}`;
        io.emit('message', display);

        display += 'n';
        fs.appendFileSync('data.txt', display);
          

    });

});


http.listen(8080, () => console.log('listening on http://localhost:8080 ') );

//Client-side Js -----------------------------------

const socket = io('ws://localhost:8080');

socket.on('message', text => {

    const el = document.createElement('li');
    el.innerHTML = text;
    el.style.marginLeft = '500px';
    document.querySelector('ul').append(el);
    
});

document.getElementById('btn').onclick = () => {


    if(document.querySelector('input').value != ''){
        const text = document.querySelector('input').value;
        socket.emit('message', text);
        document.querySelector('input').value = '';

    }

}
document.addEventListener('keydown', (e) => {
    
    if(e.key === 'Enter' && document.querySelector('input').value != ''){
        const text = document.querySelector('input').value;
        socket.emit('message', text);
        document.querySelector('input').value = '';

    }

});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Sockets Testings!</title>
    <script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
    <script defer src="app.js"></script>
</head>
<body>
    
    <input placeholder="message!">
    <button id="btn" onsubmit="return myFunction();">Send!</button>


    <ul>
    </ul>


</body>
</html>

ns, the page refreshes… Any Fixes..?

React – how to update the value using useState dynamically

Current UI:
enter image description here

There are 2 ways of updating the value of currentPercentage.

1.Scrolling
2.Click the button to update the percentage

For (1), I use react-scroll-percentage library to get the percentage.
For (2), I create 2 buttons to update the value of currentPercentage

I want to set the percentage of currentPercentage dynamically but I can’t find a way to handle it.

App.js

import "./styles.css";
import { useScrollPercentage } from "react-scroll-percentage";
import { useState } from "react";

export default function App() {
  const [ref, percentage] = useScrollPercentage({
    threshold: 0
  });

  // how to set the value of currentPercentage to percentage, while I can change the percentage by button
  const [currentPercentage, setCurrentPercentage] = useState(0);

  const onBtnClick = (num) => {
    setCurrentPercentage(num);
  };

  return (
    <div className="App" ref={ref}>
      <button
        onClick={() => {
          onBtnClick(50);
        }}
      >
        Change to 50%
      </button>
      <button
        onClick={() => {
          onBtnClick(100);
        }}
      >
        Change to 100%
      </button>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
    </div>
  );
}

Codesandbox
https://codesandbox.io/s/still-brook-hqb92?file=/src/App.js:0-2242

How to replace Mapbox default popup with customized information

I am kind of new to ReactJS and am working on a project that displays markers at different points, with the data being received from a JSON file. Currently, I am using popups to display information when the marker is being clicked on, as shown:

//Map.js
geoJson.features.forEach((location, i) => {
      const el = document.createElement("div");
      el.className = "marker";
      var marker = new mapboxgl.Marker(el)
        .setLngLat(location.geometry.coordinates)
        .setPopup(
          new mapboxgl.Popup({ offset: 0, className: "popup" }).setHTML(`
            <div>
              <h1>${location.properties.title}</h1>
              <p>${location.properties.description}</p>
              <a class="popupbutton" target="_blank" href=${location.properties.link}>
                <button class="popupbutton">Website Link</button>
              </a>
            </div>
          `)
        )
        .addTo(map);
      marker.getElement().addEventListener("click", () => {
        zoomIn(i);
      });
    });

As shown above, the popup is currently displaying the title and description of each marker, provided by the data in the JSON file. However, I would like to use something more modern and versatile to display this information, such as a Grommet Card (https://v2.grommet.io/card), since the current Mapbox Popup is not very appealing. How would I go about doing this?

How to know Swiper.js is not moving? (velocity = 0)

I’m using Swiper.js in my React project. It’s in swipeable free mode with autoplay. I will stop the autoplay when touchstart event is triggered, and resume the autoplay after touchend.

However, it’ll be awkward if the autoplay resumes immediately after the user release their finger since there’s still momentum velocity caused by the swipe. I wonder if there’s a way to detect the swiper stops, i.e. the velocity equals zero. I think the proper timing to resume autoplay is after the swiper stops for a while.

The following is my current workaround, wait 1 second until resuming the autoplay: (I also purposely slow down the momentum effect)

import React, { useRef, useState, useEffect } from "react";
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/css";
import "swiper/css/bundle";
import "swiper/css/free-mode"
import "swiper/css/pagination"
import "./App.css";

// import Swiper core and required modules
import SwiperCore, {
  Autoplay,
  FreeMode, Pagination
} from 'swiper';

// install Swiper modules
SwiperCore.use([FreeMode, Autoplay, Pagination]);

export default function App() {

  const swiperRef = useRef(null);
  let disableAutoPlayTimer = null;

  useEffect(() => {
    const swiper = swiperRef.current;
    // subscribe event
    swiper.addEventListener("touchstart", touchStartHandler);
    swiper.addEventListener("touchend", touchEndHandler);
    return () => {
      // unsubscribe event
      swiper.removeEventListener("touchstart", touchStartHandler);
      swiper.removeEventListener("touchend", touchEndHandler);
    };
  }, []);

  const touchStartHandler = (e) => {
    swiperRef.current.swiper.autoplay.stop();
  }

  const touchEndHandler = (e) => {
    // I'm now using a timer to wait 1 second for the swiper to stop
    if (!disableAutoPlayTimer) {
      disableAutoPlayTimer = setTimeout(() => {
        swiperRef.current.swiper.autoplay.start();
        disableAutoPlayTimer = null;
      }, 1000);
    }
  }

  return (
    <>
      <Swiper
        dir="rtl"
        slidesPerView="auto"
        spaceBetween={30}
        freeMode={{
          enabled: true,
          momentumVelocityRatio: 0.5
        }}
        loop={true}
        loopedSlides={9}
        grabCursor={true}
        autoplay={{
          "delay": 0,
          "disableOnInteraction": false
        }}
        speed={1000}
        className="mySwiper"
        ref={swiperRef}
      >
        <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
        <SwiperSlide><span style={{color: 'red'}}>Slide 3</span></SwiperSlide>
        <SwiperSlide>Slide 4</SwiperSlide>
        <SwiperSlide>Slide 5</SwiperSlide>
        <SwiperSlide>Slide 6</SwiperSlide>
        <SwiperSlide>Slide 7</SwiperSlide>
        <SwiperSlide>Slide 8</SwiperSlide>
        <SwiperSlide>Slide 9</SwiperSlide>
      </Swiper>
    </>
  )
}

All in all, my question is, “How to know the current velocity of Swiper.js?”, or “How do I know the swiper is not moving?”
Any idea?

focus on an input that is located inside another component in vuejs?

I would like to be able to focus on input field when certain keys are entered. The input I would like to focus on exists inside autocomplete-vue.
This is where I call it:

<autocomplete v-shortkey="['alt', 's']"
              @shortkey.native="theAction()"
              ref="autocompleteInput" 
></autocomplete>

theAction method which I would like to allow me to focus on the input, looks like this:

theAction () {
      this.$refs.autocompleteInput.$el.focus()
    }

this focus on the whole section which is not what I want. the input exists 2 divs inside the what theAction focuses on. For bettere perspective, this is what this.$refs.autocompleteInput.$el returns :

<div>
  <div data-position="below" class="autocomplete"> 
     <input role="combobox" class="autocomplete-input"> 
  </div>
</div>

Any ideas on how I can focus on the input with class autocomplete-input? any suggestion is helpful!

Fast API ‘422 Unprocessable Entity’ on multiple file post with Axios

Getting ‘422 Unprocessable Entity’ trying to post a list of files to a FastAPI route.

Python:

@app.post("/upload-images/")
async def images(images: List[UploadFile] = File(...)):
    
    for image in images:
        print(image.filename)

Javascript:

    async function handleUpload() {
    if (files.length > 0) {
      const formData = new FormData();

      Array.from(files).forEach((f) => {
        formData.append("images[]", f);
      });

      console.log(formData.getAll("images[]")); //can see the images appended properly
      const imageUploadResponse = await axios
        .post("/upload-images/", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          // toast.error("Woops. Image upload failed.");
        });
    }
  }

I’ve also tried just appending the array with no luck:

formData.append("images", files);

Can someone please let me know what I am doing wrong?

How to access two HTML files classes at the same time?

I want to access two HTML files classes at the same time. The first function takes the classes of index.html & the second function takes the class of cart.html but it is not getting the .cart-items class and gives me the else-statement.

I don’t want to use getElementByClassName() in the second function because it gives me nodes. Instead, I want to get the original HTML text using querySelector() so that I could use it to add the items in cart.html

function addToCartClicked(event) {
    var Title, Price, Image
    var button = event.target
    var shopItem = button.parentElement.parentElement.parentElement.parentElement
    var title = shopItem.getElementsByClassName("name-of-product")[0].innerText
    var price = shopItem.getElementsByClassName('product-price')[0].innerText
    var image = shopItem.getElementsByClassName("hover-img")[0].src

    let itemsList = {
        Title: title,
        Price: price,
        Image: image,
    }    
    let cartItems = {
        [itemsList.Title]: itemsList
    }
    localStorage.setItem("productsInCart", JSON.stringify(cartItems)); // It stores the data in localstorage.
    addItemToCart(title, price, image);
}

function addItemToCart(title, price, image) {
    var cartItems = document.querySelector(".cart-items");
    if (cartItems) {
        console.log(cartItems);
    } else {
        console.log("not getting the HTML code.")
    }
}

cart.html

<tbody class="cart-items"> 
    <tr class="cart-row">
        <td class="image" data-title="No"><img src="../../static/images/32.jpg" alt="#"></td>
        <td class="product-des" data-title="Description">
            <p class="product-name"><a href="#">Women Dress</a></p>
        </td>
        <td class="price" data-title="Price"><span>$200.00</span></td>
    </tr>
</tbody>

Google Apps Script (Spreadsheet) – selecting an array in spreadsheet based on a condition in cells

I am trying to select an array from google sheets to create google calendar events based on that. The code chunk below runs just fine and gets the job done. But I want to be able to only select the range that has value of “select” in their column D.
I know it is probably a very easy answer but I am new to JS.

function calendarSync() {
    var spreadSheet = SpreadsheetApp.getActiveSheet;
    var eventCal = CalendarApp.getCalendarById(calendarId);
// Below instead of selecting the entire range I only need the rows that have a value of "select" in their D cell.
    var eventArray = spreadSheet.getRange("A1:D100").getValues();
    
    for (x=0; x<eventMatrix.length; x++){
      var calEvent = eventArray[x];
      var eventName = calEvent[0]
      var startTime = calEvent[1];
      var endTime = calEvent[2];
      
      eventCal.createEvent(eventName, startTime, endTime);
    }

Discord JS v13 Reaction Collector not working

I’ve been trying for a really long time to make it work, I tried the await version too but none of them collect the reactions. The collector completes its cycle, but then it shows that no reaction was collected.

        if (command == 'react') {

        const filter = (reaction,user) => {
            return user.id === message.author.id;
        }
        
        const collector = message.createReactionCollector({
            filter,
            max: 1,
            time: 1000 * 5,
        })

        collector.on('collect',(reaction) =>{
            console.log(reaction.emoji);
        })

        collector.on('end',(collected) =>{
            console.log(collected);
        })
    }

Error in Jest Test, it wants me to test lines

I am new to testing. I have an error on 3 lines in my react project, but I am not sure what to test for. I have done a few tutorials and understanding how to run a test. However on this project, it wants me to test:

  1. setToggle(!toggle);
  2. setActive(!active);
  3. the render
    But I am not sure what I kind of tests I am suppose to run. How do I know what type of test to run based on the the line info they give me?
    enter image description here