I want to update an image source to the source of another image on a different page.
I'm creating a squarespace shop for furniture. The furniture has multiple seasonal material options which are selected every 6 months . I want the company im working for to easily update the material collection for all there products with out having to change it for each product individually. So my idea was to first add placeholder images to each product and then have a single page that describes the material. If the image on the material page changes all the place holder images update too.
I would expect this to work but instead i'm getting an error:
stoff2:740 Uncaught SyntaxError: Invalid or unexpected token
This error points to the $('img[alt...
line.
$(document).ready(function() {
var count;
var newSrc;
for (count = 1; count < 5; count++) {
var adress = "http://uk5-shop.com/stoff" + count;
$.get(adress, function(data) {
newSrc = document.getElementById("5cf7ba50095f4e0001e1519c").src;
});
$(‘img[alt = ”stoff” + count]’).src = newSrc;
};
});
Firstly, the error is because ‘
is not a valid character in JS. The same for ”
and ’
. You need to use '
and "
respectively.
However there are several other problems with your logic.
Firstly, you're using document.getElementById()
after the AJAX request to access the response, yet this will only access the current page. To fix this, use the data
argument provided to the function to retrieve the HTML of the response and find the src
attribute you need in there.
Secondly, you need to update the src
within the AJAX callback of $.get()
, not outside it, and also jQuery objects don't have a src
property. You need to use prop()
, or attr()
.
Next, the quotes themselves within the [alt=...]
selector, even when corrected, are mismatched. You're closing the attribute value quotes too early, and are missing the +
to concatenate the end of the string after count
.
Finally, to avoid issues with the count
value not being the value you expect when the AJAX request returns (due to the loop being finished) you need to either use a closure, or simply the let
keyword assuming the browsers you'r targeting support it.
With all that said, try this:
$(document).ready(function() {
for (let count = 1; count < 5; count++) {
var address = "http://uk5-shop.com/stoff" + count;
$.get(address, function(data) {
var newSrc = $(data).find("#5cf7ba50095f4e0001e1519c").prop('src');
$('img[alt="stoff' + count + '"]').prop('src', newSrc);
});
};
});
As an aside, I'd suggest that using AJAX for this is a little wasteful. For every page that's loaded you're causing an additional 5 page requests to your server just to get the location of some images. If possible I'd suggest you re-factor this logic to get those locations server side to avoid this unnecessary load on your server.