Forum Moderators: open

Message Too Old, No Replies

Making input data URI-friendly with and without URLSearchParams .set

         

csdude55

9:49 pm on Nov 18, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a form with an input field. When the user clicks the Submit button, it first runs through this Javascript (abbreviated for readability, of course):

if (window.URLSearchParams) {
params = new URLSearchParams(location.search);
params.set('name', encodeURIComponent(document[formName].name.value));
}

else {
params = location.search.substring(1) + '&' +
'name=' + encodeURIComponent(document[formName].name.value)
}

console.log(params.toString());

When "name" includes a space (eg, "webmaster world") and window.URLSearchParams passes, it prints:

name=webmaster%2520world

So somewhere along the way, the whitespace is converted to %20 before it gets here.

If I remove encodeURIComponent(), though, it prints:

name=webmaster+world

That's great, I guess that .set does its own version of encoding? Cool.

But!

If window.URLSearchParams does not pass, it prints:

name=webmaster%20world

And if I remove encodeURIComponent() from here, it prints:

name=webmaster world

(leaving the whitespace unencoded)

What should I do to get them both to return the exact same thing?

At the end of the JS it just sends param as a GET request to a PHP script, and then PHP uses the params to select from MySQL (eg, sprintf("select col from table where name='%s' limit 1", mysqli_real_escape_string($dbh, $_GET['name'])); ) . Knowing that, does it really even matter if they're the same?

Fotiman

11:44 pm on Nov 18, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It shouldn't matter. In short, you don't need to encode URLSearchParams (it does it for you), but you do need to encode if you craft it manually. And + or %20 are both fine, so even though the end result may be slightly different, they are equivalent as far as the browser is concerned.