Search code examples
javascriptquery-stringquerystringparameter

UrlSearchParams.get() doesn't work with rewritten urls


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?


Solution

  • 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>