catch non window event with alpinejs

with alpinejs I can easily catch custom window events.

markup

<div x-data="map_data" @mapupdate.window="updateTodos">

...

js

const sendEvent = (name, payload) => {
    var evt = new CustomEvent(name, {detail: payload});
    window.dispatchEvent(evt);
}
sendEvent("mapupdate", {"okay":"roger"})

Let’s say I don’t want to create a window event but catch a “local” event coming from leaflet. This is how I can normally catch the event:

map.on('zoomend', function() {
    console.log("end");
});

Is it possible to instead dispatching a custom event again to directly catch the leaflet event with alpinejs?

<div x-data="map_data" @zoomend.map="updateTodos">

Displaying a CSV file using react frontend and flask backend

I’m trying to read a csv file using flask and then display it through react (The display part should be compulsorily done through react). I’m stuck at the return part of js file.

This is the flask(.py)code:

from flask import Flask,render_template,request
import os
import pandas as pd

app=Flask(__name__)
app.secret_key="123"

app.config["UPLOAD_FOLDER1"]="static/csv"

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

@app.route("/display",methods=["GET","POST"])
def display():
    upload_file = request.files['upload_csv']
    if upload_file.filename != '':
            file_path = os.path.join(app.config["UPLOAD_FOLDER1"], upload_file.filename)
            upload_file.save(file_path)
            data=pd.read_csv(file_path,sep=",")
            return render_template("CsvContent.html",data=data.to_html(index=False))

if __name__=='__main__':
    app.run(debug=True)

And here are the two HTMLs used in the .py file above:
UploadCsv.html

<html>
    <head>
        <title>Upload CSV File</title>
    </head>
    <body>
        <div class="col-md-offset-3 col-md-5" style="margin-top:70px">
            <form method="POST" action="http://127.0.0.1:5000/display" enctype="multipart/form-data">
                <h3 class="page-header text-primary">Upload CSV File</h3>
                <div class="form-group">
                    <label>Browse CSV File</label>
                    <input type="file" class="form-control" name="upload_csv">
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-success btn-block">Upload CSV</button>
                </div>
            </form>
        </div>
    </body>
</html>

CsvContent.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSV File</title>
</head>
<body>
    <h2>Here's your uploaded CSV file :</h2>
    {{data|safe}}
</body>
</html>

This successfully reads and displays the CSV file completely through Flask. Now, here’s the catch, I have to integrate react too. And this is where I’m messing up. Here’s my React code, if it helps.

 const[csvupload,setCsvUpload] = useState()

useEffect(()=> {

  fetch('http://127.0.0.0:5000/display',{

    'method':'POST',

    headers: {

      'Content-Type' : 'application/json'

    }

  })

  .then(resp => resp.json())

  .then(resp => setCsvUpload(resp))

  .catch(error => console.log(error))

},[])

  return (

   

    <Fragment>

      <div className="upload" >

          Upload Your CSV File
       
            <Row md={12}>

                <Col md={6} className="body-upload">

                <input type="file" accept=".csv" onChange={handleFileUpload} multiple />  

                <button onClick={modalOpen}> UPLOAD </button>

                </Col>
            </Row>

            {csvupload.map(csv =>{

              return( 
(**What should be here?**)

                <div>


                </div>

              )

            })}

      </div>

    </Fragment>

  );

};

export default UploadFile;

How can I return the CSV file through react? I am using fetch here, is it even the right method? What should I put inside the return method so that when I upload the csv, it should read the file, store in “static/csv” (as given in the flask code) and display the file below before clicking Upload. I know its a long question, but please help. Any kinda help would be appreciated and I’m willing to provide information required.

Vue Ionic 6 fails to run on Vite SSR dev server

I am integrating Vite SSR to existing vue project. I copied vite configuration from SSR playground project and bumped ionic version to 6 because of dynamic loading issue from stencil.
After upgrading, it isn’t compiling, showing this error.

12:03:15 AM [vite] Error when evaluating SSR module /src/components/ImportType.vue:
/data/Work/ssr-vue/node_modules/@ionic/core/components/ion-accordion.js:4
import { proxyCustomElement, HTMLElement, h, Host } from '@stencil/core/internal/client';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Here is my vite.config.js file

