Hola buena tarde!!!

Hola buena tarde!!!

Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0
edited November 2022 in Free community support

Estoy tratando de obtener los datos en array de una tabla pero al extraerlos no los pone en un formato correcto

var datos_tabla = table.rows().data().toArray();
$("#id_data_table_carrito").val(JSON.stringify(datos_tabla) ) ;

obtengo algo asi :

[[22, '5', 'pza', 'VARILLA 3/8', '158.879', '794.39', "<i class='fa fa-check-square-o fa-lg' aria-hidden='
true'></i>"], [30, '10', 'kg', 'ALAMBRON', '26.121', '261.21', "<i class='fa fa-check-square-o fa-lg' aria-hidden='true'></i>"], [31, '7', 'pza', 'ARMEX 15-20', '160', 
'1120', "<i class='fa fa-check-square-o fa-lg' aria-hidden='true'></i>"], [34, '15', 'bulto 50 kg', 'CEMENTO', '165', '2475', "<i class='fa fa-check-square-o fa-lg' ari
a-hidden='true'></i>"]]

Si notan el primer 22 no tiene '', despues trato de meterselo de nuevo a la datatables y da error
aqui el punto es como le indico a datatables que lo extraiga como string??? para que me permita despues volverselo a cargar a la misma datatables.
De antemano muchas gracias, soy nuevo en este foro y me gusta la herramienta.
Saludos

Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

Answers

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736
    edited November 2022

    I'm trying to get the data in array from a table but extracting it doesn't put it in a correct format

    If you notice the first 22 does not have '', then I try to put it back to the datatables and it gives error Here the point is how I tell DataTables to extract it as a string??? to allow me to then reload it to the same datatables. Thank you very much in advance, I am new to this forum and I like the tool. Best regards

    var datos_tabla = table.rows().data().toArray();
    

    This will result in a Javascript array, just like you posted.

    $("#id_data_table_carrito").val(JSON.stringify(datos_tabla) ) ;
    

    Is this what you are using to add it back to the table? This is not the correct way. Use rows.add(). For example:

    var datos_tabla = table.rows().data().toArray();
    table.rows.add( datos_tabla ).draw();
    

    Kevin

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0
    edited November 2022

    hola otra vez gracias por tu respuesta.

    este es el metodo con el que trato de meterle de vuelta los datos:

    var table = $('#tabla_carrito').DataTable({
                        "data" : json_data_table_carrito,
                        columns: [
                                    { title: "Id" },
                                    { title: "Cantidad" },
                                    { title: "U. Medida" },
                                    { title: "Articulo" },
                                    { title: "Precio" },
                                    { title: "Total" },
                                    { title: "Entregado" }
                        ]
                    });
    
  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    ya intente :
    var datos_tabla = table.rows().data().toArray();
    table.rows.add( datos_tabla ).draw();

    y obtengo esto de la imagen...

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    I copied your code into this test case and it works:
    http://live.datatables.net/tiwegele/1/edit

    Please update the test case or provide a link to your page so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Tratare de reproducir exactamente el error y los detalles que tengo:
    Navegador firefox 107.0 (64-bit)
    SO Linux
    Lenguaje de programacion DJANGO + Python3

    En la pagina compras tengo un carrito de compras:

    var table = $('#tabla_carrito').DataTable();
    var datos_tabla = table.rows().data().toArray();
    $("#id_data_table_carrito").val(JSON.stringify(datos_tabla) ) ;
    

    Al hacer post guardo lo de $("#id_data_table_carrito").val() en un campo en la base de datos

    despues intento desde otra pagina distinta meter esos datos en una tabla identica a la del carrito y da error

    if BitacoraCompra.objects.filter(orden_compra = json_data['id']).exists():
    
        movimientos = BitacoraCompra.objects.filter(orden_compra = json_data['id']).values()
    
        data = list(movimientos)
    
        return JsonResponse(data,safe = False)
    

    lo que retorno es esto:

            [['1', '1', 'm3', 'Arena', '111', '111', '<i class="fa fa-square-o fa-2x" aria-hidden="true"></i>'], ['2', '2', 'VIAJE 30M3', 'Arena por tolva', '2222', '4444', '<i class="fa fa-square-o fa-2x" aria-hidden="true"></i>'], ['3', '33', 'm3', 'GRAVA', '33333', '1099989', '<i class="fa fa-square-o fa-2x" aria-hidden="true"></i>']]
    

    Despues trato de meterselo al datatables y da error adjunto imagenes:

    var json_data_table_carrito = data[0]['json_data_table_carrito'] ;
    
    alert(data[0]['json_data_table_carrito'])
    
    var table = $('#id_bitacora').DataTable();
    
    table.rows.add( json_data_table_carrito ).draw();
    
    $("#id_bitacora").css('width', '100%');
    
    
    $("#myModal").modal("show");
    

    Tambien probe con :

                    var table = $('#id_bitacora').DataTable({
                        "data" : json_data_table_carrito,
                        columns: [
                                    { title: "Id" },
                                    { title: "Cantidad" },
                                    { title: "U. Medida" },
                                    { title: "Articulo" },
                                    { title: "Precio" },
                                    { title: "Total" },
                                    { title: "Entregado" }
                        ]
                    });
    

    pero no sirve y tambien probe con :

    var json_data_table_carrito =  JSON.parse(data[0]['json_data_table_carrito']) ;
    

    y obtengo :

    ![](https://datatables.net/forums/uploads/editor/bk/aclmv5zilppo.png "") ![](https://datatables.net/forums/uploads/editor/fu/pce46h18svve.png "") ![](https://datatables.net/forums/uploads/editor/83/yim644zv3bus.png "")

    algun error en mis metodos o bug de datatables???

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Voy a tratar de describir exactamente el error:

    SO Liunux
    Firefox
    Django + Python3
    Postgres

    var table = $('#tabla_carrito').DataTable();
    var datos_tabla = table.rows().data().toArray();
    $("#id_data_table_carrito").val(JSON.stringify(datos_tabla) ) ;
    

    despues meto esto $("#id_data_table_carrito").val() en un campo de la base de datos.

    en otra pagina quiero volver a meter lo que guarde en una tabla identica a la del carrito:

            var json_data_table_carrito = data[0]['json_data_table_carrito'] ;
    
            var table = $('#id_bitacora').DataTable();
    
            table.rows.add( json_data_table_carrito ).draw();
    

    Pero no funciona(adjunto imagen), ya probe con :

            var table = $("#id_bitacora").DataTable({
                "data" : json_data_table_carrito ,
                columns: [
                            { title: "Id" },
                            { title: "Cantidad" },
                            { title: "U. Medida" },
                            { title: "Articulo" },
                            { title: "Precio" },
                            { title: "Total" },
                            { title: "Entregado" }
                ]
            });
    

    y tambien :

    var json_data_table_carrito = JSON.parse(data[0]['json_data_table_carrito']) ;

    da el siguiente error

    Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 3 of the JSON data

    Algun error en mi codigo o bug de datatables???



  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Voy a tratar de describir exactamente el error:

    SO Liunux
    Firefox
    Django + Python3
    Postgres

    var table = $('#tabla_carrito').DataTable();
    var datos_tabla = table.rows().data().toArray();
    $("#id_data_table_carrito").val(JSON.stringify(datos_tabla) ) ;
    

    despues meto esto $("#id_data_table_carrito").val() en un campo de la base de datos.

    en otra pagina quiero volver a meter lo que guarde en una tabla identica a la del carrito:

                var json_data_table_carrito = data[0]['json_data_table_carrito'] ;
    
                var table = $('#id_bitacora').DataTable();
    
                table.rows.add( json_data_table_carrito ).draw();
    

    Pero no funciona(adjunto imagen), ya probe con :

                    var table = $("#id_bitacora").DataTable({
                        "data" : json_data_table_carrito ,
                        columns: [
                                    { title: "Id" },
                                    { title: "Cantidad" },
                                    { title: "U. Medida" },
                                    { title: "Articulo" },
                                    { title: "Precio" },
                                    { title: "Total" },
                                    { title: "Entregado" }
                        ]
                    });
    

    y tambien :

    var json_data_table_carrito = JSON.parse(data[0]['json_data_table_carrito']) ;

    da el siguiente error

    Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 3 of the JSON data

    Algun error en mi codigo o bug de datatables???



  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Estos son los datos :

    [['1', '1', 'm3', 'Arena', '111', '111', '<i class="fa fa-square-o fa-2x" aria-hidden="true"></i>'], ['2', '2', 'VIAJE 30M3', 'Arena por tolva', '2222', '4444', '<i class="fa fa-square-o fa-2x" aria-hidden="true"></i>'], ['3', '33', 'm3', 'GRAVA', '33333', '1099989', '<i class="fa fa-square-o fa-2x" aria-hidden="true"></i>']]

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Nota si funciona esto en la misma pagina pero ahora que estoy tratando de llevarme estos datos a otra pagina diferente pasa esto.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    Note if this works on the same page but now that I'm trying to take this data to a different page this happens.

    The problem is the data from one page isn’t directly accessible from another page. This is not a Datatables issue. See this SO thread for ideas of how to store the data to be used on another page.

    Kevin

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Ok pero resulta que tengo otras paginas que me llevo los datos asi como describo arriba y en algunas ocaciones si funciona pero en esta no, a que se debe esto?
    Nota si te das cuenta es como si solo reconociera una columna en la foto que adjunte se aprecia, incluso lo toma como texto trasnformado a array se puede apreciar en la foto que conviere en array un string por que los ordena alfabeticamente ver foto showing 321 of 327 of 327 entries pagina 33 col 1 = u vvvv xxx

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    This is my understanding of you solution.

    This is storing the Datatables row data in an array, which is working:

    var datos_tabla = table.rows().data().toArray();
    

    Then you are storing the data as a JSON string with this:

    $("#id_data_table_carrito").val(JSON.stringify(datos_tabla) ) ;
    

    On the other page you are accessing the stored data with this:

    var json_data_table_carrito = data[0]['json_data_table_carrito'] ;
    

    What is the value and data type of json_data_table_carrito. You probably will need to use JSON.parse() to convert the JSON string into Javascript array object.

    converts a string into an array because it orders them alphabetically see photo showing 321 of 327 of 327 entries page 33 col 1

    You screenshot with blank lines is typical of adding rows to the table from a JSON string instead of a Javascript array. It looks like you have 3 rows not 327 as showin in the info element.

    Kevin

  • Abraham_MAbraham_M Posts: 12Questions: 2Answers: 0

    Hola Kevin y gracias de verdad por tu tiempo voy a intentar esto una ultima vez y si no se puede aboradre de otra manera el problema :
    entonces el error es al guardarlo como JSON.stringify ???
    voy a intentar guardarlo sin el JSON.stringify y te comento
    y voy a ponerle un
    console.log(typeof json_data_table_carrito);

    y lo pondre aca abajo para ambos casos.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    so the error is when saving it as JSON.stringify ???
    I'm going to try to save it without the JSON.stringify

    You will probably need to use JSON.stringify() to store the array object. But after retrieving is use JSON.parse() to convert it back to an array object.

    Kevin

  • seriallnumberseriallnumber Posts: 1Questions: 0Answers: 0

    Ok pero resulta que tengo otras paginas que me llevo los datos asi como describo arriba y en algunas ocaciones si funciona pero en esta no, a que se debe esto?

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736
    edited November 2022

    Ok but it turns out that I have other pages that take the data as described above and on some occasions it works but not on this one, why is this?

    Without seeing the problem its impossible to guess what the problem might be. Please provide a link to the page that exhibits the issue so we can take a look.

    You can use the browser’s debugger to step through that portion of the code to make sure it is working properly. Or, if its intermittent, use if statements to validate each step works properly and if not log errors to the console so you can narrow down where the problem is.

    Kevin

Sign In or Register to comment.