Vue 3 datatable plugin how to add action buttons?

I am using vue3 and laravel inertia for this project. How do I add a custom action button in the last column? Currently I tried by doing and the handleUser() function isnt working or triggering, i got only a console.log there.

jquery datatables for vue 3

const { users } = defineProps({
    users: Object
})

const usersData = computed(() => {
    return toRaw(users).map(user => {
        return [
            user.id_number,
            user.name,
            user.email,
            user.course.name,
            user.school_year,
            user.subject_code,
            user.phone_number,
            user.is_active ? `<span class="badge rounded-pill text-bg-primary">Approved</span>` : `<span class="badge rounded-pill text-bg-danger">Pending</span>`,
           `<button class="btn btn-sm btn-primary" @click="handleUser(user)">Approve</button>`
        ];
    });
})

My datatable component

                        <DataTable :data="usersData" class="display" ref="table">
                            <thead>
                                <tr>
                                    <th>Id Number</th>
                                    <th>Student Name</th>
                                    <th>Email</th>
                                    <th>Program</th>
                                    <th>School Year</th>
                                    <th>Subject Code</th>
                                    <th>Phone</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                        </DataTable>

my table display
enter image description here

Maybe did something wrong by converting the user props to usersData? since its reactive I cant display the users to the datatable so I converted it.

Loop object get valur from input and change object value

I have a multidimensional object with several variable levels.
For each value corresponds an input whose name is in the form “par1-par1_1-c1-type” (for example).
I want to iterate over the object to get the value of the input and update the value of the object.

Part of the object:

par1
    nc = 0
    par1_1
        c1
            type = ""
            date
                m = ""
                y = ""
        c2
            type = ""
            date
                m = ""
                y = ""
    par1_2
        c1 = ""
        c2 = ""
    par1_3
        c1 = ""
        c2 = ""

par2
    nc
    par2_1
        c1 = ""
        c2 = ""
    par2_2
        c1 = ""
        c2 = ""
    par2_3
        c1 = ""
        c2 = ""
    par2_4
        c1
            nc = ""
            list
                type = ""
                mtt = ""
        c2
            nc
            list
                type = ""
                mtt = ""

On submit i do :

var obj;
function submit() {
    datasloop(obj,"");
}

function datasloop(arr, parname) {
    for(let name in arr) {
        let fullname;
        if(parname == undefined || parname == "") fullname = name;
        else fullname = parname+"-"+name;
        if(IsObject(arr[name])) {
            datasloop(arr[name],fullname);
        } else {
            var _i = _form.elements[fullname];
            if(_i) {
                console.log(fullname+" = "+_i.value);
            }
        }
    }
}

In the console I have “par1-par1_1-c1-type = thevalue” and I would like to put this value in the object: obj[‘par1’][‘par1_1’][‘c1’][‘type’ ] = thevalue

In JavaScript, how to stop execution of a Promise which lost a Promise.race?

I did not find a straightforward way to stop execution of a Promise when using AbortController. Let me explain.

To await async function _aget_Cards within a time limit defined by timeout parameter, I created two Promises and raced them as per the code block below.

async function xxx (userCN :string, timeout :number) :Promise<CardDetailsWithCCBal[]|unknown> {
    const controller = new AbortController()
    const raced_promise =  Promise.race ([
        new Promise ((resolve, reject) => {
            _aget_Cards (resolve, reject, userCN, controller)
        }),
        new Promise ( (resolve, reject) => {
            setTimeout ( () => reject('CONTROLLER_TIMEOUT'), timeout)
        })
    ])
    raced_promise.catch((error) => {
        console.log ('Error on raced promise detected')
        if (error === 'CONTROLLER_TIMEOUT') {
            console.log ('Detected error is a CONTROLLER_TIMEOUT ... Sending "abort" signal to controller for _aget_Cards')
            controller.abort()
        }
    })
    return raced_promise
}

You will note that I raised a specific ‘CONTROLLER_TIMEOUT’ error with reject('CONTROLLER_TIMEOUT') if the time limit Promise completes earlier. In the handling of that specific error, I invoke an abort() on the AbortController with controller.abort().

The callbacks resolve, reject and the AbortController instance controller are passed as parameters in the first Promise _aget_Cards (resolve, reject, userCN, controller).

In the controller.signal.addEventListener of the _aget_Cards function, I set doAbort = true, as per code block below.

