Over a million developers have joined DZone.

Fetch An Image From A Different Domain Using Javascript And JQuery

·
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; }; };
Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}