0

I am wanting to url encode a string with Javascript, with the relevant part of the code being:

this.options[this.selectedIndex].value

or the full line:

<select name="category" onChange="javascript:document.location.href='<? echo '/' . $state . '/dir/'; ?>' + this.options[this.selectedIndex].value;">

How can I url encode this with JS and then safely decode it with PHP using urldecode?

Brett
  • 19,449
  • 54
  • 157
  • 290
  • 1
    check this topic: http://stackoverflow.com/questions/332872/how-to-encode-a-url-in-javascript – Micer Dec 16 '12 at 16:44

2 Answers2

0

I had a problem when I wanted to use & in URL. I just solved it using encodeURIComponent().

I used it in onchange function of my dropdown element like this:

onchange="window.location='test.php?c='+encodeURIComponent(this.value)"

It works well in my case.

I tried to use php function urlencode() for this, but I couldn't do that.

Dominique
  • 16,450
  • 15
  • 56
  • 112
-1

You have 3 options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

Gustav Westling
  • 633
  • 3
  • 9
  • So how to encode html like for example `
    Coffe & Cake?
    Yes
    `, to pass into a URL with JS like for example `?list=
    Coffe & Cake?
    Yes
    `? And then receive it with PHP?
    – Jeroen Steen Aug 25 '22 at 18:04