How to control microphone output from JavaScript?

I am building an app, which needs to record a microphone. I want users to control microphone output from the app, mute/unmute it.

Is it possible ? If yes, how can I achieve that ?

React version of the project

   "react": "^17.0.2",

Code where I get an microphono input

const handleRecord = async () => {
    setIsAudioLoading(true);
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/wav" });
    let orderNumber = 0;
    let chunks = [];

    mediaRecorder.ondataavailable = function (e) {
      chunks.push(e.data);
    };
    mediaRecorder.onstop = function () {
      const blob = new Blob(chunks, { type: "audio/wav" });
      streamChunk(blob, orderNumber, "mic");
      chunks = [];
    };

    mediaRecorder.start();

    setStopMic(() => () => {
      setIsMicPaused(true);
      setCurrentAudioTime(lastChunkSecondRef.current - 1.5);
      isMicPausedRef.current = true;
      mediaRecorder.stop();
    });
    setStartMic(() => () => {
      setIsMicPaused(false);
      isMicPausedRef.current = false;
      mediaRecorder.start();
    });

    setInterval(function () {
      if (!isMicPausedRef.current) {
        orderNumber++;
        mediaRecorder.stop();
        mediaRecorder.start();
      }
    }, MIC_INTERVAL);
  };

How can I use page.type() inside The page.$eval() in puppeteer?

    const browser = await puppeteerExtra.launch({
      "dumpio": true, // to log
      "headless": false, // to open browser in background process
      "devtools": false, // do disable dev-tools
      "ignoreHTTPSErrors": true, // to ignore webpage https error
      "args": [
        "--disable-setuid-sandbox",
        '--no-sandbox',
        '--disable-features=IsolateOrigins,site-per-process',
      ],
    });
    let page = await browser.newPage();
    await page.setUserAgent(userAgent.toString());
    await page.goto(url, { waitUntil: 'networkidle2' });
    await page.waitForTimeout(1000);
    await page.setCacheEnabled(false);
    await page.evaluate(() => {
      let modelSONATA = document.querySelector('input[id="model-SONATA"]');
      modelSONATA.click();
    });

i Want to Use page.evaluate() inside page.type so Please Help Me What is Way to Use Inside page.type()

clearInterval when you choose GOOD or WRONG answer JavaScript

Please help, I don’t know how to clear Interval when i choose good or wrong answer. Without choosing answer Interval clear when time goes to 0. When you choose a good option or a bad one, it moves to the next artboard, but the old interval still remains in the computer’s memory. I am not a coding specialist, which can be seen from my coding method… Game made in Adobe Animate.

createjs.Touch.enable(stage);
stage.enableMouseOver();

this.stop();
console.log("enter game")

let selected = [];
let finalMove = null;
let numberOfSec = 20;
//let level = 1;
//let score = 0;
this.timer.text = numberOfSec;
this.score.text = counterWin;

this.timer.visible = true;
this.timeplace.visible = false;

const timerInterval = setInterval(() => {
        numberOfSec--
    this.timer.text = numberOfSec;
    if(numberOfSec==5){
        this.timer.visible = true;
        this.timeplace.visible = true;
        createjs.Sound.play('clock');
        console.log("clock 5 to 0")
    }
    if(numberOfSec==0){
        this.gotoAndStop('next1')
        clearInterval(numberOfSec);
        console.log(numberOfSec);
        console.log("enter to page next1")
        createjs.Sound.stop();
    }
},1000)


const elements1 = [
this.mc1,
this.mc2,
this.mc3,
this.mc4,
this.mc5,
]


const places = [
    this.card1, 
    this.card2, 
    this.card3, 
    this.card4,
    this.card5,
];
    

shuffle(places);

elements1.forEach((element, index) => {
    element.x = places[index].x;
    element.y = places[index].y;
})


function shuffle(a) {
    let j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}


//var clear = clearInterval(numberOfSec);
var root = this;

elements1.forEach(element => {
    element.addEventListener('click', (event) =>{
    
        if (event.currentTarget.name === 'mc5'){
            console.log("GOOD")
            counterWin+=2;
            //clearInterval(numberOfSec);
            //root.clear;
            console.log(clear);
            this.score.text = counterWin;
            //createjs.Sound.stop();
            createjs.Sound.play('good');
            this.play();
            createjs.Sound.stop();
            console.log(counterWin);
        }else{
            console.log("WRONG")
            createjs.Sound.play('wrong');
            //clearInterval(numberOfSec);
            //root.clear;
            createjs.Sound.stop();
            this.play();
        }
        
        
    });
    
});

