Re: Scan from a web page into a form *on that page* (AJAX, etc)?

4,802 views
Skip to first unread message

Sean Owen

unread,
Jun 17, 2012, 6:18:29 PM6/17/12
to zx...@googlegroups.com
You can't do this, since there has to be a barcode scan from an external app in between. Asynchronous page updates are meaningless here.

ryanmc

unread,
Jun 18, 2012, 5:23:12 PM6/18/12
to zx...@googlegroups.com
I am doing something very similar with my website www.foodstoragemanagement.com/mobile (works on Android). When a user clicks the scan button I store their info in the session, it opens the barcode app. After the scan is complete it returns to my website, pulls the barcode out of the url, and the user info from the session, and reloads the page.

On Sunday, June 17, 2012 3:45:21 PM UTC-6, dfaulkner wrote:
OK, I've read the wiki on Scanning from a web page:

Say I have a  form on my page that has several inputs. One of these has a button next to it labeled "Scan."

I want to push the scan button, trigger the barcode scanner app, and have the {CODE} value inserted into the associated form field. I suspect that this is an AJAX-like maneuver, and I don't claim to be an expert on such things, but I'm a fairly quick study.

I've built some test code that seems to get close, but I feel like I'm missing something. Has anyone done something similar?

In case anyone's curious, here's some snippets of what I've built so far. I'm willing to share the final solution if there is one.

From index.php
<html>
<form>
   <input id="code" type="text" value="
<?php if($_SESSION['scan_code']) print $_SESSION['scan_code']?>">
   
<button class="btn" id="scan1">Scan1</button>
...
</form>

