Currently I am working on a phonegap that uses the Barcode Scanner plugin (v 0.6.0) with phonegap 2.9.0. The actual barcode scanner works fine, I can get the phone to bring up the camera/scanner and read a barcode. I can even get the result.text to show up in a simple alert (as long as I do this in the callback). However, if I try to save the value of results.text into a global variable or hidden field, the value is undefined in the variable, and empty in the field.
my current code
openBarcodeScanner();
var code = document.getElementById('barcode').value;
alert(code);
function openBarcodeScan(viewInfo){
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(function (result){
document.getElementById('barcode').value = result.text;
},
function (error){
alert ( error );
});
}
I might very well be doing something stupid, but for the life of me can't figure it out. I would prefer to use a global variable, but the hidden field was a last ditch effort to pass the result.text outside the call back.
EDIT: I guess this because of the asynchronous callback, but I'm not sure how get result.text outside the function.
.scan()
method is asynchronous (it's usually a sign when a method accepts a callback instead of returning a value that it's asynchronous), so the function you provide to.scan()
will not execute immediately, therefore it won't set the value when you expect it to and won't be available for retrieval by your outside code where you doalert(code);
– Ian.scan()
first callback, write the AJAX request there. You have access toresult
, and then you should be able to access any of these object properties you speak of – Ian