0

I want to load an (base64) png image for magnific popup when the user clicks a preview icon. Every preview icon displays an other image, which gets loaded via ajax, based on some parameters.

How can i manually call MP when the request is finished? Every time ajax finishes it says the image was not found. Or simply doesnt show the image (black transparent screen)

My code looks like this:

HTML and JS:

function loadPopupImage(element, p1, p2, p3, p4, p5) {
  if (element.href == "") {
    var request = $.ajax({
      method: "POST",
      dataType: "xml",
      timeout: 5000,
      data: {
        P1: p1,
        P2: p2,
        p3: p3,
        P4: p4,
        P5: p5
      },
      url: "<%=URL%>"
    });
    request.done(function(response) {
        element.href = "data:image/png;base64," + response.documentElement.textContent;
        $.magnificPopup.open({
          items: {
            src: element
          },
          type: 'inline'
        });
      }
    }
  }
<a class="magnific-popup" onclick="loadPopupImage(this,'<%=p1%>','<%=p2%>','<%=p3%>','<%=p4%>','<%=p5%>')">
  <img width="20" src="/images/70x70px.png">
</a>

If i remove the $.magnificPopup.open part. It obviously doesnt show a popup, but i can click the preview again an can see the image in the browser tab.

Liam
  • 27,717
  • 28
  • 128
  • 190
J000S
  • 197
  • 1
  • 5
  • 19
  • you can just add the image source to the image once you want to load it. So it will be loaded asynchronous – Noel Schenk Mar 06 '18 at 13:22
  • thank you... but i don't really understand, what you mean. could you explain it a litte more? – J000S Mar 06 '18 at 13:43
  • if you just want to load an image asynchronously use this: `$(".theImageToLoad").attr("src", $(".theImageToLoad").data("src"));` and inside HTML use `` – Noel Schenk Mar 06 '18 at 13:48
  • to check if an image has loaded read more here: https://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript – Noel Schenk Mar 06 '18 at 13:50
  • I dont want to change the img tag. the image just displays my preview (which is the same for all elements). I want magnific to display the content in the href attribute (the base64 png from ajax response) – J000S Mar 06 '18 at 13:58
  • Then just create a new img element and add the src attribute. – Noel Schenk Mar 06 '18 at 14:01

1 Answers1

1

I found a solution. Actually pretty easy...

request.done(function(response){
    element.href = "data:image/png;base64,"+response.documentElement.textContent;
    $.magnificPopup.open({
        items: {
            src: element.href,
        }
    });
});

I had to add the .href to the element. Now it works like a charm.

I could also add the data string directly to the src, but i want to keep the data string in the element. This way magnific can open the image once the user clicks the link and there is no need to execute the ajax request again.

J000S
  • 197
  • 1
  • 5
  • 19