"But the image isn't replaced correctly" Perhaps try changing this line instead
$('#' + id + ' img').attr("src", "images/"+msg+".png"); There's no reason why that (or your line for that matter) wouldn't work as long as the selector finds something and the value of the "src" is a valid path on your server