0 votes

Create html content according to database with JQUERY

I am developing a system for a brewery and it has two types of containers: half and quarter, but what if in the future I want to add the whole (1 liter)? In the sales window must appear this type of container. The same can happen in any system because all organizations vary.

So I wanted to ask you what is the most correct way or at least some method to dynamically create the html content and be able to process it.

I mean I should have an AJAX process where I would query the list of containers from a bd table obviously. And then I should create an input or whatever I need for each result with a different id. Is this correct? For example, the following code I have it in the click of a button, in a form where a provision of merchandise is entered, and then the 3 measures appear to update its price.

$.ajax({

            type: "POST",
            url: "../gestionweb/views/modules/stock/procesostock.php",
                data:{"accion":accion,"idprod":idprod,"barril":barril,"precio":precio},

            error: function(){
                alert("error petición ajax");
            },
            success:function(data)
            {

                    $("#prod").val("");
                    $("#prov").val("");
                    $("#cant").val("");
                    $("#gasto").val("");
                    alert("Operacion realizada con exito");

                    var contenido= '<div class="row" id="precios">'+
           '<div class="col-sm-2"><label>PRECIO FINAL 1/4</label></div>'+

    '<div class="col-sm-2"><input type="text" class="form-control" id="preciocuarto" placeholder="1/4 l."/>'+
      '</div><div class="col-sm-2"><label>PRECIO FINAL 1/2</label></div>'+

    '<div class="col-sm-2">'+
     '<input type="text" class="form-control" id="preciomedio" placeholder="1/2 l."/>'+
       '</div><div class="col-sm-2"><label>PRECIO FINAL 1</label></div>'+

   ' <div class="col-sm-2">'+
     ' <input type="text" class="form-control" id="precio1" placeholder="1l"/>'+
       '</div><div class="col-sm-2"><label>PRECIO ENVASE</label></div>'+

    '<div class="col-sm-2">'+
     ' <input type="text" class="form-control" id="precioentero" placeholder="barril"/>'+
      ' </div> <input type="button" id="actprecio" value="Actualizar" class="btn btn-primary" /></div>'
                    $(contenido).appendTo("#grupo");
                    $("#produ").attr("disabled",true);
                  $("#actprecio").click(function(){

                var preciocuarto=$("#preciocuarto").val();
                var preciomedio=$("#preciomedio").val();
                var precioentero=$("#precio1").val();
                var preciouno=$("#precioentero").val();
                if( preciocuarto=="" || preciomedio=="" || precioentero=="" || preciouno==""){
                    alert("complete todos los campos");
                }else{

                $.ajax({

            type: "POST",
            url: "../gestionweb/views/modules/stock/procesostock.php",
       data:{"accion":"actualizar","idprodu":idprod,"preciocuarto":preciocuarto,"preciomedio":preciomedio,"preciouno":precioentero,"entero":preciouno},

            error: function(){
                alert("error petición ajax");
            },
            success:function(data)
            {
           alert("actualizacion exitosa");
       window.location.href="index.php?controller=stock&action=indexb";
            }
         });}
         });
           }  
  }); } });

As you can see I create a variable with the html content. That is to say, should I make an ajax call to know what types of containers there are, and create html content for each one?

2voto

amenadiel Points 14124

Let's see... your question does not allude to a specific problem, and therefore should be called:

What is the logic of a flow where the frontend has to display dynamic results that adapt if I add elements in the database".

Or

What algorithm can be used to represent in the frontend a backend response whose attributes may change over time?

This question is a bit more answerable, because it applies to all backend languages, connected to any database, and using any frontend framework (or none).

Then:

The logic for this kind of flow is to design the front end by telling it: "Itera over the loop as many times as the backend sends you records".

And to the backend: "Send as many records as different types of categories you want to print".

In your example, you have a brewery and your criteria to distinguish is the size of the container. Then in your backend you execute a query of the type:

SELECT DISTINCT nombre, precio FROM producto 

And you return an array in JSON format containing:

[{
    "nombre":"producto1",
    "precio":10
},{
    "nombre":"producto2",
    "precio":20
},{
    "nombre":"producto3",
    "precio":30
}];

Let's think that the frontend stores this data in a variable respuesta and each response generates an HTML block inside a container with id #resultado . So, again in general terms, the front end would put

foreEach(respuesta, function(producto) {
   var bloque=jQuery('<div class="producto">');
   bloque.append('<div class="nombre">'+producto.nombre+'</div>');
   bloque.append('<div class="precio">'+producto.precio+'</div>');

   bloque.appendTo('#resultado');
});

Nested data

Looking at your code, what you want is to have for the same product, a division sub-criteria. It does not make sense for each product variant to create additional columns in the table. . The database schema should be designed so that you can add infinite combinations of product and size by simply adding rows.

Then the backend would adapt the query more or less as follows:

-- postgres
SELECT nombre, json_agg(envase), avg(precio) as precio FROM producto group by nombre

-- mysql
SELECT nombre, JSON_ARRAYAGG(envase), avg(precio) as precio FROM producto group by nombre

And the backend response could be:

[{
    "nombre":"cerveza1",
    "precio":10,
    "envases":["medio litro", "litro", "pitcher", "pecera", "barril"]
},{
    "nombre":"cerveza2",
    "precio":20,
    "envases":["medio litro", "litro", "pitcher", "pecera", "barril"]
},{
    "nombre":"cerveza3",
    "precio":30
    "envases":["medio litro", "litro", "pitcher", "pecera", "barril"]
}];

