0

I use ajaxForm to upload image. On success upload I add uploaded image to div on the page:

$("#ajaxUploadForm").ajaxForm({
            iframe: true,
            dataType: "json",
...
success: function (result) {
$("#imageList").prepend('<img src=' + result.message + '/>');

Now I was thinking that it is not smart to put this hardcoded <img/> tag in javascript code.
What is the best way to put image but not use img tag in prepend() function?

0

3 Answers 3

2

i would not have any problem with that... unless you are worried about invalid url that could break the tag...

you could use simple javascript

var img = new Image();
    img.src = result.message;

$("#imageList").prepend(img);
Sign up to request clarification or add additional context in comments.

Comments

1

IMHO that is the best way, there's no need to change anything. If you don't want to dynamically append/detach, you could have an existing img as a placeholder and just change its src attribute when you wanted to change it:

<img id="placeholder" src="initial/path" />

$("#placeholder").attr("src", result.message);

But since you're dealing with an image list, as your code suggested, I think your original solution is more appropriate for your case. If you ever decide to remove an image or sort the list or whatever, you can selected them using $("imageList img").

Edit: OTOH if you have a very complex structure, that you want to code in HTML but also need to make dynamic copies of it, you can use clone as an alternative:

<div id="model" style="display:none">complex markup goes here</div>

$("#model").clone().attr("id",anotherID).appendTo(target).show();

1 Comment

If you clone, you need to change the ids.
1

Use a template. For instance:

<div style="display:none">
  <!-- This div contains all your templates -->
  <img src="about:blank" class="classesYouNeed" id="uploadSuccess">
</div>

and then use javascript:

$("#ajaxUploadForm").ajaxForm({
  iframe: true,
  dataType: "json",
  ...
  success: function (result) {
    var img = $('#uploadSuccess')
      .clone()
      .attr('id', somethingElse)
      .attr('src', result.message)

    $("#imageList").prepend(img);
  })
})

There are jQuery templating frameworks out there that will make this much easier.

Comments

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.