How can I replace a call argument of a function with Sinon?

I am using sinon to make my tests, and I faced a problem that I can’t find a proper solution

lets say, for simplicity, that I want, when I call console.log(),that the proper console.log receives the argument that I want in my test.

I have tryied:

Sinon.replace( console, 'log', () => console.log('mytestparam'))

Sinon.stub( console, 'log').callsFake( console.log('mytestparam'))

But it creates some kind of circular dependency that crashes

I cant simply make a full stub of the function, because it contains code that I want to run, I only want to replace the argument used for the call.

I have researched the sinon docs but I can’t find any function that allows to call the original function changing the args

Any idea?

How to get posts from the next pagination page using ajax?

There is a category on wordpress where posts and standard pagination 1, 2, 3, etc. are displayed. I made that when I clicked on the pagination, an Ajax request was triggered and from the next page of the pagination the posts were inserted into the page, but for some reason all the posts are displayed. Where am I wrong?

Post output code with pagination

<?php
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
    'cat' => $current_cat_id,
    'posts_per_page' => 1,
    'paged'          => $paged,
);

$query = new WP_Query( $args );
// Цикл
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
    $query->the_post();

?>

<a class="post-list-item mb-32" href="<?php the_permalink(); ?>">
    <div class="post">
        <div class="post-header mb-32">
            <div class="post-date">Jan 4, 2022</div>
            <h3 class="post-title"><?php the_title() ?></h3>
            <div class="post-short-info">
                <?php the_field('kratkoe_opisanie'); ?></div>
        </div>
        <div class="post-thumbnail">
            <div class="image-inner"><img class="image"
                    src="<?php echo get_the_post_thumbnail_url(); ?>">
            </div>
        </div><span class="read-more">Read more</span>
    </div>
</a>



<?php
}
} else {
    // Постов не найдено
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();

$big = 999999999; // уникальное число

$pagination =  paginate_links( array(
    'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'current' => max( 1, get_query_var('paged') ),
    'total'   => $query->max_num_pages
) );


?>

</div>

<?php
echo "<div class='pagination'>" . $pagination . "</div>";

?>

Ajax javascript

<script type="text/javascript">

        $('.pagination a').click(function(e) {

            e.preventDefault(); // don't trigger page reload

            if($(this).hasClass('active')) {
                return; // don't do anything if click on current page
            }

            $.post(
                '<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
                {
                    action: 'ajax_pagination',
                    page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
                    posts_per_page: <?php echo get_option('posts_per_page'); ?>
                },
                function(data) {
                    $('.posts-list').html(data); // replace posts with new one
                    console.log(data);
                }
            );
        });
</script>

Functions.php

function my_ajax_navigation() {
    $requested_page = intval($_POST['page']);
    $posts_per_page = intval($_POST['posts_per_page']) - 1;
    $posts = get_posts(array(
        'cat' => 6,
        'posts_per_page' => $posts_per_page,
        'offset' => $page * $posts_per_page
    ));
    foreach ($posts as $post) {
        setup_postdata( $post );
        echo $post->ID;
    }
    exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );

Fill diagonals of array with same values in JS

I have an array of n x n elements, and I want to fill its diagonals with the same values as follows:

ex. n = 3:

0 1 2
3 0 1
4 3 0

arr = [0, 1, 2, 3, 0, 1, 4, 3, 0]

ex. n = 4;

0 1 2 3
4 0 1 2
5 4 0 1
6 5 4 0

arr = [0, 1, 2, 3, 4, 0, 1, 2, 5, 4, 0, 1, 6, 5, 4, 0]

I was able to fill upper half of the array using the following code, but got stuck with the rest:

var n = 3;
var values = [0, 1, 2, 3, 4]

var a = [];
for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
        a[j * n + i] = values[i - j];
    }
}

/* Result
0 1 2
  0 1
    0

arr = [0, 1, 2, undefined, 0, 1, undefined, undefined, 0] */

Length of values array is 2 * n - 1, which is the count of diagonals of the array.

Any ideas how to fill the whole array?

Angular – AWS Amplify amplify-authenticator crashes the form when the ‘Code’ I send is wrong

I have an amplify-authenticator form which I use to reset the password. If I enter a wrong code, I get a response from the API which says

CodeMismatchException: Invalid verification code provided, please try again.