const vuePlugin = require('@vitejs/plugin-vue')
const vueJsx = require('@vitejs/plugin-vue-jsx')
const virtualFile = '@virtual-file'
const virtualId = '' + virtualFile
const nestedVirtualFile = '@nested-virtual-file'
const nestedVirtualId = '' + nestedVirtualFile
/**
 * @type {import('vite').UserConfig}
 */
module.exports = {
  plugins: [
    vuePlugin(),
    vueJsx(),
    {
      name: 'virtual',
      resolveId(id) {
        if (id === '@foo') {
          return id
        }
      },
      load(id) {
        if (id === '@foo') {
          return `export default { msg: 'hi' }`
        }
      }
    },
    {
      name: 'virtual-module',
      resolveId(id) {
        if (id === virtualFile) {
          return virtualId
        } else if (id === nestedVirtualFile) {
          return nestedVirtualId
        }
      },
      load(id) {
        if (id === virtualId) {
          return `export { msg } from "@nested-virtual-file";`
        } else if (id === nestedVirtualId) {
          return `export const msg = "[success] from conventional virtual file"`
        }
      }
    }
  ],
  ssr: {
    external: ["npm: @ionic/vue"]
  },
  build: {
    minify: false
  }
}

Please help me.

How to perform multi column sorting in datatable server-side

I want to perform multi-column sorting on the data table server-side. I have done that in client-side processing, but I am a little confused with server-side!

I have realized that dataTable does initial sorting with the first column of the table. But I want to sort with the third and first columns. I need to pass two fields in the payload to the backend API.

My Code –

  $(document).ready(function () {
      $('#dataTable').DataTable({
       "columnDefs": columnDefinition,
       "processing": true,
       "serverSide": true,
       "ajax":{
          "url": "https://backend.omni.myself.health/test/getAllContactsByFilter",
          "type": "POST",
          "error":function (err){
           console.log(err);
           toastr["error"]("We could not filter your data.", "Error!");
           $('#filterButton').attr('disabled',false).html('Filter');
           },
           "contentType": "application/json; charset=utf-8",
           "beforeSend": function(xhr){
            xhr.setRequestHeader("Authorization",
            "Bearer Token");
          },
            "data":  function ( d ) {
             var payloadData = {};
             payloadData.size = d.length;

             payloadData.field = "";
             if(d.order[0].column == 0) {
             payloadData.field = "firstColumnString";
             }else if(d.order[0].column == 1) {
              payloadData.field = "secondColumnString";
             }else if(d.order[0].column == 2) {
              payloadData.field = "thirdColumnString";
             }else if(d.order[0].column == 3) {
              payloadData.field = "fourthColumnString";
             }

             payloadData.order = "";
             if(d.order[0].dir == "asc") {
               payloadData.order = "asc";
             }else if(d.order[0].dir == "desc") {
               payloadData.order = "desc";
             }
             return JSON.stringify(payloadData);
            },
             dataFilter: function(data){
             var json = jQuery.parseJSON( data );
             json.recordsTotal = json.totalElements;
             json.recordsFiltered = json.totalElements;
             json.data = json.content;
             return JSON.stringify( json ); // return JSON string
        }
      }
     });
  });

I need to perform some processing for sorting bcz api accept string field.
How can I disable initial searching of datatable and send two fields like field1 and field2 to the backend?
Please help

onpaste event to block certain characters only

So I’m working on blocking special characters and alphabets in a textarea and allowing on certain characters to be inputted(code below).To be precise I allow alphabet “a” and a semicolon and numbers[0-9] .which works fine
But when I try to handle this for onpaste it doesn’t work when I paste allowed characters it doesn’t allow it, it blocks everything

ex: if I try pasting a1234;a4567 its blocked but while typing it works ,any idea what I’m doing wrong ,guidance ill be helpful

 <textarea id="about"  onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57 || event.charCode == 97 || event.charCode == 59" onpaste="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57 || event.charCode == 97 || event.charCode == 59"></textarea>

i have data in the form of object of object in javascript

Hi everyone I have object of object and I just want to combine data inside inner object in the form of array is there any way to that

