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

11.01.2010
| 5341 views |
  • 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)

<p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function(){

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

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

<p><img src="https://mysite.com/images/default.jpg" /></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.');
    }
  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;
  };
};