Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 880
Mathlight Avatar asked Mar 27 '15 11:03

Mathlight


Video Answer


2 Answers

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.

like image 184
jcubic Avatar answered Oct 05 '22 14:10

jcubic


You can't. "An object" is a data structure that exists in memory and only makes sense to the program it is dealing with it.

You need to serialise the data (e.g. using the application/x-www-form-urlencoded format, or JSON, or XML, or a host of other choices) and send that instead.

If you are trying to send entire DOM elements (and it isn't clear what the data you are trying to send actually is) then serialising them would involve converting them to HTML or (and this would usually be the better option) a data structure that they represent.

like image 43
Quentin Avatar answered Oct 05 '22 14:10

Quentin