<script type="text/javascript">
$('document').ready(function() {
    $('#scan1').click(function() {
        event.preventDefault();
        // trigger the scanner
        window.open('http://<?php print $_SERVER["SERVER_NAME"]?>/~donf/vstest/scan.php?s=<?php print $session?>&c=%7BCODE%7D');
        session = getCookie("PHPSESSID");
        // same url, but no c={CODE}. Invoke Ajax request to get the value.
        url = "scan.php?s=".concat(session);
        $.get(url, function(result) {
        $('#code').val(result);
    });
});
</script>

... and from scan.php
<?php
session_start();
$mysession = session_id();
if($_REQUEST["s"] != $mysession ) {
    echo "failed: " . $_REQUEST["s"];
    exit;
} else {
    if($_REQUEST["c"]) {
        $_SESSION["scanned_code"] = $_REQUEST["c"];
    } else {
        echo $_SESSION["scanned_code"];
        exit;
}
?>
<html>
<body onload="window.close();"></body>
</html>


Sutikshan Dubey

unread,
Jun 19, 2012, 12:21:47 AM6/19/12
to zx...@googlegroups.com
As Sean mentioned, it is not possible to do it with AJAX, as ZXing is an external app. 
We are doing it, by passing return-url and ZXing successfully opens the web-page with scanned code. In Latest version of Android ( > 2.3) it is not opening the new browser window,  but on iPhone (tested in iOS < 4) it keeps opening new browser window, but I guess, this is due to O.S. behavior and browser-settings. (new iOS Browser windows were not a show-stopper for us,as after reaching max count, it closes the oldest window, and still opens the desired page.).

Sean Owen

unread,
Jun 21, 2012, 4:02:02 AM6/21/12
to zx...@googlegroups.com
Sure, I don't know whether it's what the OP was looking for or not. You are still leaving the page in between and so mechanisms for asynchronous on-page updates don't make sense.

Why are you parsing body.innerHTML? the result comes back in a URL parameter.

dfaulkner

unread,
Jun 21, 2012, 11:46:20 AM6/21/12
to zx...@googlegroups.com
I can't seem to get this one to work. I get a new window popup, and I get my barcode value in that window, but I'm not having a lot of luck reading that value back into the original page. Tried in dolphin and stock browser. I'll have another go later.

On Wednesday, June 20, 2012 6:25:25 PM UTC-5, alfadog wrote:
Hi guys, how 'bout this? It works in Dolphin.

var w;
function getScan(){
    w=window.open("zxing://scan/?ret="+escape("http://yourdomain/barcode.php?ret={CODE}"));
    w.onload=getScanResult;
}
function getScanResult(){
    var barcode=w.document.body.innerHTML;
    //Windows Apache PHP adds a CR on the end, so we have to get rid of it
    barcode=barcode.substr(0,barcode.length-1);
    w.close();
    //Now the variable "barcode" has the scan results, and you can put them anywhere you like.

}

dfaulkner

unread,
Jun 21, 2012, 11:48:15 AM6/21/12
to zx...@googlegroups.com
Sean, I don't mind the second page, as long as there's a way to get the barcode value back into the original page without reloading it. Your original suggestion of saving the form values into the session to maintain them does work, and it's what I'll use if I can't get this working. I'm not sure how much it matters, honestly.

alfadog

unread,
Jun 21, 2012, 11:52:14 AM6/21/12
to zx...@googlegroups.com
I believe the OP wanted this:

"I want to push the scan button, trigger the barcode scanner app, and have the {CODE} value inserted into the associated form field."

That's precisely what this code does.
BTW, Ajax is asynchronous only if you tell it to be. I can't remember the last time I used Ajax asynchronously, anyway. Having said that, the setup above is asynchronous, isn't it?

Regarding the body.innerHTML, you are correct - I could parse the returned code from w.document.URL if I chose to do so. It may even be more efficient.

I posted this yesterday, but it apparently didn't make it past review, probably because I went stupid with my tab key. Here it is again:

barcode.php:
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
ini_set('display_errors', 0);
$query = urldecode($_GET["ret"]);
?>
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function sendScanResult(){}
</SCRIPT>
</HEAD>
<BODY><?php echo $query ?></BODY>
</HTML>

Regards,
Dan

alfadog

unread,
Jun 21, 2012, 12:16:29 PM6/21/12
to zx...@googlegroups.com
I can think of a reason that it matters - as I scan things on my page, I use Javascript to rearrange the page based on what I've scanned, ie. make things visible, look up items from my database based on my scan, etc. and I wouldn't want to do all of that rearranging each time I scan, so this method seems to meet my needs. It kind of makes the [AMAZING AND FANTASTIC] barcode scanner act like a keyboard wedge.

alfadog

unread,
Jun 21, 2012, 3:15:19 PM6/21/12
to zx...@googlegroups.com
Ok sorry to keep working this, but I've stumbled across a solution that might work for everyone. This version doesn't require a separate page to return the barcode. This one should even straight from a file without the need for a server.

It works in Dolphin, too.

<!DOCTYPE html>

<HTML>
<HEAD>
<SCRIPT type="text/javascript" >

function getScan(){
    var href=window.location.href;
    var ptr=href.lastIndexOf("#");
    if(ptr>0){
        href=href.substr(0,ptr);
    }
    window.location.href="zxing://scan/?ret="+escape(href+"#{CODE}");
}
var changingHash=false;
function getHash(){
    if(!changingHash){
        changingHash=true;
        var hash=window.location.hash.substr(1);
        document.getElementById('barcode').value=unescape(hash);
        window.location.hash="";  
        changingHash=false;
    }else{
        //Do something with barcode here
    }
}
</SCRIPT>
</HEAD>
<BODY style="margin:0px;font-family:tahoma" onhashchange="getHash()">
<INPUT id=barcode type=text >
<INPUT style="width:100px;height:100px" type=button value="Scan" onclick="getScan();">
<BODY>
</HTML>

Sean Owen

unread,
Jun 21, 2012, 5:34:05 PM6/21/12
to zx...@googlegroups.com
The only thing I can imagine indeed is for the called-back page is to write a variable into the session, server-side, then close itself, then tell the original page to request to the server for that value. It's definitely harder than just rendering the current state in the called-back page.

Sean Owen

unread,
Jun 21, 2012, 5:43:28 PM6/21/12
to
The flow is...

A page invokes the barcode scanner -- using a hyperlink or JS or whatever
An entirely separate app comes to the front and scans
The app opens URL http://yourdomain/barcode.php?ret=23423464622 -- presumably in a new window

At that point, barcode.php can get '23423464622' from the URL. 

It looks like you mean that the server side read the param, render the value back in the body of a response, then parse that body in Javascript -- I think that works but isn't that the long way around?

Your second example looks, at first glance, more like what I'd imagine.

But it's still not updating the original page in place, right? I think that was the requirement.

alfadog

unread,
Jun 21, 2012, 5:45:50 PM6/21/12
to zx...@googlegroups.com
Sean, you're right - it was the long way around. I hadn't experimented with it enough yet to find a better solution.

The second example will work better, since it creates zero network traffic and won't reload the page.

Regards,
Dan


On Thursday, June 21, 2012 2:39:55 PM UTC-7, Sean Owen wrote:
The flow is...

A page invokes the barcode scanner -- using a hyperlink or JS or whatever
An entirely separate app comes to the front and scans
The app opens URL http://yourdomain/barcode.php?ret=23423464622 -- presumably in a new window

At that point, barcode.php can get '23423464622' from the URL. 

It looks like you mean that the server side read the param, render the value back in the body of a response, then parse that body in Javascript -- I think that works but isn't that the long way around?

Your second example looks, at first glance, more like what I'd imagine.

But it's still not updating the original page in place, right? I think that was the requirement.


On Thursday, June 21, 2012 4:52:14 PM UTC+1, alfadog wrote:

alfadog

unread,
Jun 21, 2012, 6:03:48 PM6/21/12
to zx...@googlegroups.com
Sean, to answer your question, yes it is updating the original page in-place, as per the requirement.

Sean Owen

unread,
Jun 21, 2012, 7:01:58 PM6/21/12
to zx...@googlegroups.com
How though -- the app is going to open a new window. At least, it always does on Android.

alfadog

unread,
Jun 21, 2012, 7:40:09 PM6/21/12
to zx...@googlegroups.com
Sean, if you are referring to the attached (Same as previous post), not true. It's only the hash that's changing, and it's being told to open in the current window.
Also, by www standard, the current window will not refresh if only the hash changes.
However, a changing hash is detectable by current browsers via the onhashchange event in the BODY element.
So here's our flow:
1) wait for a call to getScan()
2) change the hash of the current page to {CODE}
3) Detect a hash change
4) place the hash on whatever form element we like (Or in a java variable)
5) turn off hash change detection (since clearing it will cause a change detection).
6) clear the hash (In case we want to scan the same barcode again)
7) turn on hash detection

