0

I'm trying to replace an image on button click but I don't seem to figure it out. I get an image from my server that looks like this photo/1583testImg.png from my ajax value. I wan't now to replace the current photo with the one that i get from the server through ajax.

 for(file in search){
    var title = search[file].title;
    var photo = search[file].path;
    $(".search-result:first").clone().appendTo(".search").find("h3").text(title);
    $(".search-result:first").clone().appendTo(".search").find("src").replace(photo); // this is the codeline that doesn't work
    console.log(title+"+"+photo);
}
2
  • Why you are cloning it twice? Commented Mar 3, 2017 at 11:28
  • Hm good question, I suppose I could just clone it once Commented Mar 3, 2017 at 11:29

1 Answer 1

2

you should change:

$(".search-result:first").clone().appendTo(".search").find("src").replace(photo);

to:

$(".search-result:first").clone().appendTo(".search").attr("src",photo);

if you need to display full path, you can use some options:

//window.location.host //you'll get sub.domain.com:8080 or sub.domain.com:80
//window.location.hostname ////you'll get sub.domain.com
//window.location.protocol : you'll get http:
//window.location.port //you'll get 8080 or 80
//window.location.pathname //you'll get /virtualPath

var mainUrl =  window.location.protocol+"//"+window.location.hostname;

$(".search-result:first").clone().appendTo(".search").attr("src",mainUrl+"/img/"+photo);

this will give you http://example.com/img/photo/1583testImg.png

Sign up to request clarification or add additional context in comments.

7 Comments

Oh yea this worked, Can I ask one more thing, Since I get the photo from my server, how do I actually display it, since I get back the path from the server where the photo is, as in photo/testImg.png. Surley I can't just add it to the srcs?
do u want display full path? something like http://example.com/img/photo/testImg.png instead photo/testImg.png ?
Hm yea that might work, since I can use the url to view it on my browser. But doesnt seem to work to just add attr("src","http://example.com/img/"+photo);
yes u can, i edited the answer with the solution, edit to your own structure
Ye I tried this with my server (that is up and running, can view the images by the url) I tried to just paste it in the html and it worked, but the appendTo and just append the new picture didnt work (hard coded) as in clone.appendTo(".search").attr("src", "http://www.mindshiftinteractive.com/wp-content/uploads/2016/10/test-big.png"); So I think the replacing codeline doesn't work correctly
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.