0

I have written code to generate QR codes n times, (qr text generated on server and placed into html input) however there is some problem when appending the result recursively in a div. Here is the code (jQuery):

$(document).ready(function() {
    $(document).on("click", "#qr_id_create", function() {
        $(this).attr("disabled", true);
        var url = "server/qr_id_create.php?create_qr_id";
        var n = $("#n_qr_codes").val();
        jQuery('#qrcode_top div').html('');

        for (var i=0; i < n; i++) {
            $.ajax({
                type: "GET",
                url: url,
                success: function(data) {
                    $("#qr_id_result").val(data);

                    var value = $("input[name='qr_input']").val();
                    //this is the problem area
                    $("<div />", {id:"code"+i}).appendTo("#qrcode_top");
                    jQuery('#code'+i).qrcode({text:value});
                }
            });             
        }
        $("#qr_id_create").attr("disabled", false);

    });

And html:

<button id="qr_id_create" class="button">Create QR Code</button>
<div id="qrcode_top"></div> 
<input id="qr_id_result" type="text" name="qr_input" required>
<input id="n_qr_codes" type="text" name="" required>

I am trying to append each qr code generated by jquery within the html div #qrcode_top, and each qr code inside its own div with a unique id. The idea is to later on create a pdf with all the generated qr codes for printing.

The result of this code is all the qr codes appended within the same div with the last generated id. For example, if 5 qr codes are to be generated, all the qr codes (canvas) are appended in <div id="code5">

I am sure the solution is simple. I have tried various versions of the appending code, but maybe overlooked something. Your input would be appreciated.

Roelof Coertze
  • 586
  • 3
  • 15
  • Could your add your html? it looks like you need a promise / callback-function – admcfajn Apr 21 '20 at 22:11
  • Replace `var` with `let` in your `for` loop initial state. Using `var` makes the variable global to all iterations, whereas `let` "locks" it for each iteration. This is one of the reason why the use of `var` is considered bad practice now. – Seblor Apr 21 '20 at 22:25
  • 1
    @Seblor Thank you so much, that did the trick! Could you make an answer so that I can accept it? – Roelof Coertze Apr 21 '20 at 22:28
  • @roelofco I am glad I could help. I would prefer people reading the question I linked, and get your question flagged as duplicate of it to avoid duplicating the answers and to keep StackOverflow clean. – Seblor Apr 21 '20 at 22:30
  • @Seblor No problem, understood!! – Roelof Coertze Apr 21 '20 at 22:31

0 Answers0