2

How to collect variables from a URL, insert them into an array and dynamically change a href URLs?

I'm not a developer so please be easy on me here! I am familiar with HTML and not bad at taking snippets of code from various sources and cobbling them together. This is the first time, I've ever decided to reach out for help on a blog like this because I've been looking around and just can't seem to find exactly what I need. Very close and yet so far.. Please help!

What I want to do is:

  1. collect variables from the URL like this (wwww.myurl.com/index.html?var1=1&var2=2&var3=3 etc. etc..)

  2. Take those variables and insert them into an array while stripping out the un-needed parts. I found this code which gets it but prints it on the screen, which I don't need..

    myurl.com/index.html?log=1&pass=2
    

    function addComment()
    {
        var parameters = location.search.substring(1).split("&");
    
        var temp = parameters[0].split("=");
        l = unescape(temp[1]);
    
        temp = parameters[1].split("=");
        c = unescape(temp[1]);
    
        document.getElementById("log").innerHTML = l;
        document.getElementById("pass").innerHTML = c;
    }
    addComment();
    
    
    <p>http://www.myurl.com/</b><span id="log" ></span></p>
    <p>http://www.myurl.com/</b><span id="pass"></span></p>
    
    </script>
    
  3. Dynamically alter a href tags on the fly based on the parameters gathered from the URL.

I found this code which works great to alter the URLs but (a) the variable is gathered from an input form and I need to be able to take them from the URL. (b) I also need several of them (could be like 20) so an array is needed.

<input type="text" id="mySearchBox" />
<a href="http://www.myurl.com/index.html?" onclick="this.href+=+document.getElementById('mySearchBox').value">Enter Parameter</a>

(edited code format)


Regarding the technology... I'm not stuck on any particular language or method but javascript and the jquery seems to be the easiest for me. I haven't done much with PHP and other languages. The easiest method for dummies you can provide the better.

I'm sure this is like elementary school stuff to you out there but I just can't seem to figure it out so your advice is much appreciated!

3
  • The blog stripped out some of the code that I pasted in here so it is missing. Hopefully the description I provided will be enough to respond to. If not, I'll figure out how to paste it in here with the brackets to get it to be displayed... Commented Sep 16, 2012 at 22:29
  • Just pasted it, there are editors who will format it. Commented Sep 16, 2012 at 22:35
  • Thank you. Can you add this part too? It was the part where it says "Enter Parameter".. <input type="text" id="mySearchBox" /> <a href="myurl.com/index.html?" onclick="this.href+=+document.getElementById('mySearchBox').value">Enter Parameter</a> Commented Sep 17, 2012 at 3:02

2 Answers 2

1

Javascript & jQuery

