Get image SRC from javascript function

I'm creating a datagrid which may have an image. The image SRCs are constructed in SQL and passed to the calling class, and can be one of several images. These will not ever change, nor be removed, and no others will be added.
Here's my dilema...

We are now using DotNetNuke 3.1, which has URL rewriting and this kind of interferes with the image path because the path is relative to the current page on the client.

     <img src='images/image.jpg'>

In DotNetNuke a user may navigate to page http://sitename/datagrid/tabid/100/Default.aspx where the actual path is at http://sitename

What I thought about doing was modifying the function returning the image path to return either a variable or function that would refer to some javascript on the page and determine its image path that way.


     <script language=javascript>
          function getImage1()
               //baseDir is variable for root path
               return baseDir + '/images/image.jpg';
     <image src='javascript:getImage1()'>

I tried this on my own, but was not having any luck. Would anybody know how to do this?
I do not want to set the SRC of the object in javascript by calling on each image object. Images are dynamic and not determined until runtime.
I want to have the SRC of the object to call on its location from a variable or a function.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZvonkoSystems architectCommented:
Did you try with paths relative to web server root:

<img src='/images/image.jpg'>

Andrew BeersTechnology LeadCommented:
Yes, you would want to give each image an id of the image you would want to get and then you add a body onload="getImage1();" to call a function.