Attached(same as my previous post) is a complete working page. I have only opened it from my server, but a direct file open should work as well.
Please open it with your android and tell me if you like it ;-) I need the positive reinforcement.
The function getScan can be tweaked to accept a parameter, which can in-turn tell getHash which field to populate, or even execute a new function.
The name of your html page is inconsequential. The code will reload regardless of what filename you give it.

It all seems to be standards-compliant as well, so it's a process that we will be able to use indefinitely

I used it to put away my entire UPS delivery today.

By the way, thank you for the wonderful [AMAZING AND FANTASTIC] barcode software!

good luck!
Dan
Barcode.html

Martin M

unread,
Aug 17, 2012, 6:10:15 PM8/17/12
to zx...@googlegroups.com, don.fa...@gmail.com
I used a cookie rather than the session to store the scanned code. See my post in this thread (just posted, might not be approved yet):

https://groups.google.com/forum/?fromgroups#!searchin/zxing/field/zxing/Iyld6ffAWQk/iU2wpGRgbREJ[1-25]

Martin M

unread,
Sep 6, 2012, 11:26:12 AM9/6/12
to zx...@googlegroups.com
Hi Scott,

I tested this with Firefox 14 in Windows XP, IE, and the built-in browser in Android.

-Martin

alfadog

unread,
Sep 6, 2012, 11:47:29 AM9/6/12
to zx...@googlegroups.com
Hi Scott,
This works on my Android 2.3.4 with Dolphin HD or the stock browser.
It did occur to me that the example page does appear to reload every time, but it really isn't. If you tweak the code a bit to add the scan result to a DIV or something like that, you'll see that it's not refreshing, but the hash is changing.

Regards,
Dan

On Wednesday, September 5, 2012 10:25:40 AM UTC-7, samilliken wrote:
Which browser are you using?  I'm trying to replicate what you have, but every time that I scan a barcode, both Dolphin Browser and Chrome are reloading the page, rather than simply jumping to the hash tag.

Thanks,
Scott Milliken

alfadog

unread,
Sep 18, 2012, 4:19:30 PM9/18/12
to zx...@googlegroups.com
That's strange, perhaps  a mismatch in either settings or android version. I have 2.3.4, and the code works to specification on the stock browser and on Dolphin HD. I've adapted the page to allow me to put inventory away - I scan the receipt tag, and the page shows some information, then I scan the location code - more information on the same page, then I hit "confirm" and it adds the combination of the 2 previous scans to the database. It's worked flawlessly for months.

    I have also loaded a web server onto my droid and served the page locally, and it works fine there, as well.

    The problem I have is this: If the hash changes, the page, by international standards, should not reload. No browser I have ever used has, anyway. Imagine if every time you clicked a hyperlink that lead to an anchor further down the page, the entire page reloaded. That would be counter-intuitive. You'll notice that, when you click a link that has an anchor hash in it, the anchor hash is not even sent to the server. The page is loaded, and when it's complete, only then will the hash be searched for within the page.

