Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

352
Vistas
how to send array data from java script to flask

how to send array from javascript to python flask. the ajax is not returning the array (values)to flask route .Can anyone please help with these error

#flask route
@app.route('/admin',methods = ['POST','GET'])
def admin():
    if request.method == "POST":
        a=request.form.getlist("contacts[]")
        return str(a)
#js code
window.onload = function(){}
var btn = document.querySelector("#btn");
btn.onclick = function(){
    var div= document.createElement("div");
    div.innerHTML = generateit();
    document.getElementById("box").appendChild(div);
}

function generateit()
{
 return "<input type='text' class='txt' placeholder='Enter party name' required>&nbsp<input type='text' class ='txt1' placeholder = 'Enter region' required>&nbsp<input type='text' class='txt2' placeholder='Enter name' required>&nbsp<button id ='btn' onclick='removeit(this);'>Remove</button>";
}

function removeit(btn)
{
    document.getElementById("box").removeChild(btn.parentNode);
}

values =[]
$.ajax({
    url:'{{url_for("admin")}}',
    type:'POST',
    data:{contacts:values},
    success:function(res){}
  });




}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

let assume that your html code is like this:

<butoon id="generate_row">generate row</butoon>
<div id="box">
    <button onclick="send()">send</button>
</div>

here is your javascript code:

    window.onload = function () {
        var btn = document.querySelector("#generate_row");
        var box = document.getElementById("box");

        btn.onclick = function () {
            var div = document.createElement("div");
            var row_num = box.querySelectorAll("#box > div").length + 1;  // add 1 to start from 1
            div.innerHTML = generateit(row_num);
            box.appendChild(div);
        }
    }

    function generateit(row_num) {
        return `<input type='text' placeholder='Enter party name' required>
                <input type='text' placeholder = 'Enter region' required>
                <input type='text' placeholder='Enter name' required>
                <button id ='btn_remove${row_num}' onclick='removeit(this);'>Remove</button>`;
    }

    function removeit(btn) {
        document.getElementById("box").removeChild(btn.parentNode);
    }

    function send() {
        values = [];
        let divs = document.querySelectorAll("#box > div");

        divs.forEach(innerDiv => {
            let innerDivValues = [];
            let textInputs = innerDiv.querySelectorAll("input[type='text']");
            textInputs.forEach(inputElement => innerDivValues.push(inputElement.value))
            values.push(innerDivValues);
        });
       
        
        fetch('{{url_for("site_bp.formit")}}', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({contacts: values})
        }).then(async response => await response.json())
        .then(data => {
            console.log(data);
        })
    }

and your flask route:

@bp.route('/formit',methods = ['POST','GET'])
def formit():
    if request.method == "POST":
        contacts=request.json.get("contacts", None)
        for contact in contacts:
            print (contact)
        return {"contacts": contacts}
    return "not post request"

i used blueprints so don't be confused about that @bp or site_bp.formit

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda