0

I'm populating the src attribute of an image dynamically with the following code:

function getLocalUrl(item) {
    if (item.item_id != null && item.item_id != "") {
        return host + "images/" + item.item_tid + "-" + item.item_id + ".jpg";
    } else {
        return host + "images/temp/" + item.item_tid + ".jpg";
    }
}
... 
var cont = "<img class=\"image image-large\" src=\"" + getLocalUrl(item) + "\"/>";
$(element).append(cont);

However when I look at the http requests that my browser makes I see two of them: the first one to

/images/undefined-1.jpg

and the second one to

/images/correctstring-1.jpg

Of course the first one produces an error but the second one downloads the images correctly so the end result is correct. But I still don't understand why the first request is made. The function getLocalUrl is only called once and the item_tid field is always defined (otherwise the second request wouldn't be produced). I'm a bit of a newbie so I might be missing something very basic.

splinter123
  • 1,101
  • 1
  • 9
  • 27
  • 2
    Can we have an example of `item` please ? – Magicprog.fr Nov 20 '15 at 12:02
  • 6
    You should also check `item.item_tid` because is that what's undefined. – ojovirtual Nov 20 '15 at 12:02
  • Remember that in JS `null` and `undefined` is not the same. You can find more info [here](http://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript) – Adrian Menendez Nov 20 '15 at 12:07
  • Considering the code you've posted appears to work exactly as expected for the correctstring example, and you say that `getLocalUrl` is called only once, have you considered looking elsewhere in the code for things that append `` tags? I mean, based on the information given, there's no reason to suspect the code shown is faulty (even if it does fail to check the values). You could put a `console.log` line into the function if you want to check. – Chris Lear Nov 20 '15 at 12:24
  • So, splinter, does either of the answers answer your question? – Cerbrus Nov 20 '15 at 14:58

2 Answers2

0

Replace:

if (item.item_id != null && item.item_id != "") {

With:

if (item.item_id != null && item.item_id != "" && item.item_tid) {

Or, shorter:

if (item.item_id && item.item_tid) {

You weren't checking for item_tid being undefined.


However, this will result in return host + "images/temp/" + item.item_tid + ".jpg"; being used. Since item_tid is undefined, you're still not getting the result you want.

The problem is that, if item_tid is undefined, you can't build an url based on that.

Cerbrus
  • 60,471
  • 15
  • 115
  • 132
0

Check if item.item_tid is undefined, since seeing from your code item.item_tid is undefined.

Change

if (item.item_id != null && item.item_id != "") {

with

if (item.item_id && item.item_tid) {
Joshua Bakker
  • 1,831
  • 2
  • 22
  • 52