3

So, I really need some help. I've done extensive searches, and some of the solutions I've found are great but aren't working for me, so here goes...

When someone comes to my site, they are going to click on a link which will pass a URL to "recipes.html"... For Example, if they clicked on "Ancho Chile Sauce", the URL would be:

blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

This parameter is actually the name of a JPEG in the folder "Recipes", of course with the ".jpg" extension

I need to take this parameter into a string and add "Recipes/" before it and ".jpg" after it, and then alter the source of an image tag in my html document to display the new dynamically called recipe image.

I thought I'd done this, but nothing seems to be working. There's obviously something I'm doing wrong in my Javascript, because my markup works fine and the url with parameter is getting passed.

Here is my code:

<!DOCTYPE html>
<html>
<head>
<title>Recipes</title>
<link href="mobi-styles.css" rel="stylesheet" />
<script type="text/javascript">
function getParam ( sname )
{
  var params = location.search.substr(location.search.indexOf("?")+1);
  var sval = "";
  params = params.split("&");
    // split param and value into individual pieces
    for (var i=0; i<params.length; i++)
       {
         temp = params[i].split("=");
         if ( [temp[0]] == sname ) { sval = temp[1]; }
       }
  return sval;
}
window.onload = changePic();
var param = getParam("r");
var recipeName = "Recipes/"+param+".jpg";
function changePic() {
document.getElementById("recipe").src=recipeName;
}
</script>
</head>

<body>
<img class"resizer" id="recipe" src="" />
</body>
</html>

Please help! Me love you long time!

1
  • what is the problem? Is there any error? Try to hardcode into the "src" attribute of your "recipe" image putting inside an extract of "recipeName" Commented May 15, 2012 at 22:13

5 Answers 5

6

remove the (). When attaching events, you assign a function, not the result of a function call. What you did was call changePic(), returned sval and assigned the value of sval to window.onload - that's wrong.

window.onload = changePic;
                         ^---remove ()

And move window.onload = changePic at the bottom so JSLint won't be mad. It's best practice to declare functions up top before using them, even when there is hoisting.

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

2 Comments

Holy s---!!! This did it! Thank you so much! I've been working on this function for 5 hours... Hard to believe it was something so simple... Can you tell I'm still a noob at programming? Ha!
@Spartacus every knowledgeable person started out as a noob at some point :D
3

I have written a little script that gives me access to the url paramater in the past and it can be very effective. it runs in the beginning of the file so you can access them anytime.

GET = (function () {
    var get = {
        push:function (key,value){
            var cur = this[key];
            if (cur.isArray){
                this[key].push(value);
            }else {
                this[key] = [];
                this[key].push(cur);
                this[key].push(value);
            }
        }
    },
    search = document.location.search,
    decode = function (s,boo) {
        var a = decodeURIComponent(s.split("+").join(" "));
        return boo? a.replace(/\s+/g,''):a;
    };
    search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function (a,b,c) {
        if (get[decode(b,true)]){
            get.push(decode(b,true),decode(c));
        }else {
            get[decode(b,true)] = decode(c);
        }
    });
    return get;
})();

Now you can access the parameters you want:

blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

GET['r']; // will print: Ancho-Chile-Sauce

or

GET.r; 

if the parameter are repeated multiple times then it is stored as an array;

example.com/test?name=John&name=Smith

the name property becomes an array

GET.name[1] ; // Smith

I hope this can help you

1 Comment

Super, just change regexpt to /\??(?:([^=&]+)=?([^&]*)&?)/g so it also accept empty values without =
1

Change this:

if ( [temp[0]] == sname ) { sval = temp[1]; }

To this:

if ( temp[0] == sname ) { sval = temp[1]; }

Comments

1

This is what I use to collect URL variables:

JQUERY EXTENSION

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

And you can use it like this:

// blahblahblah.com/recipes.html?r=Ancho-Chile-Sauce

var r = $.getUrlVar('r');

alert(r); // outputs 'Ancho-Chile-Sauce'

function changePic() {
  $('#recipe').attr("src", r);
}

If you don't use Jquery, a Javascript only solution would be:

function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

And can be used like this:

var r = getQueryVariable("r");

alert(r); // outputs 'Ancho-Chile-Sauce'

function changePic() {
  document.getElementById("recipe").src = r;
}

2 Comments

Should I just replace all of my existing function? And then how would I use the output in my document.getElementByID????
Just edited both options to show how you can pass the r value to the src of #recipe.
0
parseURLparameters(string) {
    let parsed = {};
    (string.split('?')[1] || string).split('&')
                                    .map((item) => {
                                        return item.split('=');
                                    })
                                    .forEach((item) => {
                                        parsed[item[0]] = item[1];
                                    });
    return parsed;
}

So you can pass an any string:

'?asd'
'?asd=123'
'asd=&kjnwer=13'

and so on...

Comments

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.