Search code examples
javascriptpostxmlhttprequest

XMLHttpRequest send JS Object


I'm trying to send an JS Object with an (POST) XMLHttpRequest, but I get no POST data in PHP.

This code worked before with an Ajax request, but i'm trying to get feedback from the server for an progressbar ( whitch is working fine now). That's why i've chagend to XMLHttpRequest.

The code:

var dataRows = {
    'bewaarnaam': bewaarNaam,
    rows: {}
};

$(".rows").each(function (i, obj) {
    var row = $(obj);
    var rowName = $(row).attr('name');
    var chests = {};

    $(".cv_chest", row).each(function (i2, obj2) {
        chests[$(obj2).attr('id')] = {
            'counter': $(obj2).attr('chest_counter'),
                'height': $(obj2).attr('chest_height'),
                'db_id': $(obj2).attr('db_id')
        };
    });

    var top = $(row).css('top').replace("px", "");
    var left = $(row).css('left').replace("px", "");

    var rowData = {
        'name': $(row).attr('name'),
            'x': parseInt(left),
            'y': (parseInt(top - 100)),
            'rotation': rotation[$(row).attr('dir')],
            'db_id': $(row).attr("db_id"),
            'chests': chests
    };

    dataRows.rows[$(row).attr('id')] = rowData;
});

...

var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url('bewaarplaatsen/xhrTest/') }}", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(dataRows);

So my question is rather simple... How can i send an object with an post through the XmlHttpRequest function?


Solution

  • Use JSON:

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "{{ url('bewaarplaatsen/xhrTest/') }}", true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.send(JSON.stringify(dataRows));
    

    EDIT:

    You can also use newer fetch API, see Fetch: POST JSON data.