Regards,
Dan

PCPete

unread,
Sep 19, 2012, 10:17:28 AM9/19/12
to zx...@googlegroups.com
Interestingly enough, I thought chrome was the problem so I opened my web-app up in the default browser and this time it appeared to have kept the page open,and refreshed with the hash+code instead of opening a new tab. However, this celebration was short lived as what really happened was that it opened a new chrome window which tricked me for a second into thinking it was the same window. So I'm back to square one. I uninstalled chrome just to verify and indeed a second tab opens even in the default browser. I'll try dolphin just for grins but Im not thinking it will make a difference. Probably something changed in 4.0.4 to cause the inconsistent behavior between you and I.

Martin M

unread,
Sep 19, 2012, 11:58:16 AM9/19/12
to zx...@googlegroups.com
That could be the problem. I've been testing on an Android 4.04 phone.

On Tuesday, September 18, 2012 3:19:30 PM UTC-5, alfadog wrote:
That's strange, perhaps  a mismatch in either settings or android version. I have 2.3.4, and the code works to specification on the stock browser and on Dolphin HD....

alfadog

unread,
Nov 5, 2012, 10:33:25 AM11/5/12
to zx...@googlegroups.com
Hi Martin and all,

I've just had an epiphany:
I got a new 2.3.4 device that I'm using exclusively for barcode scanning. I installed ZXING (thank you) and Dolphin, and started scanning. Every time I'd scan, it's open a new window using the default browser, even though I'd set Dolphin as my default. So, what I did was this:
Menu
Settings
Applications
App Associations
Web URLs
Then chose Dolphin.
Now it's working as intended.

I hope this helps - good luck!
Dan

alfadog

unread,
Apr 5, 2013, 7:05:11 PM4/5/13
to zx...@googlegroups.com
Hi Judah, I had the same problem when some of my devices automatically upgraded, as did some users above, but the I figured out (I think) what everyone's problem is.

When the hash changes, rather than running code on the current page, it's opening the default browser and trying to put the hash there, where, of course, there is no javascript to collect the data.

So try changing your default browser like this:

Install Dolphin if you haven't already.

From Android home screen, Go to  settings, Application Manager, All, Internet (Or the name of your browser, if you installed one), Force Stop, Clear Data, Clear Cache, Clear Defaults.

Open the page in Dolphin, and scan a barcode.

When you see "Complete Action using", choose "Dolphin Browser", and "Always".

That made all of my 4.2 devices work.

Good luck!
Dan

P.S. I recommend the paid version, as Sean has done some AMAZING things with speed and accuracy.

On Friday, April 5, 2013 11:55:56 AM UTC-7, Judah Holstein wrote:
This seems to be a version/os based problem. I had an older version Android tablet and your code worked flawlessly! I upgraded to a new tablet and phone (4.1.1 and 4.1.2) and now it opens in a new tab. Very frustrating!

Judah Holstein

unread,
Apr 5, 2013, 8:27:44 PM4/5/13
to zx...@googlegroups.com
Hi Dan,
 It really is a behavior in the Android/Chrome browser that causes it to open in a new tab instead of in the existing tab. But it would be great if there were a way to tag a target for the destination, as has been described elsewhere...  That would presumably provide consistent results regardless of browser...

 Still, if I have to set it up Dolphin as the default browser, it's not ideal, but it's not the end of the world.

John Brunsden

unread,
Nov 18, 2013, 6:32:18 AM11/18/13
to zx...@googlegroups.com, don.fa...@gmail.com
Hi,

I was wondering whether I could get some advice on the best way of integration the scanning from web page into the code, and what changes if any needed to made for iPhone integration.

Currently we have written some php and html to display the results of an access database, which uses asset labels we would like to scan directly into the input field and go and run the query.

search.php
<?php
 
if(isset($_POST['submit'])){
 
if(preg_match("/^\d+$/", $_POST['asset'])){
  $asset
=$_POST['asset'];
//Connect to sql server..
  $db
=mysql_connect  ("") or die ('I cant connect to the db :( - ' . mysql_error());
//Select db
  $mydb
=mysql_select_db("booking_inout");
//Query table
  $sql
="SELECT `Asset No`, `Serial No`, `New Location` FROM `StockRoom` WHERE `Asset No`=" . $asset;
//Run the query
  $result
=mysql_query($sql);
//Create loop and loop through result
 
while($row=mysql_fetch_array($result)){
          $AssetNo
=$row['Asset No'];
          $SN
=$row['Serial No'];
          $NewLocation
=$row['New Location'];
//Display result
  echo
"<h3>Item Found -</h3><p>";
  echo  
"Asset Number: " . $AssetNo . "<p>";
  echo  
"Serial Number: " . $SN . "<p>";
  echo  
"Location (If booked out): " . $NewLocation . "<p>";
 
}
 
}
 
else{
  echo  
"<p>Please enter a asset number to search..</p>";
 
}
 
}
?>