input data

  let data = {
      
      ok123b:{
        name:'shanu'
    },
       of123b:{
        name:'rahul'
    },
       og1453jdfk:{
        name:'ak'
    },
       ok1kjjdde23b:{
        name:'man'
    }
      
      
    }
    
    let arrayOfData  =[data.ok123b.name,data.of123b.name,data.og1453jdfk.name,data.ok1kjjdde23b.name]
    console.log(arrayOfData);
    
    //this is hard coded i want dynamic code to convert data in the form of array

expected output

output  = ['shanu','rahul','ak','man'];

Using the onclick function for a button and the button content (words) show up but the button is not clickable. Any advice?

Just doing some practice and I cannot seem to get this button to function. I have checked multiple sites and seem to be formatting it right. Everything else in my code works properly.

Here is the code:

    <html>
    <head>
        <title>This is a picoCTF JS Example</title>
        <script>
            function myFunctionSum(){
                var number1 = document.getElementById("number1").value;
                var number2 = document.getElementById("number2").value
                car result = number(number1) + Number(number2);
                alert(result);
            }
        </script>
    </head>
    <body>
        <h1>JavaScript example to add2 numbers</h1>
        Input the first number<br>
        <input type="text" id="number1" ><br>
        Input the second number<br>
        <input type="text" id="number2"
        <button onclick="myFunctionSum()"> Show alert! </button>
    </body>
</html>

It is the button portion that seems to not be working. Appreciate all the help.

cant find the matching array of object search by id

i used a custom hook and i want to show a single item which is matched by particular id,i tried multiple method but didnt work.here is my code :

const SingleServiceDetail = () => {

const {idOfService} = useParams();
const [data] = useCustom();

const singleItem = data.find(element =>element._id === idOfService);
console.log(singleItem);
return (
    <div>
        <h2>You have Choosed :{idOfService}</h2>
        {/* <p>{singleItem.name}</p> */}
    </div>
);

};

Converting div block that includes sag d3 chart into the image throws an error Extra content at the end of the document

Converting div block that includes sag d3 chart into the image throws an error Extra content at the end of the document

 SVG2PNG() {
  var canvas = document.createElement('canvas'); // Create a Canvas element.
  var ctx = canvas.getContext('2d'); // For Canvas returns 2D graphic.
  //var data = svg.outerHTML; // Get SVG element as HTML code.
    var svg = document.querySelector('.chart-root').innerHTML;
   console.log(svg)
  var img = new Image();
  img.src = 'data:image/svg+xml;base64,' + btoa(svg);
  canvas.width = 300,
  canvas.height = 500
  img.onload = function() {
    canvas
            .getContext('2d')
            .drawImage(img, 0, 0);
  }
  console.log(img.src)
  //return await canvg(canvas, data); // Render SVG on Canvas.

},

I am using above method for converting a block that includes d3 chart inside it (which is an SVG) into image however when I click the link in the console from img.src it throws an error Extra content at the end of the document What is wrong and how can I fix this conversion problem and convert it into the image properly for passing it in the PDF later

How to sort table data with data-picker in Vue?

And this is my data below, please help me sort data based on selected date in calendar! And this is my data below, please help me sort data based on selected date in calendar!

 <date-picker
          v-model="time3"
         placeholder="날짜/기간 변경"
          confirm
          valueType="format"
          :input-class="mx - input"
        ></date-picker>

**Above is my date-picker,I want to show data based on selected date in table.Above is my date-picker,I want to show data based on selected date in table.**
<table>
      <thead>
        <tr>
          <th>
            날짜
          </th>
          <th
          >
            결제 금액
          </th>
          <th >
            결제 비율
          </th>
          <th>
            결제당 결제 금액
          </th>
          <th>
            환불 금액
          </th>
          <th>
            환불 비울
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user">
          <td>{{ user.date }}</td>
          <td>{{ user.amount }}</td>
          <td>{{ user.rate }}</td>
          <td>{{ user.per_payment }}</td>
          <td>{{ user.refund_amount }}</td>
          <td>{{ user.refund_rate }}</td>
        </tr>
      </tbody>
    </table>

