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.


            type: "POST",
            url: "../gestionweb/views/modules/stock/procesostock.php",

            error: function(){
                alert("error petición ajax");

                    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>'

                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");


            type: "POST",
            url: "../gestionweb/views/modules/stock/procesostock.php",

            error: function(){
                alert("error petición ajax");
           alert("actualizacion exitosa");
  }); } });

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?


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".


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).


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:


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>');


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:

    "envases":["medio litro", "litro", "pitcher", "pecera", "barril"]
    "envases":["medio litro", "litro", "pitcher", "pecera", "barril"]
    "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.


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.


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.


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.


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!!!


            type: "POST",
            url: "../gestionweb/views/modules/venta/procesoventa.php",

            error: function(){
                alert("error petición ajax");
                   $.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>'+
    '<td>60 lts</td>'+
    +'<td><input type="button" id="Confirmar" value="Confirmar" class="btn btn-primary" /></td>'
    +'<td><input type="button" id="Confirmar" value="Confirmar" class="btn btn-primary" /></td>'
   ' </tr>'+
   ' </tbody>'+
      '     </div></div></div> ' +
      '  </div>';




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: