2

I am trying to call a function saveBadge() and getting the value of the function to use in the for loop.But every time I am getting the value from an array where I am converting the div tag to Image. but every time I am getting the last value. How do I handle the Asynchronous call?.

    for(var j=0;j<anarray.length;j++)
    {
        var json=JSON.parse(anarray[j]);
        // adding in badge image
        alert(anarray[j]);

        var imgTem=json['regId']['image'];
        var imgFin=imgTem.replace("dataimage","data:image").replace("base64",";base64,");              


        $("#name").text(json['regId']['fname']+" "+json['regId']['lname']);  // User name
        var imgTem=json['regId']['image'];
        var imgFin=imgTem.replace("dataimage","data:image").replace("base64",";base64,");     
        $("#image").attr("src",imgFin);                                     // User Image
        $("#gender").text(json['regId']['gender']);                         // User Gender

        //QRcode generator
        var qrcode = json['badgeId'];                                       // User QRcode
        var qr = new QRious({
            element: document.getElementById('qrcanvas'),
            value: qrcode,
            background: 'white', // background color
            foreground: 'black', // foreground color
            level: 'L', // Error correction level of the QR code (L, M, Q, H)
            mime: 'image/jpeg', // MIME type used to render the image for the QR code
            size: 120 // Size of the QR code in pixels.
        });         
        //qr.toDataURL("jpeg"); // Generates a base64 encoded data URI for the QR code. 
       savebadge();  
        var bdgImg = localStorage.getItem("bdgImg");

        var qrjson = JSON.parse(anarray[j]);
        qrjson.badgeImg=bdgImg.replace("data:image","dataimage").replace(";base64,","base64");
        anarray[j]=JSON.stringify(qrjson);  
     } // End of for-loop



    toReq();
   });

Function Definition

function savebadge(){

for(var j=0;j<anarray.length;j++)
{
html2canvas($("#bdg"+j+""), {
    onrendered: function(canvas) {
        theCanvas = canvas;
        var base64img = canvas.toDataURL();
        badgeimg=base64img.replace("png","jpeg");
        alert($("#name").text());
        //console.log("render "+badgeimg);
        localStorage.setItem("bdgImg",badgeimg); 

        var img = $("<img>",{
            "src" : badgeimg,
            "alt" : "badgeimg"
        });
        $("#divimg").append(img);


    }       
});
}}
Ramana
  • 31
  • 1
  • 7
  • that code after save badge needs to be called in onrendered. That is what callbacks and promises are for. – epascarello Jan 31 '18 at 13:55
  • I closed it with the two tickets that have tons of options on how you can deal with running code with an asynchronous request. Promises and callbacks are the way to handle situations where code is dependent on asynchronous calls. – epascarello Jan 31 '18 at 13:58

0 Answers0