And this is my data below, please help me sort data based on selected date in calendar! And this is my data below, please help me sort data based on selected date in calendar!

 time3:null,
      users: [
        {
          date: "2020-01-01",
          amount: "5.2100.000",
          rate: "99%",
          per_payment: "50.000",
          refund_amount: "30.000",
          refund_rate: "0%",
        },
        {
          date: "2020-01-01",
          amount: "5.2100.000",
          rate: "99%",
          per_payment: "50.000",
          refund_amount: "30.000",
          refund_rate: "0%",
        },
        {
          date: "2020-01-01",
          amount: "5.2100.000",
          rate: "99%",
          per_payment: "50.000",
          refund_amount: "30.000",
          refund_rate: "0%",
        },
        {
          date: "2020-01-01",
          amount: "5.2100.000",
          rate: "99%",
          per_payment: "50.000",
          refund_amount: "30.000",
          refund_rate: "0%",
        },
        {
          date: "2020-01-01",
          amount: "5.2100.000",
          rate: "99%",
          per_payment: "50.000",
          refund_amount: "30.000",
          refund_rate: "0%",
        },
      ],

Final result should be sorted data based on selected date in my data picker

How to resolve ERR_PROXY_CONNECTION_FAILED in puppeteer connection while calling page.goto

Image of error I receive while the code executes

Here is the code I am using :

proxy.js –

class Proxy
{
    static create() {
     return new Proxy();
   }
   this.browser = await puppeteer.launch({
       args: [`--proxy-server=socks5:127.0.0.1:9150`, "--no-sandbox",
      ],
     });
    async newPage(newBrowser = false) {
     /* Ensure a browser instance is present */
     if (!this.browser) {
       await this.launchNewBrowser();
     }
 
     /* Close all other pages/tabs */
     await this.closePages();
}

connections.js ( calling from this file )

const createTBrowser = require("..pathTo/proxy");   
const Browser = createBrowser();
const page = await Browser.newPage();
await page.goto('Valid_URL');

How To Filter and Search the Selected value in Dropdown in Datatables using Jquery in MVC5?

I Want to get the data in the DropDownList and to Show in the datatable, but i’m not getting the desired one.

    <div class="card-header d-flex align-items-center">
        <h4>Web API Logs</h4>
        <div class="col-sm-4">
        </div>
    </div>
    <div class="card-header">
        <form action="" id="searchForm" name="searchForm">
            <div class="row">
                <div class="col-sm-3">
                    <div class="form-group">
                        <label for="txtFromDate" class="col-sm-12 control-label">From Date</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <input id="txtFromDate" name="txtFromDate" type="text" class="form-control date-input" readonly="readonly" />
                                <label class="input-group-btn" for="txtFromDate">
                                    <span class="btn btn-default">
                                        <span class="fa fa-calendar"></span>
                                    </span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-3">
                    <div class="form-group">
                        <label for="txtToDate" class="col-sm-12 control-label">To Date</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <input id="txtToDate" name="txtToDate" type="text" class="form-control date-input" readonly="readonly" />
                                <label class="input-group-btn" for="txtToDate">
                                    <span class="btn btn-default">
                                        <span class="fa fa-calendar"></span>
                                    </span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-3">
                    <div class="form-group">
                        <label for="type" class="col-sm-12 control-label">Type</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <select id="type" name="txttype" class="form-control dropdown" style="height:33px" tabindex="17">
                                    <option value=""></option>
                                    <option value="">All</option>
                                    <option value="offers">Offers</option>
                                    <option value="Subs">Subscribers</option>
                                    <option value="login">Login</option>
                                </select>

                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-3">
                    <div class="form-group">
                        <label for="status" class="col-sm-12 control-label">Status</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <select id="status" name="status" class="form-control dropdown " style="height:33px" tabindex="17">
                                    <option value=""></option>
                                    <option value="">All</option>
                                    <option value="ss">Success</option>
                                    <option value="cust">Customer  failed</option>
                                    <option value="fle">Failed</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>


            </div>
            
            <div class="col-md-2" style="margin-top: 6px">
                <input type="submit" class="btn btn-primary mt-4" id="btnSearch" value="Search" />
                
