Rich-text Reply

Image swap from third party-domain using jQuery.ajax

philippedenis 05-18-16

Image swap from third party-domain using jQuery.ajax

I am trying to run a variation that modifies the src attribute of all images on a product category page, and for various reasons have to do it using jQuery.ajax. However, when I do so, I get the following error: 

 

No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

I guess this has to do with the fact that the page is at mymaindomain.com, but that images are hosted on a third party domain.

 

Is there anyway I can still make this work? 

 

Variation code below: 

 

	$(".product-image img").not('.abReplaced').each(function(){
		var that = $(this);
		var imgsrc=that.attr('src');
		var imgLarge = imgSrc.replace('medium','large');
		var imgThird = imgLarge.replace('0.jpg','2.jpg');
		jQuery.ajax({
   			url: imgThird,
   			success: function(){
     			that.attr('src',imgThird);
     			that.addClass('abReplaced');
     		},
     		error: function(){
     			that.addClass('abReplaced');
     		}
     	});
	});

JDahlinANF 05-19-16
 

Re: Image swap from third party-domain using jQuery.ajax

You should totally be able to load an image that happens to exist on a different domain. However, it sounds like you are not actually changing an image, you are changing a URL which executes server side code which responds with something that happens to be an image and you are needing to place that response into your page. (This is not an uncommon way for image hosting sites to prevent users from direct-linking images and this stealing their bandwidth)

This stack overflow topic has a few good answers for Cross Origin Scripting (CORS) which may help you find a solution to the setup you are dealing with.
http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-...