Getting data from fetch xhr call: encoding problem

hi all!

i’m experiencing what i think it’s an encoding problem from the kirby side:

i’m sending a some data through a form

<form id="newsletter" method="post">
  <input id="email" name="email" type="email" class="bd-b--main">
   <input type="submit" name="submit" class="submit" value="Send">

   <div class="honeypot">
     <input id="website" type="website" name="website">
  </div>
</form>

fetch the data and send it to a kirby api endpoint like this

function onsubmit (e) {
    e.preventDefault();
    var form = document.querySelector('form');
    var bot = document.querySelector('.honeypot');
    var formdata = new FormData(form);

    var body = {};
    formdata.forEach(function(value, key){
      body[key] = value;
    });

    console.log(body);

    if (formdata.get('website') !== '') {
      console.log('hallo bot');
    } else {
      fetch('api/newsletter', {
        method: 'POST',
        mode: "same-origin",
        headers: { 
          "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
      }).then(function (res) {
        res.json();
      }).then(function (resp) {
        console.log(resp);
      }).catch(function (error) {
        console.log('Error:', error);
      });
    }
    
  }

kirby api file

kirby()->routes([
      [
        'method' => 'POST',
        'pattern' => 'api/newsletter',
        'action' => function() {
          if(r::is('POST')) {
            $mc_data = r::data();
            
            // echo $mc_data = a:1:{s:47:"{"email":"work@andrefincato_info","website":""}";s:0:"";}
          }
        }
      ]
    ]);

am i over-encoding? if i try to decode i get nothing.

thanks for any hint!

Hi,
I think your route should be in the config.php and your function should be in the api or controller.
And you used the Kirby V3 routes for Kirby V2.

hey @JanStieler thanks for following up!

i used the same code in api.php for another kirby v2 website, and it’s working well. so i really think i am missing out some encoding parameters on the kirby receiving end, as in the other website im building the frontend in javascript and in this case it’s done in kirby.

OK, figured the problem I’m having is due to php / kirby converting the json string into an array and by doing so things go wrong.

Whether I use php’s json_decode() or kirby’s str::parse() I have the same output.

Which is a bit confusing, as if I don’t decode the json string, the data is correctly formatted.

OK, resolved this by changing the js function:

i am simply sending the formData object to kirby, to serialization into a json object and then stringifying it. As this last passage was most probably causing the encoding problem.

function onsubmit (e) {
    e.preventDefault();
    var form = document.querySelector('form');
    var bot = document.querySelector('.honeypot');
    var formdata = new FormData(form);

    var body = { };
    formdata.forEach(function(value, key){
      body[key] = value;
    });

    if (formdata.get('website') !== '') {
      console.log('hallo bot');
    } else {
      // new function (also replacing fetch() w/ old-style XMLHttpRequest())
      var xhr = new XMLHttpRequest();
      var url = 'api/newsletter';

      xhr.open('POST', url, true);
      xhr.onload = function () {
        console.log(this.responseText);
      };
      xhr.send(formdata);
      
    }
}