1

On my website, I rewrote all my urls. But now I have started using AJAX for a voting functionality (it is a Q&A Community), there are some problems:

I am storing new UrlSearchParams(window.location.search) in a constant. Then I call the .get() method for this. However, because the urls are rewritten, it doesn't recognize the query.

const myParam = urlParams.get('id');

The url is www.example.com/Questions/7 rewritten from www.example.com/pages/question.php?id=7

My .htaccess file looks like this:

RewriteEngine On    # Turn on the rewriting engine
Options -MultiViews
RewriteRule ^$ /pages/index.php [L]
RewriteRule    ^users/([0-9]+)$    pages/profile.php?id=$1   [NC]    # Handle users
RewriteRule    ^questions/([0-9]+)$    pages/question.php?id=$1   [NC]    # Handle questions
RewriteRule    ^([A-Za-z_]+)$       pages/$1.php                    [NC]    # Handle pages
RewriteRule    ^([A-Za-z_]+)$       pages/$1.html                    [NC]    # Handle pages

How can one overcome the fact that UrlSearchParams will not recognize query string data when the url is rewritten?

Marvin
  • 853
  • 2
  • 14
  • 38
  • I used the .htaccess file in the root directory of localhost – Marvin Apr 13 '19 at 23:27
  • 2
    You would have to change it to match the new URL format by parsing `window.location.pathname` instead… or just pass it from PHP in the HTML somewhere, which is probably simpler and more flexible. – Ry- Apr 13 '19 at 23:32
  • If the URL is rewritten, you can't use the same code to get information from the URL. You need different code. In your case, `location.pathname.substring(location.pathname.lastIndexOf('/'))`... – Heretic Monkey Apr 13 '19 at 23:32
  • Alternative to parsing the pathname is passing a small object variable in a script tag – charlietfl Apr 13 '19 at 23:37
  • 1
    Pop this in your `` section ~ `` – Phil Apr 13 '19 at 23:39
  • @Phil this worked. Mind making it into an answer? – Marvin Apr 22 '19 at 00:34

1 Answers1

1

Your rewrite-rules all internal rewrites which means the client-side code can only see the original URL, ie /Questions/7.

Since your PHP runs server-side and can see the rewritten query parameters, you can directly inject them as JS variables for your client-side code to use.

For example, put this in your <head> section...

<script>
const ID_PARAM = <?= json_encode($_GET['id'] ?? null) ?>;
</script>
Phil
  • 157,677
  • 23
  • 242
  • 245