Again, the logic repeats, the backend sends you an array containing arrays. Whenever you work with arrays you know the length of the array (property length ) and you can use it to iterate by adding elements to your loop.

In the particular case of your example, this is not a good approach and since browser space across the width is a scarce commodity (as opposed to the height, no one is used to scroll to the side), diagramming with variable columns is not a viable way to go.

You could instead study diagramming with cards. Let me explain: Each product is a card that occupies one third of the width of the container. It can have N types of packaging, but you know that it has a name, an average price and a photo (for example). Then the body of your card has as a fixed layout the data you do have standardized and, as a stand, in a container with ample space, data that may vary either over time or between products package sizes such as tabs, or squares, or chips.

introducir la descripción de la imagen aquí

Let's say, you have to basarte in what you can take for granted and handle which can be variable. In this case, there are N beers, but there is no problem with each beer occupying a third of the screen, if they are going to be ordered in rows of three.

On the other hand, if each beer has a child element of variable length, or several custom attributes, you have to handle that case with some layout logic (in the image above, the chips could occupy a quarter of the card and be arranged in rows of 4).

Basically, you adapt your layout to the way you know your data will change.

If the purchase process involves configuring how many units you want and what size, the base of each card has an input for the number of units and you can only activate one chip at a time. The price of the cart changes according to your actions on each card. Note that for this, the subcriterion must be an array of objects with attributes "size" and "price". This is particular to your flow, everyone will have to adapt it to how it works best for them.

Finally:

To go even further, and this is going to the extreme, let's think that you have a marketplace like AliExpress. Each product has or can have different attributes.

  • If you sell a trouser it has attributes color y tamaño .
    • color is an array of 10 colors.
    • tamaño is an array of 6 sizes.
  • If you sell a microSD memory card, it has only the attribute capacidad (16, 32 and 64 GB)
  • A third product may have no attributes or variations
  • A fourth product can have many attributes and among these many variations.

In this case, the database would have a tuple of three levels

producto | atributo  | valor | precio
---------------------------------------
vestido  | color     | rojo  | 10
vestido  | color     | azul  | 10
microsd  | capacidad | 16GB  | 20  <--- mala compra, conviene el de 32
microsd  | capacidad | 32GB  | 25  

But already in that scenario, it would not be healthy to put everything in the same table and you would have to redesign the database in third normal form. This I only raised as the most elaborate example and it is not worth going into detail.

0voto

phpMyGuel Points 3336

I don't know how you have organized your DB but I suppose that each beer can be sold in one or more of the capacity formats (1/4, 1/2 and 1/1) and that these depend on the manufacturer. What I would do would be to have in my table "Beers" (I suppose you will have one to store the data of each beer) a field for each of the measurement formats in which it is marketed and value it in "0" if it is not marketed in that format and in "1" if it is marketed in that format.

Then, when it comes time to paint the HTML of your view, in the loop that runs through each beer to paint it, check the values of these fields and construct the option of your select based on it.

All this speaking from hypothetical, because as I told you, there is information I lack to refine further.

You really wouldn't need a phone call AJAX to do this, since you are not going to generate content dynamically, but at the moment of painting the HTML you now have all the necessary data to know the size formats in which each of the beers are sold.

EDIT

I just read that what you do when you select a value for the beer measurement format is update the purchase price. There you would use a callback AJAX to ask your DB the price of that specific measurement format.

You could do this with a function change() from Jquery to launch the query depending on the option of the user's choice.

I don't think I have left anything out and I hope it will help you to orientate your application a little.

0voto

Caruso Points 188

Of course, the logic is the same for different cases since many things are variable. In this brewery these measures are sold from kegs that are on tap, and tomorrow there may be more or fewer taps.

So with Bootstrap create a panel, or what amenadiel call little cards, and putting 3 per row (3 td per tr) is enough for the space it occupies.

Then it should divide by 3, if there are 7 bobbins it is two rows of 3 and one row with one. But in bootstrap the width must add up to 12, so with:

'<div class="col-sm-4" >

I already specified that 3 fit, it's great!!!

$.ajax({

            type: "POST",
            url: "../gestionweb/views/modules/venta/procesoventa.php",
                data:{"accion":"lcanillas"},

            error: function(){
                alert("error petición ajax");
            },
            success:function(data)
            {
         console.log(data);
                   $.each(JSON.parse(data), function (index, item) {
         var contenido='<div class="col-sm-4" > '+
         '<div class="panel panel-danger">'+
          '<div class="panel-heading">CANILLA '+item.idcanilla+'</div>'+
          '<div class="panel-body">'+
        '<table class="canilla">'+
   ' <thead>'+
    '<th></th>'+
    '<th>Valor</th>'+
    '<th>Accion</th>'+
    '</thead>'+
    '<tbody>'+
    '<tr>'+
    '<td>Estado</td>'+
    '<td>60 lts</td>'+
    '</tr>'+
    '<tr>'+
    '<td>Cuarto</td>'+
    '<td>$10</td>'+
    +'<td><input type="button" id="Confirmar" value="Confirmar" class="btn btn-primary" /></td>'
    '</tr>'+
    '<tr>'+
    '<td>Medio</td>'+
    '<td>$15</td>'
    +'<td><input type="button" id="Confirmar" value="Confirmar" class="btn btn-primary" /></td>'
   ' </tr>'+
   ' </tbody>'+
  '</table>'+
      '     </div></div></div> ' +
      '  </div>';
      $(contenido).appendTo("#canilla1");
                });

                }

});

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X