                @*<span class="btn btn-success mt-4"></span>*@
              </div>
</div>
        </form>

    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-sm-12">
                <table id="logviewgrid" class="table table-striped table-bordered dt-responsive nowrap" style="width:100%"></table>
            </div>
        </div>
    </div>
</div>
<div id="loading" style="display: none">
    <p class="div_processing">Processing..</p>
</div>

This is the View in that Action And Status fields are the DropDownlist, from that list I want to search and fetch the values based on that.

This the Jquery Ajax Function for Type Dropdown

 $.ajax({
                type: 'GET',
                url: '@Url.Action("Actionurl")',
                dataType: 'json',
                data: { id: $("#txttype").val() },
                success: function (datas, status) {
                    var duplicate = [];

                    $("#txttype").append('<option value="' + "" + '">' + " " + '</option>');

                    $.each(datas, function (i, data) {
                        if (duplicate.indexOf(data.fld_type) == -1) {
                            $("#txttype").append('<option value="' + data.fld_type+ '">' + data.fld_type+ '</option>');

                            duplicate.push(data.fld_type);
                        }

                    });
                }

            });

This the Jquery Ajax Function for Status Dropdown

 $.ajax({
                type: 'GET',
                url: '@Url.Action("Actionurl")',
                dataType: 'json',
                data: { id: $("#status").val() },
                success: function (datas, status) {
                    var duplicate = [];

                    $("#status").append('<option value="' + "" + '">' + " " + '</option>');

                    $.each(datas, function (i, data) {
                        if (duplicate.indexOf(data.fld_status) == -1) {
                            var code = data.fld_status.split('CC-');
                            $("#status").append('<option value="' + code + '">' + data.fld_status+ '</option>');

                            duplicate.push(data.fld_status);
                        }

                    });
                }

            });

This is the DataTable and search Ajax Jquery Function

 $('#logviewgrid td').css('white-space', ' ');



             $("#searchForm").validate({
                errorClass: "error-class",
                validClass: "valid-class",
                errorElement: 'div',
                errorPlacement: function (error, element) {
                    if (element.parent('.input-group').length) {
                        error.insertAfter(element.parent());
                    } else {
                        error.insertAfter(element);
                    }
                },
                onError: function () {
                    $('.input-group.error-class').find('.help-block.form-error').each(function () {
                        $(this).closest('.form-group').addClass('error-class').append($(this));
                    });
                },
                rules: {
                    txtFromDate: "required",
                    txtToDate: "required"
                },
                messages: {
                    txtFromDate: "From Date Is Required",
                    txtToDate: "To Date Is Required"

                },
                 submitHandler: function (form) {
                     $('#loading').show();

                    $.ajax({
                        url: '@Url.Action("SearchWebApiLog", "Report")',
                        type: 'GET',
                        data: {
                            fldFromDate: moment($('#txtFromDate').val(), 'DD/MM/YYYY').toISOString(),
                            fldToDate: moment($('#txtToDate').val(), 'DD/MM/YYYY').add(1, 'days').toISOString(),
                            fld_type: $('#txttype').val().toString(),
                            fld_status: $('#status').val().toString(),
                            //cause: $('#txtcause').val().toString(),
                            //servicetype: $('#txtservice').val().toString(),
                            //custid: $('#txtcustid').val().toString()
                        },
                        error: function () {
                            $('#loading').hide();
                            var notify = $.notify('<strong>Error</strong> An error has occurred. Contact administrator.!', {
                                allow_dismiss: true,
                                type: 'danger'
                            });
                            return false;
                        },
                        success: function (data, status) {
                            if (status == 'success') {

                                //if (data.status = "") {

                                //}

                                table.clear().draw();
                                //table.rows.add(eval('(' + data + ')')); // Add new data
                                table.rows.add(data);
                                // Redraw the DataTable
                                table.columns.apply().draw();
                                $('#loading').hide();
                            } else {
                                $('#loading').hide();
                                var notify = $.notify('<strong>Warning</strong> Error for reading online count details. Please contact administrator.!', {
                                    allow_dismiss: true,
                                    type: 'warning'
                                });
                                return false;
                            }

                            return false;
                        }

                    });
                    return false;

                 }
            })