Jquery and JSON - I can not show the data

1

I'm learning jquery and trying to understand Json.

I have a page called index.php where when loading, a query of all the products is generated by php, it dynamically arms me an amount of divs (.boxes) and shows them to me.

The issue is that I added a select so that after that first view, it can be filtered by product category.

By jquery I get the change of select and something unexpected happens:

  • All the boxes that can be seen on the screen are assembled (does not match the number of records) , they are blank for 2 seconds and then they are all filled with data from the first record.
  • If I do console.table(response); , it throws me the correct records in console, I even put a alert($.trim(value.id)); at the end of .each and it shows me the correct registration ids.
  • The idea is to delete the DIV , and recreate it dynamically from jquery with the data filtered by category.
  • I put the parts that I think are the most important, if it's necessary I hang it from a pastebin, it's not a lot of code but it's 3 files:

    index.php

    <?php
         session_start();
    ?>
    
    <html>
        <head>
            <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
            <link href="css/estilo.css" rel="stylesheet" type="text/css" />
            <script src="jquery-3.1.0.js" type="text/javascript"></script>
    
            <script>
                var getdetailsfilter = function(categoria) {
                    return $.getJSON("busca_articulos.php", {
                        "categoria": categoria
                    });
                };
    
                $(document).ready(function() {
                    $('#combo_categorias').unbind('change').bind('change', function(e) {
                        optionSeleccionado = $(this).val();
                        alert(optionSeleccionado);
                        // Borro las cajas
                        fila = '';
                        $('.caja').empty();
                        getdetailsfilter(optionSeleccionado).done(function(response) {
                            console.table(response);
                            fila += $.each(response.data.arts1, function(key, value) {
                                $('.caja').append("<div class='caja_imagen'><img src=" + $.trim(value.imagen) + " style=widht='100' height='100' /><p class='caja_nombre'>" + $.trim(value.nombre) + "</p><p class='caja_precio'>$ " + $.trim(value.precio) + "</p></div><div class='caja_boton'><form action='detalle.php' method='POST' name='detalle'><input name='id' type='hidden' value=" + $.trim(value.id) + " /><input class='boton_detalle' type='submit' value='Detalle'></form></div></div>");
                                alert($.trim(value.id));
                            });
                        });
                    });
                });
            </script>
        </head>
    

    File PHP search_articles.php

    $jsondata = array();
    $cad = "SELECT * FROM 'productos' WHERE 'categoria' LIKE '%{$categoria}%' Order by 'nombre';";
    
    if ($result = $con - > query($cad)) {
        if ($result - > num_rows > 0) {
            $jsondata["success"] = true;
            $jsondata["data"]["message"] = sprintf("Se ha encontrado %d coincidencia", $result - > num_rows);
            $jsondata["data"]["arts1"] = array();
    
            while ($row = $result - > fetch_object()) {
                $jsondata["data"]["arts1"][] = array("id" => $row - > id, "imagen" => $row - > imagen, "nombre" => $row - > nombre, "descripcion" => $row - > descripcion, "costo" => $row - > costo, "precio" => $row - > precio, "stock" => $row - > stock, "categoria" => $row - > categoria);
            }
        } else {
            $jsondata["success"] = false;
            $jsondata["data"] = array(
                'message' => 'No se encontró ningún resultado.'
            );
        }
    } else {
        $jsondata["success"] = false;
        $jsondata["data"] = array(
            'message' => $database - > error
        );
    }
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($jsondata, JSON_FORCE_OBJECT);
    $con - > close();
    }
    exit();
    
        
    asked by look68 18.10.2016 в 15:52
    source

    1 answer

    1

    The reason why all white is left for X amount of seconds is because you are cleaning the box before having the results. Try changing your code to this:

    $(document).ready(function() {
        var getdetailsfilter = function(categoria) {
            return $.getJSON("busca_articulos.php", {
                "categoria": categoria
            });
        };
    
        $('#combo_categorias').on('change', function(e) {
    
            getdetailsfilter($(this).val())
                .done(function(response) {
                    var html = ''; // Acumulador
    
                    $.each(response.data.arts1, function(key, value) {
                        html += "<div class='caja_imagen'><img src=" + $.trim(value.imagen) + " style=widht='100' height='100' /><p class='caja_nombre'>" + $.trim(value.nombre) + "</p><p class='caja_precio'>$ " + $.trim(value.precio) + "</p></div><div class='caja_boton'><form action='detalle.php' method='POST' name='detalle'><input name='id' type='hidden' value=" + $.trim(value.id) + " /><input class='boton_detalle' type='submit' value='Detalle'></form></div></div>";
                    });
    
                    $('#caja').html(html); // Sobre escribir el contenido HTML de <div id="caja"
                });
        });
    });
    
        
    answered by 18.10.2016 в 17:15