From there you are going to have a document.getElementsByTagName("img) assigned to a variable:

it is implimented like this:


      <script type="text/javascript">
            function getImage1(){
                  var imgs = document.getElementsByTagName("img");
                  for(i = 0; i < imgs.length; i++){
                        imgs[i].src = prefixPath +"/"+(imgs[i].id);


<body onload="getImage1();">

      <img src="" id="name.jpg">



If you need any further help feel free to ask.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Andrew BeersTechnology LeadCommented:
By the way your prefixPath is the same as your baseDir.  You can possibly do it with the src trick as well using src="javascript: getImage1()" but the method I gave you will work the best more than likely.

Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

jeremypettitAuthor Commented:
Zvonko, yes, this path is relative to the server, but the web site being viewed may not be from the root.

Aqua, If I'm going to iterate through the controls and set the images, then I need to step through the recordset as well. Currently, the links are created/determined from SQL via a User Defined Function.

I finally got this to work with <image src='javascript:getImage1()'>, but it will not work as a returned variable, so here's what I did.

<script language=javascript type=text/javascript>
function getImage1(imgName)
      document.getElementById(imgName).src = baseDir + '/images/image.jpg';


<a href=open2.htm><img id=image2 src="javascript:getCamera('image2')"><a>

This way, I can create the ID and pass it when it goes to retrieve the SRC. No need to iterate through the images.
What I can also do is pass another parameter for which image to display.
ZvonkoSystems architectCommented:
Check this:
var baseDir = '/some/path/';

<a href=open2.htm><img name=image2 src="javascript:document.images.image2.src=baseDir+'image2.jpg';"><a>

Or together with your serever side script:

<a href=open2.htm><img name=image2 src="javascript:document.images.image2.src=baseDir+'image<% =SomeValue %>.jpg';"><a>

Andrew BeersTechnology LeadCommented:
Either way your doing the javascript:  so you are essentialy iterating through the images... either way.

Though Zvonko points out that you can just put the image name using the server side script... which I didn't even think of posting.

Andrew BeersTechnology LeadCommented:
Another side note:

Using the src="javascript:.." call will load after your page finishes loading... so each function call will be delayed until the prior loads while doing it with body onload="..." executes as soon as the source reaches the browser and then all your images will get pulled in at the same time rather than one at a time.

Just a side note.

You'd probabally be best to use the src=<%= (baseDir + someValueFromDB) %> than using client side js to parse this.

jeremypettitAuthor Commented:
Zvonko, your way works just as mine did with the call of the function, but then that string will be retrieved from SQL for every record and sent to the client. By using a method/function call, less text is passed through.

Aqua, this method does not iterate/loop through each control through javascript. This method allows the method/function to be dumb and not know what the IDs are of the images.
Also, the image paths are determined from the database server and not through code in the application, so the server side tags will do nothing unless I'd modify on render or on bind of the datagrid. That method would require more code and more work. Very little code can be added to this so not to affect the existing classes. This is why I needed it to be called through the use of a function or variable. Now all I have to do is modify a SQL function and add a function to the header.

The above method will work the same as each image does in normal html in that the path is determined on load.
ZvonkoSystems architectCommented:
When I have understood your requirments, then you can build a JavaScript Array with the variable parts of the image paths and reuse them by the functions called from the img tags.
And from my point of view are the script lines on the page evaluated and executed in the order of their occurance on the page. Just for that problem is the body onLoad event handler to ensure that ALL page elements and external files, like images, applets annd other external stuff has completed loading before executing the onLoad handler.
Therefore you can use beside every img tag the apropriate call to start loading the just rendered img tag with the appropriate src from the header array values choosen by the called function and assigning to the image name as passed by the calling script statement parameter.
Andrew BeersTechnology LeadCommented:
What I do not understand is you keep saying you would have to parse through the entire record set server side... you have to parse through the record set to get the image name as you've described how the process works so what is the extra difficulty in doing this via inserting the image name directly into an element OR even doing it with the javascript function method I've posted.  

You keep saying some things that make little to no sense.. client side scripts can not access a recordset passed from jsp unless it's entered into the plaintext that enters the browser.. which is what you're doing now.. aka: no more text passing would occur than does now.

Unless I've totally misunderstood your process in which case a better explination would be greatly appreciated.

"And from my point of view are the script lines on the page evaluated and executed in the order of their occurance on the page. Just for that problem is the body onLoad event handler to ensure that ALL page elements and external files, like images, applets annd other external stuff has completed loading before executing the onLoad handler."  -This makes absolutely no sense... o.o;  just for that problem is the body onload event handler... executing the onload handler?  You used the same event twice?

ZvonkoSystems architectCommented:
I stated this: the body onLoad event handler is fired AFTER the complete html page is loaded.

And ofcourse is the script line in an event handler not executed at page rendering but at event occurance.
But all script lines embedded on the page, header, body, footer, are executed as they occure.
jeremypettitAuthor Commented:
Okay, I'll explain in more detail, because this has gone far away from what I needed as does many of the topics on this site. I've already solved this, but here we go.

Here is what I have:
1.     SQL Server 2000 Database
2.     IIS 6.0 Web Server with ASP.NET 1.1
3.     ASP.NET Web Application
4.     ASP.NET Web Services

ASP.NET Web Application will display a datagrid of information to a user.
The datagrid will display an image in one of the fields.
ASP.NET Web Application requests its data via ASP.NET Web Service.
ASP.NET Web Service gets all of the data from SQL Server 2000.
Images in the datagrid are already determined in SQL through the use of a function.
Once the Web Service retrieves the data from SQL, it relays it to the Web Application.
The Web Application binds to the dataset.

That was how the process worked before this was needed, and did not want to make edits throughout the entire code set. Wanted to do this the easiest and most simplistic way. This would be to change the function in SQL to instead of sending back a relative URL for the image, it would send a javascript string for a function.

Now, we have URL rewriting in effect, so different users can appear to be at different sites/locations. But this is all virtual.
With the rewriting in effect, relative image paths no longer point to the same image location.
Example: will now try to pull from or from

I can eliminate the need to edit the Web Service, Web Application's code behind, and SQL Function and having to recompile and redeploy. By only having to edit the User Defined Function in SQL and add a javascript function to an HTML header file, I achieve my goal with less work.

I haven't mentioned anything about running anything in the onLoad event of the page. I'm not sure what else you did not understand. If you re-read the very first post, you should be able to get back to what my question was.

The looping through each control that I wanted to avoid was this...
               for(i = 0; i < imgs.length; i++){
                    imgs[i].src = prefixPath +"/"+(imgs[i].id);

In order to do that, I would need to give each image a unique ID and properly identify them through javascript. To give a unique identifier, I use the ID from the database. Or I could use the count property of the dataset, and this would all have to be done through code and not in SQL. Unless you would propose to use cursors on the server and bring it to its knees.

A browser will always process the first part of the page first. Javascript will only execute one command at a time, so no matter what you do, nothing is going to load at the same time. But quite frankly, I don't care. All I wanted to do was set the SRC property of an image by calling on a javascript function from the property of the image. I've figured out how to do this already and posted the solution above at 12:49PM CDT.
ZvonkoSystems architectCommented:
Fine that your problem is solved.
Andrew BeersTechnology LeadCommented:
Since his real question was both answered by myself and Zvonko it should be a split.  I disagree with a Refund due to the fact he changed the criteria of his question partially through the discussion.  My oppinion is split / PAQ  with No Refund.

jeremypettitAuthor Commented:
     I found my solution after 2 posts from yourself and one from Zvonko. Zvonko's post regarding the server root was not a workable solution for the web app would not always be at the server root.
     Your second post didn't show anything and said what I was doing already may possibly work. But another look at your first post, a closer look, I saw you were using getElementsByTagName, where I originally thought you were trying to tell me to create a loop using some integer value and construct the Name of the images and set them that way.
     I apologize. I now notice that you were stating to get an array of all images with a specified prefix/tag, and loop through those. So what I could do now is merely change the prefix of my images to reflect the image to display, and through the function set the src property. This can actually shorten the string returned from SQL for that field.
     After finding a way on my own, and misunderstanding your post, I thought the other posts were like rabid dogs fighting over a dead corpse. I was wondering how the hell were we now on subject of the onLoad event.
     Anyway, to show I am sorry about the confusion and my short fuse, I'm bumping up the points and splitting as I feel appropriate.
Andrew BeersTechnology LeadCommented:
*nods*  No disrespect was meant here... and the onload event discussion was merely another way of triggering the loop to circle through the image tags and apply the src.  Using an onload event will trigger the event with 1 javascript call instead of many using the javascript: embedded method.

Just 2 different ways to get to the same end result.  My appologies for any disrespect taken or confusion caused.  I do hope that this helped you solve your problem to some extent though.  Once again my appologies for the confusion in posts and my own failure to fully explain my own code.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.