async function _aget_Cards (resolve :(value :unknown) => void, reject :(reason ?:any) => void, userCN :string, controller :AbortController)  { 
    
    let doAbort = false
    controller.signal.addEventListener ("abort", () => {
        console.log ('Controller received "abort" signal ... aborting ...')
        doAbort = true
    })  

    let start_time = Date.now()
    if (doAbort) return
    const cardDetails_lists :CardDetails[][] = await Promise.all ( [
        aget_CardDetails_List (userCN, true),  // Get Primary cards
        aget_CardDetails_List (userCN, false)  // Get Secondary cards
    ])
    console.log(`List of Primary and Secondary Cards obtained in ${(Date.now()-start_time)/1000}s`)
    
    start_time = Date.now()
    if (doAbort) return
    const cardDetails_list :CardDetails[] = [...cardDetails_lists[0], ...cardDetails_lists[1]]
    cardDetails_list.sort ( (a, b) => {
        let a_sortVal :string = `${a.cardType}${a.cardNo}`
        let b_sortVal :string = `${b.cardType}${b.cardNo}`
        return (a_sortVal < b_sortVal) ? -1 : (a_sortVal > b_sortVal) ? 1 : 0 
    })

    if (doAbort) return
...

You will note that I have been using if (doAbort) return in more than one place to abort execution. I did not find a straightforward way to force the return when an abort was detected.

Rejecting the promise with reject inside controller.signal.addEventListener does not affect the execution of _aget_Cards. Neither does raising an error.

Your help would be much appreciated.

There is a problem occured to me during learning firebase

WARNING in configuration
The ‘mode’ option has not been set, webpack will fallback to ‘production’ for this value.
Set ‘mode’ option to ‘development’ or ‘production’ to enable defaults for each environment.
You can also set it to ‘none’ to disable any default behavior.

i dont know what to expect.

The ‘bind()’ method within a constructor in JavaScript

Is it a good practice to use .bind(this) in the constructor or it’s better to avoid it and istead use arrow function for event handlers to automatically bind ‘this’ ?

Thanks.

Example:

constructor() {
    super();
    this.addHandlerIngredient.bind(this);
    this.addHandlerRemoveIngredient.bind(this);
  }

Instead of above, use:

_addEventListener() {
target.addEventListener('click', () => this.addHandlerIngredient())
target.addEventListener('click', () => this.addHandlerRemoveIngredient())
}

and call this method in the constructor.

how to read input and and calculate in reactjs?

i am new to reactjs. And this is my code for product price list in which i am trying to multiply data on input change, to get the total value. also i need to update the list using axios put method.

import './App.css';
import FormInput from './Components/FormInput';
import axios from 'axios'
import { useEffect, useState } from 'react'

function App() {
  const [list, setList] = useState([])
  const [qty,setQty]=useState(0)
  const crackers = async () => {
    const res = await axios.get("http://localhost:8000/items")
    setList(res.data)
  }


  useEffect(() => {
    crackers()
  }, [])

  const handleChange = (e) => {
    e.preventDefault()
    setQty({
      ...qty,
      [e.target.name]: e.target.qty
    })
    console.log(qty)
  }
  return (
    <div >
      <form>
        <table>
          <thead>
            <tr>
            <th>S.no</th>
              <th>Name</th>
              <th>Unit</th>
              <th>price</th>
              <th>Quantity</th>
              <th>total</th>
            </tr>
          </thead>
          <tbody>
            {list.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.unit}</td>
                <td>{item.price}</td>
                <td>
                  <FormInput type="number" name={item.name} handleChange={handleChange} value={qty}/>
                </td>
                <td>{item.price*qty}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </form>
    </div>
  );
}

export default App;

this is my FormInput element.

const FormInput = ({name,value,handleChange,type}) => {
  return (
    <div>
        <input
            type={type}
            onChange={handleChange}
            value={value[name]}
            name={name}
        />
    </div>
  )
}
export default FormInput

Using this code i could not multiply the product price and quantity.
could you please correct if i made any mistake, since i am new to this.

i tried to multiply the price and qty from input. but i get NaN in all total field.

My html form will no longer submit once I added a redirect

I have an html form which was working properly, however it would redirect to
"{"result":"success","row":1".

I have since changed my google app script and added two html pages to my script, a success.html and fail.html which will show a button that redirects to my website. My issue is that now that I’ve added this, every time I submit I get the failed submition page and nothing is added to my google sheets.

Does my GAS look correct? It is included below.

const sheetName = 'Alltechrepair'
const scriptProp = PropertiesService.getScriptProperties()

function initialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}


