javascriptqr-code

Distinguishing qrcode URL parameters from those of the API URL


I want to generate a qr code with multiple pre-filled values, but only the first value seems to be encoded into the generated QR code. I guess because it's assuming parameters after the first belong to the API URL..

Can anyone help me here?

.src = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" 
+ "https://google.com/?" + "field1=" + var1 + "&" + "field2=" + var2

I've looked online without luck - perhaps because I don't know how to describe the problem. (note that google.com is jut a placeholder URL, and not the one I'm using)


Solution

  • Since the URL you are trying to pass to data contains /, ? and & you have to encode it. For instance, the browser wouldn't know whether to pass field2 to the main URL or to the data URL. To encode the URL being passed to data:

    const url = "https://google.com/?" + "field1=" + var1 + "&" + "field2=" + var2
    const src = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" + encodeURIComponent(url)
    

    On an unrelated note, consider using template string to make your code more readable:

    const url = `https://google.com/?field1=${var1}&field2=${var2}`
    const src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(url)}`