1

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.

2 Answers 2

1

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

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

2 Comments

Hello, after using this JSON.stringify my son is empty. Do you know why ?
@Testy did you use exactly this syntax? With square bracket and triple dots
1

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));

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.