which is correct, but the entire form then freezes and I also get this message in the console of the browser:

Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading ‘authAttributes’)
TypeError: Cannot read properties of undefined (reading ‘authAttributes’)
at actorDoneData (index.js:2:34774)

which points to webpack:///node_modules/@aws-amplify/ui/dist/esm/index.js

This is the code I have:

HTML

<amplify-authenticator [services]="services" initialState="resetPassword"></amplify-authenticator>

TS

    this.services = {
      async handleForgotPasswordSubmit(formData): Promise<void> {
        const { username, code, password } = formData;

        return Auth.forgotPasswordSubmit(username, code, password)
          .then(res => {
            //  Do something on success
          })
          .catch(err => {
            // The ERROR is here
            console.log(err);
          });
      }
    };

Please advise what can I do to avoid the form freeze problem. Thanks!

MUI-Datatable: TableHead inside Expandable Row keeps on repeating for every row of the table and table does not center

How do I solve this? Table headings just keep on repeating for every row in the table as seen in the picture below. Also, the table is always at the far end of the right side. How can I make this at the center as well?

enter image description here

Codesandbox: https://codesandbox.io/s/xenodochial-fog-s984v0?file=/src/App.js

codes:

 const options = {
    filter: true,
    selectableRows: "none",
    responsive: "simple",
    expandableRows: true,
    renderExpandableRow: (rowData, rowMeta) => {
      console.log(rowData, "rowData");
      return Object.entries(rowData[3]).map(([key, value]) => {
        return (
          <TableContainer>
            <Table>
              <TableHead>
                <TableCell align="right">Name</TableCell>
                <TableCell align="right">Color</TableCell>
              </TableHead>
              <TableBody>
                <TableRow key={key}>
                  <TableCell component="th" scope="row">
                    {value.name}
                  </TableCell>

                  <TableCell align="right">{value.color}</TableCell>

                  {/* Product: {value.name} + {value.size} +{" "}
                  {value.color + value.quantity} */}
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
        );
      });
    }
  };

How to fix JsonWebTokenError in node.js using express and reactjs?

I am trying to show the page only if the Jsonwebtoken is verified and the user is logged on to the website, else show him the sign-in page.

However, I can see the token is generated in MongoDB, and also when I console log I can see that it is all good. But the issue is when I try to verify it using an already generated jwt token i.e.

req.cookies.signinToken

it shows an error.

Please the detail code below:

On app.js

const dotenv = require("dotenv");
const mongoose = require("mongoose");
const express = require("express");
const app = express();

const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

dotenv.config({ path: "./config.env" });
require("./db/connection");

app.use(express.json());
app.use(cookieParser());

app.use(require("./router/route"));

const PORT = process.env.PORT;

app.listen(5000, () => {
    console.log(`server running on ${PORT}`);
});

On route.js

const express = require("express");
const bcrypt = require("bcrypt");
const router = express.Router();
const jwt = require("jsonwebtoken");

require("../db/connection");
const User = require("../model/newUserSchema");
const auth = require("../middleware/auth");

// router.get("/", (req, res) => {
//     res.send("hello am backend sever");
// });

//Signup or  Register Part
router.post("/signup", async (req, res) => {
    const { username, email, cpassword, retypePassword } = req.body;

    if (!username || !email || !cpassword || !retypePassword) {
        return res.status(422).json({ error: "please enter valid details" });
    }

    try {
        const UserExist = await User.findOne({ email: email });

        if (UserExist) {
            return res.status(422).json({ error: "email already exist" });
        } else if (cpassword !== retypePassword) {
            return res.status(422).json({ error: "password incorrect" });
        } else {
            const user = new User({
                username,
                email,
                cpassword,
                retypePassword,
            });

            const userResgister = await user.save();

            if (userResgister) {
                return res.status(201).json({ message: "signup successfully" });
            }
        }
    } catch (error) {
        console.log(error);
    }
});

//Login Part
router.post("/signin", async (req, res) => {
    try {
        const { email, cpassword } = req.body;

        if (!email || !cpassword) {
            return res.status(400).json({ error: " please enter valid credentials" });
        }

        const userLogin = await User.findOne({ email: email });

        const token = userLogin.generateAuthToken();

        res.cookie("signinToken", token, {
            expires: new Date(Date.now() + 25892000000),
            httpOnly: true,
        });

        if (userLogin) {
            const isMatch = await bcrypt.compare(cpassword, userLogin.cpassword);

            if (isMatch) {
                return res.status(200).json({ message: "sigin in scuccessfully" });
            } else {
                return res.status(400).json({ error: " Invalid credentials" });
            }
        } else {
            return res.status(400).json({ error: "  Invalid credentials " });
        }
    } catch (error) {
        console.log(error);
    }
});

