amur567
amur567

Reputation: 67

Display svg on HTML with jQuery request

I'm trying to get this avatar from an API to appear on my HTML when I click the button but it does not work.


$(document).ready(function () {

    $("#generate").click(function(){
        var c= $("#c").val().split(",");

        $.ajax({
            method: 'GET',
            url: "https://avatars.dicebear.com/api/male/example.svg",
            dataType: "svg"
        })
            .done(function(result){
                $('#result').html('<img src="data:image/png;base64,' + result + '" />');
            })

            .fail(function(error){
                console.log(error);
            });
    })


 });

Upvotes: 1

Views: 1693

Answers (2)

Patzelpuff
Patzelpuff

Reputation: 1

To do it with AJAX you could do this:

  $("#generate").click(function(){
      $.ajax({
          method: 'GET',
          url: "https://avatars.dicebear.com/api/male/example.svg",
          dataType: "html"
      })

      .done(function(result){
          $('#result').html(result);
      })

      .fail(function(error){
          console.log(error);
      });
  })

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337570

svg is not a valid dataType for an AJAX request. Also, you cannot set the content of an SVG file as the base64 encoded content of an img element.

To do what you require needs no AJAX at all. Just set the src of the img element to the URL of the svg file:

<img src="https://avatars.dicebear.com/api/male/example.svg" />

Upvotes: 1

Related Questions