将映射数组传递给PHP页面

For my project, I'm using this:

var arr = new Map(); to create a map with JS.

After each click on elements, I'm using this to populate the map.

arr.set(roomid + '_' + date, {
    status: updatedStatus,
    date: date,
    roomid: roomid
});

After few clicks, on the console panel, I have:

[Log] Map {"48_2019-03-09" => {status: "Open", date: "2019-03-09", roomid: 48}, "48_2019-03-19" => {status: "Open", date: "2019-03-19", roomid: 48}} (2) (app.js, line 93)

So, this is what I want.

Now I need to pass this datas to PHP via Ajax like this:

$.ajax({
    type: 'POST',
    data: { datas: arr },
    url  : 'update.php',
    success: function(responseText){
        ...
    }
});

On my PHP page, I have the following code:

$arr = $_POST;
print_r($arr);

But this code output:

Array
(
)

But this doesn't work because my PHP page print an empty array.

What I'm doing wrong please ?

Thanks.

Ajax expects an object, not a Map. So you need to convert your Map to an object before passing it to the ajax request.

function mapToObject(map) {
  var obj= {}
  map.forEach(function(value, key) {
      obj[key] = value
  }
  return obj
}

....

$.ajax({
    type: 'POST',
    data: { datas: mapToObject(arr) },
    url  : 'update.php',
    success: function(responseText){
        ...
    }
});

EDIT: just noticed, if you need to pass a full JS object to PHP you need to convert it to JSON.

So the real ajax call should be:

$.ajax({
    type: 'POST',
    data: JSON.stringify({ datas: mapToObject(arr) }),
    url  : 'update.php',
    success: function(responseText){
        ...
    }
});

and on your server:

$data = file_get_contents("php://input");
print_r(json_decode($data, true));

you need to convert the map to a json object. Easiest way I know to do this is to stringify and then parse to a JSON object.

JSON.parse(JSON.stringify([...arr]))

$.ajax({
    type: 'POST',
    data: { datas: JSON.parse(JSON.stringify([...arr])) },
    url  : 'update.php',
    success: function(responseText){
        ...
    }
});

Ref: http://2ality.com/2015/08/es6-map-json.html