4

I'm learning to use AJAX, and I want to insert an image after click a button.

But the image doesn't appear, instead appears lots of characters.

How can I do it correct?

$(document).ready(function() {

  $('#botonAjax').click(function() {
    type: "GET",
    $.ajax({
      url: "Img/inlaw.png",
      success: function(result) {
        $('#divAjax1').append(result);
      }
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="divAjax1">
  <h2>TEST AJAX</h2>
</div>

<button id="botonAjax">Cargar contenido externo</button>

Thank you very much ´

4
  • 2
    Just add an image element when loaded: $('#divAjax1').append($('<img />').attr('src', 'Img/inlaw.png'));. Commented May 13, 2018 at 18:23
  • Upvote for your thought as i never tried this. Commented May 13, 2018 at 18:38
  • @muecas Hi, if you write your answer down, I can mark it like the solution. Thank you Commented May 13, 2018 at 18:50
  • Ok, if it was a good option for you. Glad i could help. Commented May 13, 2018 at 18:58

2 Answers 2

3

I don’t think this is the best option or solution, but when loading an image thru ajax will mean that when the request is completed, the image will be on the browsers cache so, you only need to append an image with the same source as the one from the ajax call:

$(document).ready(function() {
   $('#botonAjax').click(function() {
    $.ajax({
      url: "Img/inlaw.png",
      success: function(result) {
        $('#divAjax1').append($('<img />').attr('src', 'Img/inlaw.png'));
      }
    });
  });
});
Sign up to request clarification or add additional context in comments.

Comments

2

Well... you have to understand, what exactly are you loading and how is it going to be integrated into your html.

Ajax request returns you contents of the image file, and you put it directly into the div. Yes - you see the contents of the image file, not the image itself.

To see the image you have 2 options:

1) don't use ajax. just have an 'img' element in your code and change the src property of it on button click. For more information check here so question

2) similarly, have the img element, but set the source in the form of CDATA. For reference on data uri check MDN

I hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.