Home > other >  Get URL paramater after page load
Get URL paramater after page load

Time:05-20

I use jquery to load a script.php file after loading my index.php page and I want to be able to retrieve the parameter of my URL in my script.php file but it doesn't work because the page is already loaded and it tells me

Undefined array key "query"

index.php :

 <div id="loader">
    $(window).on('load', function () {
        $('#loader').load('scripts.php');
    })

scripts.php :

    $current_url = $_SERVER['REQUEST_URI'];
    $parts = parse_url($current_url);
    parse_str($parts['query'], $query);
    $parameter = $query['q'];

URL example : https://example.com/search?q=test

Is there any way to get my parameter back after loading the page ?

thank you in advance

CodePudding user response:

You can pass arbitrary query string parameters to scripts.php, just like you would any other URL:

...load('scripts.php?q='   variable)

However there is no way for scripts.php to know what parameters were involved in the request to index.php.

You'd have to forward anything you're interested in making scripts.php aware of.

However, it's not really clear why you would do this. You typically shouldn't be assembling multiple related PHP pages on the frontend, over several HTTP requests. Rather, your PHP pages should just include the necessary related components, and serve up a complete document in a single request.

Instead of having index.php serve up some JavaScript that makes another round-trip request for scripts.php, forwarding details about the original request, why not just have index.php require( "scripts.php");, so that it is part of the original request?

CodePudding user response:

The HTTP request to scripts.php is a different HTTP request to the one make to the URL that returns the HTML document. It has a different URL.

If you want to copy the query string from the latter then you need to do so explicitly.

const q = new URLSearchParams(location.search);
const url = new URL("search.php", location);
[...q.entries()].forEach(
    ([key, value]) => url.searchParams.append(key, value)
);
$('#loader').load(url.toString());
  • Related