DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Fetch An Image From A Different Domain Using Javascript And JQuery

  • submit to reddit
        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)

<script src=""></script>
<script type="text/javascript">// <![CDATA[

 $("form").submit(function() {
  var imageCode=$("input:first").val();
   if (imageCode==null)
     alert('image code is null!');
  var imageUrl='';
$("#success").html("loading...").load(imageUrl, function(response, status, xhr) {
  if (status == "error") {
    var error=document.createElement('div');
    var msg = "Sorry but there was an error: ";
    var xhrStatus=xhr.status;
    var xhrStatusText=xhr.statusText;
    error.innerHTML=msg + xhrStatus + " " + xhrStatusText;
   $("#success").html("<img src=" + imageUrl + " mce_src=" + imageUrl +" />");
   var successDiv=document.createElement('div');
   successDiv.innerHTML="no error! status: " + status + 'xhr status text: ' + xhr.statusText;
return false;
// ]]></script>

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

<p><img src="" /></p>
<form id="imageCodeInput" action="javascript:return false;">
<h1><span style="color: #000099;">Enter Your Unique Code</span></h1>
<p>(This was the code that was emailed to you):</p>
<input id="input" name="resp" type="text" /> <input type="submit" value="Submit" /> </form>
<p> </p>
<p id="success"> </p>

  var imageCode=(theForm.resp.value);
  alert("the image code entered is: " + imageCode);
   if (imageCode=="")
     alert('Nothing entered!  Please insert your image code.');
  var imageUrl="" + imageCode + ".jpg";
  var success=document.getElementById("success").innerHTML="loading...";

// 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);