//watchlistpage
router.get("/watchlist", auth, (req, res) => {
    console.log("  this is jwt token test  " + req.cookies.signinToken);
    res.send(req.rootuser);
    console.log(req.rootuser);
});

module.exports = router;

On newUserSchema.js:

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

const newUserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
    },
    cpassword: {
        type: String,
        required: true,
    },
    retypePassword: {
        type: String,
        required: true,
    },
    tokens: [
        {
            token: {
                type: String,
                required: true,
            },
        },
    ],
});

newUserSchema.pre("save", async function (next) {
    if (this.isModified("cpassword")) {
        this.cpassword = await bcrypt.hash(this.cpassword, 12);
        this.retypePassword = await bcrypt.hash(this.retypePassword, 12);
    }
    next();
});

newUserSchema.methods.generateAuthToken = async function () {
    try {
        let token = jwt.sign({ _id: this._id }, process.env.SECRETKEY);
        this.tokens = this.tokens.concat({ token: token });
        await this.save();
        return token;
    } catch (error) {
        console.log(error);
    }
};

const User = mongoose.model("newUser", newUserSchema);

module.exports = User;

On auth.js (this is also my middleware)

    const jwt = require("jsonwebtoken");
const User = require("../model/newUserSchema");

const Auth = async (req, res, next) => {
    try {
        console.log(JSON.stringify(req.cookies.signinToken) + "  this is jwt token test");
        const token = req.cookies.signinToken;
        const verifytoken = jwt.verify(token, process.env.SECRETKEY);

        const rootuser = await User.findOne({ _id: verifytoken._id, "tokens.token": token });

        if (!rootuser) {
            throw new Error("user not found");
        }

        req.token = token;
        req.rootuser = rootuser;
        req.UserID = rootuser._id;

        next();
    } catch (error) {
        res.status(401).send("Unauthorized access");
        console.log(error);
    }
};

module.exports = Auth;

The API call result in postman

postmanimg

The terminal error :

terminalimg

Could you please help to correct the error also please let me know why is this error coming?

Thanks a million in advance for any tips or suggestions.

JS/React Drawing Application with TouchMoveEvent

I am trying to build a react app and I need one component for simple handwriting and drawing on mobile/touch devices.
The problem im am facing is that the TouchMoveEvent is not fired upon small movements. Therefore it gets pretty hard if someone has a small handwriting. Sometimes some parts of letters or numbers are missing because the touchmoveevent was not fired and subsequently no line has been drawed.
Has anyone an idea how to lower the treshhold to fire the touchmoveevent or has someone a different approach to this? The goal is just a very simple mobile drawing app but the touchmoveevent is not sufficient for very detailed and small drawings as it is not fired upon small movements.

This is my code so far:

