-2

In Javascript i encode parts of the request parameter like this

window.location.href = "search.php?qry=" + encodeURIComponent("m & l");

In my Search.php i reach this like this

$url = urldecode($_SERVER['REQUEST_URI']);
echo ."Full URL: " .$url ."<br>";
$parts = parse_url($url);
parse_str($parts['query'], $query);
$qry = "Just Query: " .trim($query['qry']);
echo $qry ."<br>";

This prints out:

Full Url: /Search.php?qry=m & l
Just Query: m

Looks like the stuff after the & is being dropped in the 'm & l`

What changes do i need to make in PHP or Javascript?

codeNinja
  • 1,442
  • 3
  • 25
  • 61
  • Can you give concrete example of your desired result? – 0xInfection Feb 09 '19 at 04:09
  • the `Just Query:` echo statement should have printed `Just Query: m & l` – codeNinja Feb 09 '19 at 04:14
  • 1
    You just asked [this question](https://stackoverflow.com/questions/54602850/encoding-url-in-javascript-not-encoding), shouldn't this have been an edit? – Jack Bashford Feb 09 '19 at 04:15
  • possibly, but i thought that one was about encoding and this one is about decoding. What help can i get with this please? – codeNinja Feb 09 '19 at 04:26
  • @Jack Bashford - I actually chose to answer because it seemed like a separate, but related question to me. I could also see why decoding the result separately and then passing that to `parse_url` might not behave the way the asker was expecting. – EPB Feb 09 '19 at 04:33

1 Answers1

3

Just change:

$url = urldecode($_SERVER['REQUEST_URI']);

to

$url = $_SERVER['REQUEST_URI'];

You're basically double-decoding as parse_url will decode it as well.

Worth noting that PHP has already done this for you so there's not really a reason to parse your own URL. $_GET['qry'] will contain 'm & l'

If you're doing this for several query variables, you'll need to run encodeURIComponent separately for each.

Example:

window.location.href = "search.php?qry=" + encodeURIComponent("m & l") + "&subcat="+encodeURIComponent("hello & there");

You're explicitly telling it to encode the & after all.

EPB
  • 3,939
  • 1
  • 24
  • 26
  • i tried the using the PHP way like you recommended. Works if i only have one paramenter in the url. But when i have two this is what happens. `$qry = trim($_GET['qry']);` `echo $qry ;` this prints out. `M & L&subcat=` so the second query param is being clubbed in – codeNinja Feb 09 '19 at 04:40
  • I added an edit for situations where you want to send several query variables. Since you'd be encoding the separator, you'll need to encode them separately. – EPB Feb 09 '19 at 04:52