0

I need advice and help. I have a code with which I receive data from the table in json format, so that I can then send it via ajax to the server

for (var i = 1, row; row = table.rows[i]; i++) {
    let docDate = document.querySelector('input[name="invoice-date"]').value
    let docContragent = document.querySelector('select').value
    // ITEMS
    let name = row.cells[1].querySelector('span').dataset.id
    let quantity = row.cells[2].querySelector('input').value
    let buy_price = row.cells[3].querySelector('input').value
    var sell_price = row.cells[5].querySelector('input').value

    if(row == document.querySelector('.add-elements')) {
      break;
    }
   let invoice = {
    "doc_type": "capitalize",
    "date": docDate,
    "number": 98,
    "contragent_id": docContragent,
    "comment": "",
    "items": [
        {
            "product": name,
            "buy_price": buy_price,
            "sell_price": sell_price,
            "quantity": quantity
          },
        ]
      }
      let json = JSON.stringify(invoice);
      console.log(json)
    }

The problem is that there can be any number of elements in the "items" array (rows in the table) and I don't know how to implement this in javascript. And how safe is it? Maybe you know the best option for sending such data, I work with django (the only possible solution I found there was to use form sets, but it seems to me that this option will not work because of its limited customization).

I need this json output:

[
    {
        "doc_type": "capitalize",
        "date": "2022-06-04",
        "number": 1,
        "contragent_id" : 1,
        "comment": "",
        "items": [
            {
                "product": 10,
                "buy_price": "200.00",
                "sell_price": "500.00",
                "quantity": 5
            },
            {
                ...
            },
            {
                ...
            },
        ],
    }
]

The HTML of the table is added dynamically via api, with this code:

success: function (res) {
          let invoiceRow = document.querySelector(".invoice-add-table table tbody tr.add-elements").insertAdjacentHTML('beforebegin', '<tr class="invoice-row">' +
          '<td align="right" class="fixed">'+ res.articul +'</td>' +
          '<td class="name" align="left"><span data-id="'+ res.id +'" title="'+ res.name +'" style="text-decoration: underline; cursor: pointer;">'+ res.name +'</span></td>' +
          '<td align="right" class="fixed"><input name="quantity" value="'+ 1 +'" class="ta-right fixed" onkeypress="validateNum(event)" type="number"></td>' +
          '<td align="right" class="fixed"><input name="last_buy_price" value="'+ res.last_buy_price +'" class="ta-right fixed" onkeypress="validateNumFloat(event)" type="number"></td>' +
          '<td align="right" class="fixed"><input name="summ" value="" class="ta-right fixed" onkeypress="validateNumFloat(event)" type="number"></td>' +
          '<td align="right" class="fixed"><input name="sell_price" value="'+ res.sell_price +'" class="ta-right fixed" onkeypress="validateNumFloat(event)" type="number"></td>' +
          '<td align="right"><div style="display: flex;" class="edit-tool-table"><span class="iconify" onclick="test()" data-icon="bx:trash" style="color: white;" data-width="20"></span></div></td>'+
          '</tr>');
        },

P. s I'm sorry if there are errors in the text, I write it through google translate)

2
  • Please provide the HTML which this code is reading. Also, your code has more closing braces than opening, and docContragent is never used. Commented Jun 5, 2022 at 18:29
  • The HTML of the table is added dynamically, I edited the question Commented Jun 5, 2022 at 18:39

1 Answer 1

1

Your loop will fill your array with all items and at the end push array with all items on your json

let items = [];
let docDate;

for (var i = 1, row; row = table.rows[i]; i++) {
    if(row == document.querySelector('.add-elements')) {
      break;
    }
    docDate = document.querySelector('input[name="invoice-date"]').value
    let docContragent = document.querySelector('select').value
    // ITEMS
    let name = row.cells[1].querySelector('span').dataset.id
    let quantity = row.cells[2].querySelector('input').value
    let buy_price = row.cells[3].querySelector('input').value
    var sell_price = row.cells[5].querySelector('input').value

    items.push({
        "product": name,
        "buy_price": buy_price,
        "sell_price": sell_price,
        "quantity": quantity
    });
}

let invoice = {
    "doc_type": "capitalize",
    "date": docDate,
    "number": 98,
    "comment": "",
    "items": items
}
let json = JSON.stringify(invoice);
console.log(json)
Sign up to request clarification or add additional context in comments.

4 Comments

I pasted this into a function, now the console has this error on this line "items.append({": TypeError: undefined is not a function (near '...items.append...')
My bad in JS .append doesn't exist use : .push
I don't understand why this is also wrong: "TypeError: null is not an object (evaluating 'row.cells[2].querySelector('input').value')"
I managed to fix it, I edited your answer, thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.