warehouse.html
<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
 
<head>
   
<meta  http-equiv="Content-Type" content="text/html;  charset=iso-8859-1">
   
<title>Warehouse Asset Search [POC]</title>
 
</head>
 
<p><body>
   
<h3>Warehouse Search [POC]</h3>
   
<p>Search using the items asset number..</p>
   
<form  method="post" action="warehouse\search.php"  id="Search">
     
<input  type="text" name="asset">
     
<input  type="submit" name="submit" value="Search">
   
</form>
 
</body>
</html>
</p>


Any advice or example of the best way of integrating the scanning functionality into our current search?

Many Thanks

John

joel PEYRON

unread,
Jan 28, 2015, 5:36:47 AM1/28/15
to zx...@googlegroups.com, jhol...@gmail.com
Le vendredi 5 avril 2013 20:55:56 UTC+2, Judah Holstein a écrit :
> This seems to be a version/os based problem. I had an older version Android tablet and your code worked flawlessly! I upgraded to a new tablet and phone (4.1.1 and 4.1.2) and now it opens in a new tab. Very frustrating!
>
>
> On Monday, November 5, 2012 10:33:26 AM UTC-5, alfadog wrote:Hi Martin and all,
2 things first of all thank you for your great idea and second sorry for my bad english. I tested your code on 2 devices : Android kitkat 4.4.4 and the browser opens a new rab. The second device is Android 5.0.1 and it works perfectly. So if Google could fix the issue in Android 4.4 it would be great !

Ankit Ramani

unread,
Jan 29, 2015, 10:55:03 AM1/29/15
to zx...@googlegroups.com, don.fa...@gmail.com
Hello,

I am trying a demo with above code. In the demo, when barcode application scan the code, it opens an URL (contained inside QR code, eg. www.youtube.com). But it isn't working as intended. So, In short I want to get the URL from the barcode.

Is anybody tell me that how to get the URL/data from QR code and load the URL (load youtube website into browser)?

Ankit Ramani

unread,
Feb 10, 2015, 11:42:49 AM2/10/15
to zx...@googlegroups.com
Hi Dan,

I am trying a demo with above code. In the demo, when barcode application scan the code, it opens an URL (contained inside QR code, eg. www.youtube.com). But it isn't working as intended. So, In short I want to get the URL from the barcode.

Is there anyway to get the just only CODE and open it inside the browser?

w=window.open("zxing://scan/?ret="+escape("{CODE}"));

alfadog

unread,
Feb 10, 2015, 12:26:34 PM2/10/15
to zx...@googlegroups.com
Hi Everyone,

I've had tens-of-thousands of successful executions with this small code snippet in Android 2.2 thru 4.3. It won't work in Firefox, but it works well in he default browser and in Chrome. It stopped working in Dolphin some months ago. I haven't tried it in Lollipop yet. If this doesn't work, you might try adding preventDefault() and stopPropagation() to the function, or try using window.addEventListener("hashchange", [...], false).


window.onhashchange=function(){
var hash = window.location.hash.substr(1);
if (hash != "") {
window.location.hash = "";
processBarcode(unescape(hash));
}
}
function processBarcode(code){
//do what you need here.
}

Kind Regards,
Dan

alfadog

unread,
Feb 10, 2015, 12:32:50 PM2/10/15
to zx...@googlegroups.com
Hi again,
Here's the code I use to initiate the scanner:

function getScan(){
var href = window.location.href;
var ptr = href.lastIndexOf("#");
if (ptr > 0) {
href = href.substr(0, ptr);
}
window.location.href = "zxing://scan/?ret=" + escape(href + "#{CODE}");
}

Dan

alfadog

unread,
Apr 29, 2015, 11:22:03 AM4/29/15
to zx...@googlegroups.com
I've written a synapses and a short script that will work with Chrome, Firefox, and the Android Browser. You can see that here:

http://stackoverflow.com/a/29931389/1182988

Good luck, everyone, and Happy Scanning!

Thanks again, Sean, for your awesome creation.
Reply all
Reply to author
Forward
0 new messages