function doPost(e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow() + 1

    const newRow = headers.map(function (header) {
      return header === 'Date' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    const template = HtmlService.createTemplateFromFile("redirectSuccess");
    template.url = ScriptApp.getService().getUrl();
    return template.evaluate();
  }

  catch (e) {
    const template = HtmlService.createTemplateFromFile("redirectError");
    template.url = ScriptApp.getService().getUrl();
    return template.evaluate();
  }

  finally {
    lock.releaseLock()
  }
}

I have tried rearranging the code on my GAS, as well as inputing my sheet name.

I can’t find out how to get operators to work the way I want them to

I have a bit of code in an if statement that doesn’t consistently work. I can’t tell why.

This is my code:

CNSinsertG.CNlogo=true
CNskipG=true
a=CNSinsertG.CNlogo==true||CNSinsertG.CNlogo==undefined||CNSinsertG.CNlogo==null && CNskipG==false||CNskipG==undefined||CNskipG==null 

I was hoping for a to equal false because CNskipG==true, but it equals true.

Check an element to see if it contains an image. If so, play a sound. Play a different sound if no image

I have a table of records, some of those records will have an image in an element.

    <td id='record'> </td>

If that element does NOT contain an image I want to play the default sound, but if an image exists in the element play a different sound.

Here is what I have tried, but it doesn’t work, it just plays the default sound.

  //this is the default sound file//
    var audio_element = document.getElementById("alert_audio"); 

    var tab_element = document.getElementById("record");
    for (i = 0; i <= tab_element.childNodes.length - 1; i++) {

            // check if the element is an IMG (image type).
    if (tab_element.childNodes[i].tagName == 'IMG'){

  //this is the other sound file//
    var audio_element = document.getElementById("alert_audio1");
    }
    }   

    if (audio_element.paused){
        audio_element.play();
    }

the result was, it only plays the default sound even though there is an image in some of the other element.

CSS – Animation on filter is extremely slow on Chrome

I want to transition my filter effect through css animation, but this makes my page very laggy. If you click the button continuously, it will be very obvious that the browser is not responding to your clicks in a timely manner.

Here are some key css codes:

.ripple {
  animation: ripple 0.5s ease-out forwards;

  /* Next line will make the page very slow on chrome after button click */
  filter: opacity(0) drop-shadow(0px 0px 10px black) opacity(0);

  @keyframes ripple {
    from {
      scale: 0;
      filter: opacity(0.5) drop-shadow(0px 0px 0px black);
    }
  }
}

When I annotate the first filter, the animation effect becomes very smooth, but it is not the animation effect I want.

And on firefox the page runs fine without any issues.

The full code and preview can be seen in jsfiddle.

I want to select the value of the last element in an array and give that value to an input field based on its ID

I have given some input fields the class gd. These input fields capture date time. I have created a function called getDo() that creates an array that contains all input fields with the class gd. I want this function to return the value of the last element in this array that has a value and give that value to an input field with the id “new9” onblur.

These Input fields have the class gd. The same Input fields that i want to put in my array

function getDO(){

var boxes=[...document.querySelectorAll('.gd')]
box1 = boxes.slice(-1)


document.getElementById('new9').value=box1.value


}

Error Connecting Frontend and Backend on Different Ports with Flask

Description:

I’ve been working on a project that involves a frontend and a backend component, both running on different ports. However, I’m encountering an error when trying to connect them. Specifically, I’m receiving the following error message in my browser’s developer console when I input a message for my chatbot:

POST http://127.0.0.1:5000/predict net::ERR_CONNECTION_REFUSED

I’ve tried to resolve this issue by importing flask_cors, but I’m getting the error:

Import "flask_cors" could not be resolved from source

Here’s a snippet of my frontend (app.js):

class Chatbox {
  constructor() {
    this.args = {
      openButton: document.querySelector(".chatbox__button"),
      sendButton: document.querySelector(".send__button"),
    };

    this.state = false;
    this.messages = [];
  }

  toggleState(chatBox) {
    chatBox.classList.toggle("chatbox--active");
  }

  onSendButton(chatBox) {
    var textField = chatBox.querySelector("input");
    let text1 = textField.value;
    if (text1 === "") {
      return;
    }

    let msg1 = { name: "User", message: text1 };
    this.messages.push(msg1);

    fetch($SCRIPT_ROOT + "predict", {
      method: "POST",
      body: JSON.stringify({ message: text1 }),
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((r) => r.json())
      .then((r) => {
        let msg2 = { name: "Sam", message: r.answer };
        this.messages.push(msg2);
        this.updateChatText(chatBox);
        textField.value = "";
      })
      .catch((error) => {
        console.error("Error:", error);
        this.updateChatText(chatBox);
        textField.value = "";
      });
  }

  updateChatText(chatBox) {
    var html = "";
    this.messages
      .slice()
      .reverse()
      .forEach(function (item, index) {
        if (item.name === "Sam") {
          html +=
            '<div class="messages__item messages__item--visitor">' +
            item.message +
            "</div>";
        } else {
          html +=
            '<div class="messages__item messages__item--operator">' +
            item.message +
            "</div>";
        }
      });

    const chatMessage = chatBox.querySelector(".chatbox__messages");
    chatMessage.innerHTML = html;
  }

  display() {
    const { openButton, sendButton } = this.args;
    const chatBox = document.querySelector(".chatbox__support");

    openButton.addEventListener("click", () => this.toggleState(chatBox));

    sendButton.addEventListener("click", () => this.onSendButton(chatBox));

    const inputNode = chatBox.querySelector("input");
    inputNode.addEventListener("keyup", (event) => {
      if (event.key === "Enter") {
        this.onSendButton(chatBox);
      }
    });
  }
}

const chatbox = new Chatbox();
chatbox.display();

And here’s a snippet of my backend (app.py):

import sys
print("Python Interpreter Path:", sys.executable)

from flask import Flask, render_template, request, jsonify
from chat import get_response
from flask_cors import CORS  # Import CORS from flask_cors

app = Flask(__name__)

# Configure CORS for the entire app
CORS(app)

@app.route("/", methods=['GET'])
def index_get():
    return render_template("base.html")

@app.route("/predict", methods=['POST'])
def predict():
    text = request.get_json().get("message")
    # TO-DO: check if text is valid
    response = get_response(text)
    message = {"answer": response}
    return jsonify(message)

if __name__ == "__main__":
    app.run(debug=True, port=3000)

Can anyone help me identify what’s causing the “ERR_CONNECTION_REFUSED” error and how to properly set up CORS in my Flask app?

Thanks for your assistance!

Why am I getting this error: migration failed with error: Cannot read properties of undefined (reading ‘createTable’)

LOG

npx knex migrate:latest
migration file “20230917031623_createUsers.js” failed
migration failed with error: Cannot read properties of undefined (reading ‘createTable’)
Cannot read properties of undefined (reading ‘createTable’)
TypeError: Cannot read properties of undefined (reading ‘createTable’)
at exports.up (C:PROJECTSENVOLVIDOS_apisrcdatabaseknexmigrations20230917031623_createUsers.js:1:35)
at C:PROJECTSENVOLVIDOS_apinode_modulesknexlibmigrationsmigrateMigrator.js:519:40
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Migrator._runBatch (C:PROJECTSENVOLVIDOS_apinode_modulesknexlibmigrationsmigrateMigrator.js:381:19)

knexfile.js

`const path = require("path");

module.exports = {
    client: 'mysql2',
    connection: {
        database : 'shopbarber',
        user: 'root',
        password: ''
    },
    pool: {
        min: 2,
        max: 10
    },
    migrations: {
        directory: path.resolve(__dirname, "src", "database", "knex", "migrations")
    }
}`

config

`const config = require("../../../knexfile");
const knex = require("knex")(config);

knex.raw("SELECT VERSION()").then(() => {
    console.log('Connection to db succesful')
})

module.exports = knex;`

Migration File

``exports.up = knex => knex.schemas.createTable("users", table => {
    table.increments("id");
    table.string("name", 60).notNullable();
    table.string("telephone", 11).notNullable();
    table.string("email", 90).notNullable().unique();
    table.text("password").notNullable()
    table.string("avatar", 120);
    table.timestamp("created_at").defaultTo(knex.fn.now());
    table.timestamp("updated_at").defaultTo(knex.fn.now());
})`

exports.down = knex => knex.schemas.dropTable(“users”);`

I recreated the migrations, the files, changed functions, I don’t know how to resolve it.
The connection is established, I just can’t perform the migrations.

Help me?

How to add append < after every 10 Jquery or Javascript

I make a unlimited table generated through php file_put_contents
i want to add </tr><tr> after every 10 </td> with help of Jquery or Javascript

Here is the example to table

<TABLE BORDER="1" WIDTH="100%" CLASS="Numbers">
<TR>
    <TD>img1</TD>
    <TD>img2</TD>
    <TD>img3</TD>
    <TD>img4</TD>
    <TD>img5</TD>
    <TD>img6</TD>
    <TD>img7</TD>
    <TD>img8</TD>
    <TD>img9</TD>
    <TD>img10</TD>
                           <==== i want here </TR><TR> , which will automatically add after EVERY 10 </td>
    <TD>img11</TD>
    <TD>img12</TD>
    <TD>img13</TD>
    <TD>img14</TD>
    <TD>img5</TD>
    <TD>img16</TD>
    <TD>img17</TD>
    <TD>img18</TD>
    <TD>img19</TD>
    <TD>img20</TD>
                                <=== i want it auto add </TR><TR> here after every 10 </td>
    <TD>img21</TD>
    <TD>img22</TD>
    <TD>img23</TD>
    <TD>img24</TD>
    <TD>img25</TD>
    <TD>img26</TD>

table… continue