1

How would I use XMLHttpRequest if I need to send some parameters that might contain '&' sign (without knowing which one or if any might contain it). Of course if there is an '&' sing it will break parameters on receiving end.

Is there a way to do this without using encodeURIComponent?

Normally I would do this:

        var params = 'action='+foo+'&token='+bla+';

        xhrRequest = new XMLHttpRequest();
        xhrRequest.onreadystatechange = function() {
            if (xhrRequest.readyState == 4) {

                
            }
        }
        xhrRequest.onerror = function(e) { 
           
        };
        xhrRequest.open('POST', url);
        xhrRequest.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
        xhrRequest.send(params);
Toniq
  • 4,492
  • 12
  • 50
  • 109
  • 1
    Does this answer your question? [Escaping ampersand in URL](https://stackoverflow.com/questions/16622504/escaping-ampersand-in-url) – Dhana D. Mar 13 '23 at 09:18
  • 1
    "Is there a way to do this without using encodeURIComponent?" — This doesn't seem like a reasonable requirement. (Admittedly, `encodeURIComponent` isn't a great way of doing it today, but it would solve the problem and you are rejecting it without explanation.) – Quentin Mar 13 '23 at 09:27

1 Answers1

-1

Don't try to generate application/x-www-form-urlencoded data by mashing strings together.

Use the URLSearchParams API. It will escape characters with special meaning.

XHR can also infer the correct content-type from it, so you don't need to specify it manually.

const params = new URLSearchParams();
params.append("action", foo);
params.append("token", bla);

const xhrRequest = new XMLHttpRequest();
xhrRequest.onload = function(e) {
}
xhrRequest.onerror = function(e) { 
};
xhrRequest.open('POST', url);
xhrRequest.send(params);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • When I receive these parameters do I need to use rawurldecode? – Toniq Mar 13 '23 at 10:40
  • @Toniq — What is `rawurldecode`? Are you asking a PHP question now? If you are, then you should [ask a new question](https://stackoverflow.com/questions/ask) showing your attempt as a [mcve]. (And I wouldn't expect rawurldecode to be used, but a really weird approach to reading the request body might demand it). – Quentin Mar 13 '23 at 10:43
  • Yes, a simple javascript post to php. I wasnt using rawurldecode so far, just $action= $_REQUEST['action']; – Toniq Mar 13 '23 at 12:08
  • Have you tried it? (Note that `$_REQUEST` is generally best avoided as it merged `$_COOKIES`, `$_GET` and `$_POST` which makes things (including security) harder to manage). – Quentin Mar 13 '23 at 12:11
  • So I should use $_POST? – Toniq Mar 13 '23 at 13:04
  • Generally, yes. – Quentin Mar 13 '23 at 14:00