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 ´

Lleims
  • 1,275
  • 12
  • 39

2 Answers2

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'));
      }
    });
  });
});
muecas
  • 4,265
  • 1
  • 8
  • 18
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.

Vladimir M
  • 4,403
  • 1
  • 19
  • 24