0

I'm calling an API from an API provider that requires UTF-8 encoding of parameters.

I have used the js encodeURI and encodeURIComponent for that particular parameter. It does not work. Pls is there another way to do this?

This call is made via JavaScript that sends the UTF-8 encoded parameter value to a PHP script that requests from the API.

hakre
  • 193,403
  • 52
  • 435
  • 836
Blakjay116
  • 27
  • 4
  • Javascript uses UTF-8 as default, we maybe need more info to help with this one. eg. The text I'm typing here is utf-8, and is the reason I can show a or – Keith Jul 31 '23 at 20:56
  • Lets say I want to send “United Kingdom” as a query. The API expects it as “united%20kingdom” How do I get this – Blakjay116 Jul 31 '23 at 21:16
  • 1
    Well `encodeURIComponent` does that apart from the lowercase. So you could try -> `encodeURIComponent('United Kingdom').toLowerCase()` But it does seem odd that your API endpoint requires this, do you have more info on what the PHP endpoint looks like? – Keith Jul 31 '23 at 21:31
  • Add the example where you call the API in Javacript to the question, and for the PHP part the same (if you have it available), otherwise for the API specific requirements, e.g. an example request. You need to add more infos otherwise you invite to speculate and you will not have much fun with that. – hakre Jul 31 '23 at 21:34
  • Please clarify if the PHP is the API that is being requested by the Javascript (Browser?) or if it passes the parameters along requsting the API that is on a different endpoint? Better add and example to your question, it's really unclear. – hakre Jul 31 '23 at 21:36
  • 1
    To clarify, the API sounds like it expects URL-encoded UTF-8 data. Step one is to determine what encoding your source data uses. [This cannot be reliably detected, you must _know_.] Step two is to use [`mb_convert_encoding()`](https://www.php.net/manual/en/function.mb-convert-encoding) to change it to UTF-8 if necessary. Step three is [`urlencode()`](https://www.php.net/manual/en/function.urlencode). – Sammitch Jul 31 '23 at 21:49
  • thank you guys. Like Keith said, I had to call the toLowerCase on the already encoded string. thats ```encodeURIComponent(data).toLowerCase()``` – Blakjay116 Aug 01 '23 at 00:04

1 Answers1

1

I think your mean "URL Encode" not "UTF8 encode" since UTF8 is the default character encoding for JS.

Let me know if I'm mistaken.

Check this stack overflow post on url encoding

encodeURIComponent is probably what you want.

Justin
  • 945
  • 12
  • 26