1

The context

I'm building a save/load system for an email template builder based on grapesjs-mjml. I'm saving my MJML code in a BDD (MySQL).

My current code

I'm sending my template name and my template MJML code through an ajax call which look like that

let params = "name="+template_name + "&html="+template_mjml;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "save.php", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // doing stuffs when it's saved
  }
};
xhttp.send(params);

and on the server side, I'm catching the html value with a standard $_POST['html']

My issue

Sometimes, there is urls inside my html param (it could be links for example). And inside those urls, there is some & which means my $_POST['html'] is not reading the whole param: it's stopping right before the first & of my html code

My dirty solution

On my client side, I added a html = html.replaceAll('&','//amp;') and I'm doing the reverse function on the server side. Which that, I'm getting rid of all & in my 'html' param, but it's not very nice...

I would like to know if one of you know a better/nicer solution to do that ?

Pof
  • 829
  • 5
  • 20
  • See the linked question's answers. You *always* have to encode URI values, for instance with `encodeURIComponent`. In fact, keys need to be encoded too, but if you know the key doesn't have any characters that encoding will change (`name` and `html` don't, for instance), you can skip it. – T.J. Crowder Apr 07 '21 at 13:00
  • Encode and decode your data before and after the request. Encode it on your ajax call using `encodeURI()` and decide in php using `htmlspecialchars_decode()` – Beshambher Chaukhwan Apr 07 '21 at 13:02

1 Answers1

0

You should use encodeURIComponent(). This will properly encode special characters.

let params = "name=" + encodeURIComponent(template_name) + "&html=" + encodeURIComponent(template_mjml);
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Hum... I already tried that and it was not working and now it works... Thank you for your answer ! – Pof Apr 07 '21 at 13:33