amirhossein
amirhossein

Reputation: 371

how to get image from json and display it

I get the photo address from the backend with json, but how to set it as a src image and show this image?

 $.post(               
       "{%url 'validate_email' %}",
         {
           email: $("#members_email").val()
         },
          function (data, status) {
              console.log("Data: " + JSON.stringify(data) + " " + status);
          }
       );

output in console:

Data: {"user_avatar":"/media/mizbanuser/profile_img/2020-10- 
        27_095908.3275338039170.jpg","status":true} success

Upvotes: 0

Views: 708

Answers (1)

Nathan Chu
Nathan Chu

Reputation: 657

function createIMG (data, status) {
  var img = document.createElement('img')
  img.setAttribute("src", data.user_avatar);
  document.body.appendChild(img)
}

//simulate the input:
createIMG({"user_avatar":"/media/mizbanuser/profile_img/2020-10- 27_095908.3275338039170.jpg","status":true}, 'success')

You can change document.body to document.getElementById('<insert parent element here>') if you want to add it to a specific element. The 2nd line creates the element, the 3rd sets the src, and the fourth puts the element inside body. In the end your code should look like:

 $.post(               
       "{%url 'validate_email' %}",
         {
           email: $("#members_email").val()
         },
          function (data, status) {
              var img = document.createElement('img')
              img.setAttribute("src", data.user_avatar);
              document.body.appendChild(img)
          }
       );

Or if you want to check for success first:

 $.post(               
       "{%url 'validate_email' %}",
         {
           email: $("#members_email").val()
         },
          function (data, status) {
              if (status == 'success') {
                  var img = document.createElement('img')
                  img.setAttribute("src", data.user_avatar);
                  document.body.appendChild(img)
              } else {
                  // handle error
              }
          }
       );

Upvotes: 1

Related Questions