1

"Appending an url with appendages that were already in the previous url?" That's the most confusing title -- I know. But I can't think of a better way to explain it.

Maybe the below example will help.

I have URL 1: http://example.com/?value=xyz&stuff=abc

If someone clicks on a link within the page, can I pass along the appended values?

ie: http://www.example.org/?value=xyz&stuff=abc

Thanks and sorry for being such a noob.

3
  • How this link is built? With JavaScript or PHP? Commented Sep 17, 2012 at 23:48
  • 1
    Where's your code. Have you tried anything yet? Commented Sep 17, 2012 at 23:50
  • What do you mean pass it along? Do you want it in the URL? In PHP, that information is in $_SERVER['QUERY_STRING'] Commented Sep 17, 2012 at 23:52

3 Answers 3

7

These appendages you ask about is the actual so called query part of an URI:

<scheme>://<authority><path>?<query>

  foo://example.com:8042/over/there?name=ferret#nose
  \_/   \______________/\_________/ \_________/ \__/
   |           |            |            |        |
scheme     authority       path        query   fragment

Taken from: 3. Syntax Components (RFC 3986) https://www.rfc-editor.org/rfc/rfc3986#page-16

You then need a helper function that is append the (optional) <query> to an existing <scheme>://<authority><path> part. I ignore the <fragment> for this exmaple, as it would needed to be added at the end and I want to leave something as an exercise:

function href_append_query($href)
{
    $query = isset($_SERVER['QUERY_STRING'])
        ? '?' . $_SERVER['QUERY_STRING']
        : ''
    ;

    $query = strtr(
        $query, [
            '"' => '&quot;',
            "'" => '&#39;',
            '&' => '&amp;'
        ]
    );

    return $href . $query;
}

And it's usage:

<a href="<?=href_append_query('http://step2.com/')?>Some link</a>

This little function will ensure that the exisitng QUERY_STRING which can be obtained via $_SERVERDocs is encoded for HTML output.

Sign up to request clarification or add additional context in comments.

Comments

3

If links are built with PHP, just append the original query string to them:

<a href="http://step2.com/?<?php echo $_SERVER['QUERY_STRING']; ?>">Some link</a>

In JavaScript, just append the value of window.location.search to all the links you need to 'pass' the query string.

Comments

0

You could also use js/jquery to append the existing query string to each link on the page:

 $(function() {
    $('a').each(function() {
      link = $(this).attr('href');
      query = window.location.search;
      if (link.indexOf('?') !== -1 && query !== '') {
        query = query.replace('?','&');
      }
      $(this).attr('href',link+query);
    });
  });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.