import React from "react";
const Immutable = require('immutable');
class DrawArea extends React.Component {
    constructor(sized) {
        super();

        this.state = {
            lines: new Immutable.List(),
            isDrawing: false
        };
        console.log(sized)
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.handleMouseMove = this.handleMouseMove.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);
        this.handleTouchStart = this.handleTouchStart.bind(this);
        this.handleTouchMove = this.handleTouchMove.bind(this);
        this.handleTouchEnd = this.handleTouchEnd.bind(this);

    }

    componentDidMount() {
        document.addEventListener("mouseup", this.handleMouseUp);
        document.addEventListener("touchend", this.handleTouchEnd);

    }

    componentWillUnmount() {
        document.removeEventListener("mouseup", this.handleMouseUp);
        document.removeEventListener("touchend", this.handleTouchEnd);

    }

    handleMouseDown(mouseEvent) {
        if (mouseEvent.button != 0) {
            return;
        }

        const point = this.relativeCoordinatesForEvent(mouseEvent);

        this.setState(prevState => ({
            lines: prevState.lines.push(new Immutable.List([point])),
            isDrawing: true
        }));
    }

    handleMouseMove(mouseEvent) {
        if (!this.state.isDrawing) {
            return;
        }
        const point = this.relativeCoordinatesForEvent(mouseEvent);

        this.setState(prevState =>  ({
            lines: prevState.lines.updateIn([prevState.lines.size - 1], line => line.push(point))
        }));
    }

    handleMouseUp() {

        this.setState({  isDrawing: false });
    }

    handleTouchStart(e) {
        console.log("s")

        let touch = e.touches[0];
        const point = this.relativeCoordinatesForEvent(touch);
        this.setState(prevState => ({
            lines: prevState.lines.push(new Immutable.List([point])),
            isDrawing: true
        }));
    }
    handleTouchMove(e) {
        console.log("m")

        if (!this.state.isDrawing) {
            return;
        }
        let touch = e.touches[0];
        const point = this.relativeCoordinatesForEvent(touch)
        this.setState(prevState =>  ({
            lines: prevState.lines.updateIn([prevState.lines.size - 1], line => line.push(point))
        }));

    }
    handleTouchEnd() {
        console.log("e")
        this.setState({  isDrawing: false });

    }

    relativeCoordinatesForEvent(mouseEvent) {
        const boundingRect = this.refs.drawArea.getBoundingClientRect();
        return new Immutable.Map({
            x: mouseEvent.clientX - boundingRect.left,
            y: mouseEvent.clientY - boundingRect.top,
        });
    }

    relativeCoordinatesForTouchEvent(mouseEvent) {
        const boundingRect = this.refs.drawArea.getBoundingClientRect();
        return new Immutable.Map({
            x: mouseEvent.clientX - boundingRect.left,
            y: mouseEvent.clientY - boundingRect.top,
        });
    }

    render() {
        //console.log(this.state.lines)
        //this.state.lines.map(s => console.log(s))
        return (
            <div
                className="drawArea"
                ref="drawArea"
                onMouseDown={this.handleMouseDown}
                onMouseMove={this.handleMouseMove}
                onTouchStart={this.handleTouchStart}
                onTouchMove={this.handleTouchMove}
                onTouch
            >
                <Drawing sized={this.props.sized} lines={this.state.lines} />
            </div>
        );
    }
}

function Drawing({ lines, sized }) {
    return (
        <svg className="drawing">
            {lines.map((line, index) => (
                <DrawingLine key={index} sized={sized} line={line} />
            ))}
        </svg>
    );
}

function DrawingLine({ line, sized }) {
    let multi = sized ? 1.0 : 0.5;
    const pathData = "M " +
        line
            .map(p => {
                return `${p.get('x')*multi} ${p.get('y')*multi}`;
            })
            .join(" L ");

    return <path className="path" d={pathData} />;
}

export default DrawArea;
´´´



    

How can I drag an image tag to overlaying on a canvas tag?

How can I arrange ‘objy’ next to ‘objx’ and able to drag ‘objz’ to overlaying on ‘objy’ or ‘objx’? Thank you so much for any help/suggestions. How can I arrange ‘objy’ next to ‘objx’ and able to drag ‘objz’ to overlaying on ‘objy’ or ‘objx’? Thank you so much for any help/suggestions. How can I arrange ‘objy’ next to ‘objx’ and able to drag ‘objz’ to overlaying on ‘objy’ or ‘objx’? Thank you so much for any help/suggestions.

<html>
<body>
    <canvas id="objx" ondragover="dropZone(event)" ondrop="dropImg(event)"></canvas>
    <canvas id="objy" ondragover="dropZone(event)" ondrop="dropImg(event)"></canvas>
    <img id="objz" src="object.png" draggable="true" ondragstart="dragImg(event)"> </img>

    <script>
        let obj_x = document.getElementById("objx")
        let obj_y = document.getElementById("objy")
        let obj_z = document.getElementById("objz")
        var x = obj_x.getContext('2d');
        var y = obj_x.getContext('2d');
        var z = obj_x.getContext('2d');

        if (obj_x.getContext && obj_y.getContext) {    
            obj_x.width = 200;
            obj_x.height = 200;           
            x.moveTo(0, 0);
            x.lineTo(0, 200);
            x.lineTo(200, 200);
            x.lineTo(200, 0);
            x.lineTo(0, 0);
            x.lineWidth = 1;
            x.strokeStyle = "black";
            x.stroke();  

            obj_y.width = 200;
            obj_y.height = 200;    
            y.moveTo(200, 0);
            y.lineTo(200, 200);
            y.lineTo(400, 200);
            y.lineTo(400, 0);
            y.lineTo(200, 0);
            y.lineWidth = 1;
            y.strokeStyle = "red";
            y.stroke();   
        } else {   
            document.write("Canvas Unsupported"); 
        }   

        function dragImg(e) {
        e.dataTransfer.setData('imgId', e.target.id);
        }

        function dropZone(e) {
            e.preventDefault();
        }

        function dropImg(e) {
            var mId=e.dataTransfer.getData('imgId');
            e.target.appendChild(document.getElementById(mId));
            e.preventDefault();
        }
    </script>
