Over a million developers have joined DZone.

Fetch An Image From A Different Domain Using Javascript And JQuery

DZone's Guide to

Fetch An Image From A Different Domain Using Javascript And JQuery

Free Resource
This code uses javascript to fetch an image specified by an input code that you might have sent to a user in an email or something.

The first snippet attempts ajax with jQuery's load() function, but jQuery prevents you from doing cross site requests (and thus it won't work).  The second script uses no ajax but still updates the DOM using javascript (recommended)

I recommend this approach, and it may very well be the only functioning example on the page

Enter Your Unique Code

(This was the code that was emailed to you):



{ var imageCode=(theForm.resp.value); alert("the image code entered is: " + imageCode); if (imageCode=="") { alert('Nothing entered! Please insert your image code.'); } else { var imageUrl="https://mysite.com/images/" + imageCode + ".jpg"; var success=document.getElementById("success").innerHTML="loading..."; image=document.createElement('img'); // neato thing about image tags is the onError event handler image.setAttribute('onError',"javascript:alert('Image code not found. Did you type it correctly?');"); image.setAttribute('src', imageUrl); sucess.innerHTML=image; }; };

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}