The first line of the addComment function gets the searchsrtring from the url, wich is everething from (and with) the ? up to (and without) the hash (#) or the end if there is no hash.

After that the first character (?) is removed with substr(1). Finally the string is split at every "&" with .split("&"). All the splited parts are stored in an array. Applying this on an example:

www.myurl.com/index.html?var1=1&var2=2&var3=3

Becomes

["var1=1", "var2=2", "var3=3"]

this array is stored in the variable parameters. Next the first element of the array is splitted at the "=" character. We get

temp = ["var1", "1"]

the second element of temp is unescaped ( to decode special characters from the url like %20 to " " (space) )

To create an object of that, first create an empty object and then fill it like this:

var obj = {};

obj[ temp[0] ] = temp[1];

Doing this on a for loop with all the elements from parameters will get you:

obj = { var1 : 1, var2 : 2, var3 : 3 }

The object that you wanted. This is a very simple parser and may not work properly for more complex values. This is the full code described above:

function getUrlObj() {
  var parameters = location.search.substring(1).split("&");
  var obj = {};
  for( var i = 0; i < parameters.length; ++i) {
    var tmp = parameters[i].split("=");
    obj[ tmp[0] ] = unescape( tmp[1] );
  }
  return obj
}

now to the links:

with your example the onclick event of the link decides which url is loaded. Like this the status bar of the browser will not show the correct destination which is more difficult to debug and less user friendly. A different approach (with jQuery) would be to collect all links from the page and change their href tags according to the url. This can be done after the page (or better the DOM) has been loaded. a jquery example may look like this:

$( function() { //called when dom is ready
  //get url object
  var urlObj = getUrlObj();
  //find all <a> elements on page
  // iterate over elements
  $('a').each(function() {
    // change attribute href
    $(this).attr('href', 'new url goes here');
  });
});

I guess you want to insert some parts of the url object in the new url. what is the initial value of the href attribute? what should it look like in the end?

The initial value may indicate how the url must be changed. The value of an attribute can be accessed with the method .attr('href') in jquery (a second argument would change the value).

a detailed explanation of the .attr() method (and others) can be found in the jquery documentation: http://api.jquery.com/attr/

if you don't want to change all the link elements you may apply a class to the links you want to modify like:

<a class="modify" href...

and then acces those elements with $('.modify') (with dot) instead of $('a').

PHP

If you want to do it with php the code might be a lot simpler because php can handle the url querystring natively. Example:

<a href="<?php echo $_GET["var1"]; ?>.php">link</a>

will result in a link to "1.php" with your example.

UPDATE: (according to the discussion in the comments)

The search query ?iframe1=1&banner1=1&button1=1&button2=2&button3=3 is sent to the server along with the url. PHP can access the values of the search query directly via the magic variable $_GET as pointed out above. $_GET['button1'] will be 1.

To use the variable the file ending has to be .php so the server knows that the contents of the file have to be evaluated. The resulting file will be a normal html file (with php ending).

writing <?php indicates that the following text up to ?> is php code. echo "something"; will print the string something into the resulting html file. A shortcut for printing something to the document is <?="text" ?>. Instead of a string a variable can be printed: <?=$somevar ?>.

Applying this to the example the html file has to updated something like this:

<a target="theiframe" href="www.mysite.com/redirect2external?<?=$_GET['button1'] ?>">a link</a>
<a target="theiframe" href="www.mysite.com/redirect2external?<?=$_GET['button2'] ?>">another link</a>

and so on. Same for the iframe (or the banner):

<iframe name="theiframe" src="www.mysite.com/redirect2external?<?=$_GET['iframe1'] ?>"/>

Another (better) way of combining all the html files into one php file would be to have a number or a string that represents a page. e.g. ?page=somepage (try to avoid special characters and spaces, they might not work properly).

In the php file there will then be a switch for all the pages:

<?php if( $_GET['page'] == "somepage" ) { ?>
  <a target="theiframe" href="www.mysite.com/redirect2external?1">a link</a>
  <a target="theiframe" href="www.mysite.com/redirect2external?2">another link</a>
<?php } elseif( $_GET['page'] == "someotherpage" ) { ?>
  <a target="theiframe" href="www.mysite.com/redirect2external?3">a link</a>
  <a target="theiframe" href="www.mysite.com/redirect2external?4">another link</a>
<?php } //and so on (btw this is a php comment) ?>

The advantages of that approach are:

  1. a shorter url
  2. in the first approach, if a new button is added later you would have to change all the links to that page, adding a buttonx=x in the url. also the additional button would not work if someone uses a bookmark (with the old url) to navigate to that site.
Sign up to request clarification or add additional context in comments.

18 Comments

Thank you for your detailed reply! Love the "pascalfree" UN. LOL :) I'll take it for a spin in a while after my day j.o.b. and let you know how it goes. Looks promising and I really appreciate the explanation. I lied.. should have said 25yrs+ :D
Ok. I had a chance to read through this. That was very helpful to gather the variables. Now I'm left hanging with getting them into those <a> tags. I'm not exactly sure what you mean about how to populate the red parts and my feeble brain can't fill in the dots here. PHP sounds like an option but the site is all built in JS and I'm wondering whether that would clash.
I hate to request to be spoon fed here but need a little more help to get to the correct syntax for: 1. <a href="www.myurl.com/index.html?"+'var1'>link1</a> resulting in the a tag hyperlink www.myurl.com/index.html?2 ... or the addition of the <img src="./images/.."> tag so I can link an image to that dynamic URL 2. <iframe src="www.myurl.com/index.html?"+'var2'></iframe> resulting in the iframe opening for www.myurl.com/index.html?2
To provide context, this is an example of the type of page I am working on doxietalk.com/doxiecalendars.html The 3 dynamic objects are: 1. The banner (which will change per breed) 2. The black buttons (all of the URLs are the same. The only thing that changes is the last digits after the "=" (node=x)). 3. The iFrame on the bottom. Same syntax as the 2nd URL
The goal is that I only create 1 page and just tweak the variables in the URL to make the topic of the page anything I want. Currently, I need to make separate pages for every breed and type which is a pain. Again, my apologies for being thick here! Thank you..
|
1

Great jQuery plugin for reading and modification of query strings: http://archive.plugins.jquery.com/project/query-object

Just use it to get job done or examine it's source to get answer to your question.

1 Comment

Thank you for your reply. I just had a quick look at that site and it does look informative. I will read up on it but was hoping to have someone either fix what I have so far or provide the best approach. Over time, I will try to brush up on my skills but the boat to being a developer sailed off about 20 years ago when I used to know Fortran, Pascal, and Basic. lol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.