tzkmx
6/27/2018 - 8:18 PM

Mithril request formats and PHP server side receive

Mithril request formats and PHP server side receive

The problem

By default, mithril sends data serialized in JSON, however some people prefer receive the data like it was sent through a form, i.e. $_POST & $_GET in PHP

The solution(s)

  1. Change your server side script in order to receive JSON serialized data
  2. Change the way mithril sends data through the m.request serialize option

Notes

Source

https://github.com/MithrilJS/mithril.js/issues/635#issuecomment-107375862

The data you send is irrelevant to the problem, for this simple gist, you could test with a data as simple as this:

const requestData = {
  user: 'username',
  pass: 'password'
}
// Default for mithril is JSON format over the network
m.request({
  url: './script-json.php',
  method: 'POST',
  data: requestData
})
  .then(console.log)
  .catch(console.warn)
// changing the headers and with a custom serialize function
// you send the data more friendly with legacy PHP scripts

m.request({
  url: './script-urlencoded.php',
  method: 'POST',
  data: requestData,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  serialize: function(data) {
    return m.buildQueryString(data)
  },
})
  .then(console.log)
  .catch(console.warn)
<?php
// Change your script to decode the input in JSON in the body

$input = file_get_contents('php://input');
error_log('input: ' . var_export($input, true), 0);
$requestData = json_decode($input, true);
<?php
// The you could use the data received in $_REQUEST ($_POST || $_GET)
error_log(var_export($_REQUEST, true), 0);