1

I have a node.js + pug application stack. I can send a delete request, but have problem with put/post request with body. My pug table looks like this

    table.table.table-striped.text-center
        each order in orders
            tr
                td #{order.id}
                td #{moment(order.date).format('DD.MM.yyyy hh:mm:ss')}
                td #{order.total_price} €
                td
                    button.btn.btn-success(onClick="archiveOrder(" + order + ")")
                        i.fa.fa-archive
                td
                    button.btn.btn-danger(onClick="deleteOrder(" + order.id + ")")
                        i.fa.fa-trash-o
        else
            tr
                td(colspan=7) There are no items

I included a script file in pug that has this content:

function deleteOrder(id) {
    $.ajax({
        type: "DELETE",
        url: "/orders/" + id,
        success: function () {
            location.reload()
        }
    });
}

function archiveOrder(order) {
    order.archived = true;
    $.ajax({
        type: "PUT",
        contentType: 'application/json',
        dataType: 'json',
        url: "/orders/" + order.id,
        data: JSON.stringify(order),
        success: function () {
            location.reload()
        }
    });
}

Renders ok, delete works fine. How can I send the order I want to archive in the javascript function? I tried onClick="archiveOrder(" + order + ")" and onClick="archiveOrder(#{order})" The first one generates

<button class="btn btn-success" onClick="archiveOrder([object Object])" title="Archive order = hide from list">
  <i class="fa fa-archive"></i>
</button>

Logicaly it fails with Uncaught SyntaxError: Unexpected identifier because of [object Object] string i think.

The second attempt result in orders:23 Uncaught SyntaxError: Invalid or unexpected token

How could I send the object order from pug's loop into the rest endpoint?

1 Answer 1

1

HTML can't render the object. So you can turn the object into a sting with JSON.stringify()

button.btn.btn-success(onClick="archiveOrder(" + JSON.stringify(order) + ")")

You will see a JSON string in your markup. The opposite is JSON.parse() to parse it back into an object.

Sign up to request clarification or add additional context in comments.

Comments

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.