</body>

Manege more request ajax

Hy guys, I have a problem with async call in ajax jquery. This is my code:

$(document).on('click', '#search', function () {
    
        $.get(context + '/AjaxGetIvaNoleggio', function (data) {
            iva = (data / 100) + 1;
        });
        cont = 0;
        var dataDal = $('#dataDal').val();
        var dataAl = $('#dataAl').val();
        $.get(context + '/AjaxRendimento?tipoUtente=-1&dataDal=' + dataDal + '&dataAl=' + dataAl + "&all=" + all, getAll).done(
                $.get(context + '/AjaxRendimento?tipoUtente=0&dataDal=' + dataDal + '&dataAl=' + dataAl + "&all=" + all, getAll).done(
                $.get(context + '/AjaxRendimento?tipoUtente=1&dataDal=' + dataDal + '&dataAl=' + dataAl + "&all=" + all, getAll).done(
                $.get(context + '/AjaxRendimento?tipoUtente=3&dataDal=' + dataDal + '&dataAl=' + dataAl + "&all=" + all, getAll))));

});
const  getAll = function (data) {
var numNoleggio = 0;
var imponibile = 0;
var iva = 0;
var tot = 0;
var table =  '<table class="table table-bordered table-striped tableData ">n'
        + '<tr>';
if (cont === 0) {
    table += '<th colspan="4" class="text-center">ALL</th>';
} else if (cont === 1) {
    table += '<th colspan="4" class="text-center">USER</th>';
} else if (cont === 2) {
    table += '<th colspan="4" class="text-center">AGENCY</th>';
} else if (cont === 3) {
    table += '<th colspan="4" class="text-center">ADMIN</th>';
}

//here I iterate the data 
table += //here create the table with datas in data;
$('.rendiconto').append(table);
cont++;
};

I tried with done, after and then but the results are not in order, how can I do it?
I want the first call in cont ===0, the second call in cont ===1, the third call in cont ===2 and the fourth call in cont===3.

django and javascript question show and hide edit form from list of selected queries

I have the following in my index

 <div id="posts">
{% for post in posts %}
<div class="card">
    <div class="card-body">
        <h5 class="card-title"><a href="{% url 'profile' post.user.username %}">{{post.user.username}}</a> wrote:</h5>
        {%if post.user_id == user.id %}
        <div class="cardn">
            <a href="#" onclick="editpost()">Edit</a>

            <div class="card-body" id="card-body" style="display: none">
                <form action="editpost/{{post.id}} " method="post">
                    {% csrf_token %}
        
                    <div class="form-group">
                        <label for="post_text" class="h4">Edit Post</label><br>
        <textarea name="post_text">{{post.text}}</textarea>            </div>
                    <button type="submit" class="btn btn-primary btn-sm">Edit</button>
                </form>
            </div>
        </div>
        {%endif%}
        <p class="card-text" id="post_text_{{post.id}}"> {{ post.text }}</p>
   
        <p class="card-text"><small class="text-muted">on: {{post.post_date}}</small></p>
        <p class="card-text">
            <div data-id="{{post.id}}"
                class="card-link {% if post.current_like > 0 %} fas {%else%} far {% endif %} fa-heart">&nbsp<small
                    class="text-muted">{{post.like_set.count}}</small>
                    </div>
        </p>
    </div>
</div>
{% empty %}
<h2>No posts</h2>
{% endfor %}

what i would like to reach is to show only the edit form for the clicked edit button using javascript

here is my view

 def editpost(request, id):
post = Post.objects.get(
            id=id)
if request.method == "POST":
        text = request.POST.get("post_text")
        Post.objects.filter(
            id=id, user_id=request.session['_auth_user_id']).update(text=text)
        return HttpResponseRedirect(reverse("index"))
else:
    return render(request, "network/editpost.html",  {
    'post': post
    })

my JS thats not working
document.addEventListener(“click”, editPost);

function editPost(event){ // Listener sees triggering event
  const clickedThing = event.target; // Event has useful properties
  const userCard = clickedThing.closest(".cardn");
  if(userCard){ // Makes sure button has a `card` ancestor before proceeding

    // Now, with the correct card identified, we can collect values from it
    document.querySelector(`#card-body`).style.display = "block";
      // ...etc, as described above
  }
}

thanks in advance