I have a barcode scanner which reads the string of the barcode and displays in the active text box. also there is no consistent end character to the barcode, or standard length (I have 5 diffent length sizes. 16,17,18,19,20). I need to extract values from scanned data. so extracting values also depend on the barcode length.
So how would I go about firing a method when the WHOLE string has been read in?
Im using php and ajax to do this.
$(document).ready(function()
{
$("#bcode").focus();
//prevents autocomplete in some browsers
$("#bcode").attr('autocomplete', 'off').keyup(function(event)
{
var name = $("#bcode").val();
$("#status").empty();
if(name.length > 17 ) `// need to check all possible length values like this`
{
selectAll();
$("#status").html('<img align="absmiddle" src="images/loading.gif" /> Checking availability...').show();
$.ajax({
type: "POST",
url: "namecheck.php",
data : "bcode=" + name,
success: function(msg)
{
$("#status").html(msg).show();
}
});
}
else
{
$("#status").html('').addClass('err').show();
}
});
});
I did some work with a card swiper, there are similar challenges there. The data comes in a rapid burst, but there isn't a consistent "end-of-data" string being sent. The solution is to use setTimeout and wait - when the input stops, then you fire your processing code.
Depending on your hardware, the amount of waiting you'll want to do varies. Experiment with this code, to adjust the wait time, simply adjust the duration argument of setTimeout. I've started it on 500ms - that works pretty well for the card swipers. Forgive me if there are any minor wobbles in my code here - I am not a jQuery guy :)
$(document).ready(function() {
$("#bcode")
.focus()
.attr('autocomplete', 'off')
.keyup(function(event){
// if the timer is set, clear it
if (barcode_watch_timer !== false)
clearTimeout(barcode_watch_timer);
// set the timer to wait 500ms for more input
barcode_watch_timer = setTimeout(function () {
process_barcode_input();
}, 500);
// optionally show a status message
//$("#status").html('waiting for more input...').show();
// return false so the form doesn't submit if the char is equal to "enter"
return false;
});
});
var barcode_watch_timer = false;
function process_barcode_input() {
// if the timer is set, clear it
if (barcode_watch_timer !== false)
clearTimeout(barcode_watch_timer);
// grab the value, lock and empty the field
var name = $("#bcode").val();
$("#bcode").attr('disabled', true);
// empty the status message
$("#status").empty();
// add a loading message
$("#status").html('<img align="absmiddle" src="images/loading.gif" /> Checking availability...').show();
// send the ajax request
$.ajax({
type: "POST",
url: "namecheck.php",
data : "bcode=" + name,
success: function(msg) {
// unlock the field, show a success status
$("#bcode").attr('disabled', false);
$("#status").html(msg).show();
}
});
}
Does it need to be a text area?
The last barcode reader I used always ended with a newline. If you are inputing into a <input type="text"/> the return char will likely try to submit the form, and you can use an onSubmit to capture the event and process your input.
Try observe the field with code by interval
Example
setInterval(function() {
var value = $("#code").val(),
prev_value = $("#code").attr("prev_value");
if (prev_value == value) {// compare with prevent value for detecting canges
console.log("value is not changed");
return;
}
//if (value.length < 17) {
//exeption
// or reset value $("#code").val(prev_value);
//return;
//}
if (value[value.length-1] == "\n") {// check last symbol
console.log(value);// Do something with you code eg send by AJAX
}
$("#code").attr("prev_value", value); // save current value for compare later
}, 1000 );
Related
I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});
Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds
I have a page with some checkboxes and a submit button. I use AJAX to post the checkbox values to a PHP script, calc.php, run some calculations with the data and assign the result to a PHP session variable. I have another PHP script, json.php, that takes that session data and encodes it as JSON for the jquery to display in the div. My problem is I allow the user to set the amount of data sets they are going to submit, subnumber, and my display loop gets out of sync when the user changes the number of sets.
For example, if they start with 3 data sets, they submit them one by one by pressing #button. After the last set, if (count == max) runs and. Now they can do another calculation and change the number of data sets if they wish. If they change it to say 2, output goes to four instead of reseting to 1 and emptying #log.
$("#button").click(function() {
$.ajax({
type: "POST",
url: "calc.php",
data: $("form#checkboxes").serialize(),
success: function(data) {
if(document.getElementById('calc').checked) {
var max = checkboxes.subnumber.value;
var stop = Number(max) + 1;
count++;
output++;
$.getJSON('json.php', function(data) {
$.each(data, function(key, val) {
$('#log').append(output);
$('#log').append(val.result);
$('#log').append("</br>");
})
})
if (count == max){
count = 0;
$("#results").load('results.php')
}
if(output == stop) {
$("#log").empty();
output = 1;
}
}
}
})
}
I know it's something simple, but I have been trying to fix it for two hours now and can't figure out the problem. Everything else works perfectly, it's just the output counter that isn't done correctly.
You're running asynchronous calls into your JSON. If users are doing things so quickly that the calls are coming back out of order, the issue lies in there.
You've got two options:
Run all of your JSON synchronously (use async:false in your JSON calls)
Utilize a counter and only process events that are coming back on the current index.
Psuedo Code for #2:
var pCounter = 0;
function doSomeAjax()
{
pCounter++;
$.ajax('url',{
data:{count:pCounter}
success:function(data)
{
// your json should return the current counter index
if (data.counter != pCounter) return;
// execute normally.
}
});
}
I am using JQUERY .ajax() to send serialized form data to MySQL using PHP. The backend PHP being called will return a message if there was an issue processing the data. My Javascript function then checks for a message being returned before deciding what to do next. If the message length is '0', then the post was successful and it can carry on. If the message length > '0', then an error must have occured in the form processing, and it traps there to deal with it. However, when testing, I found that a successful processing of my form data, returned a message of size 13, even though the message itself was blank.
The javascript function I used is below. I have modified it to test for a message length of more than 13 characters, and this is working fine now. I' am just curious as to why a blank response is 13 characters in length. Ignore the complicated .load() statements, they just return the user to a different page depending on whether an error message was detected or not.
$("button#update").click(function() {
var cat = $("select#cat_select").val();
var dataString = $("form#project_update").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: 'text',
success: function( msg ) {
console.log('msg is ' + msg);
length = msg.length;
console.log('length is ' + length);
if (length > 13) { // no idea why a blank msg has a length of 13!!
alert(msg);
$("#main").load('?app=$app&func=$func&sub=ajax&ajaxSub=edit_project&cat=' + cat + '&proj_id=' + $proj_id).fadeIn('fast');
}
else {
$("#main").load('?app=$app&func=$func&sub=ajax&ajaxSub=project_detail&cat=' + cat + '&proj_id=' + $proj_id).fadeIn('fast');
}
}
});
return false;
});
Instead of
length = msg.length;
try with
length = msg.replace(/\s/g,'').length
Note
But you should make sure that there are no spaces or newlines within <?php and ?> tags, I would be better if you remove them.
Check for hard-coded spaces outside your <?php and ?> tags. I suppose the script calls itself via ajax, right?
How would I fill in the boxes of my form if I select one of the values from the dropdown menu (The dropdown is got from the DB) Somehow in my javascript I need to connect to functions as there is to different tables involved with the form fields.
Question
Do I need to set the fields using $field name?
if(document.id('LoadExtension') && document.id('ExtensionResponse')) { // id of select box
var sel = document.id('LoadExtension'); // ser select box as var.
sel.addEvent('change', function(chg) { // add change event to select box.
if(sel.getSelected().get('value') != '') { // on change if selected value is not empty.
new Request.HTML({
url : 'http://domain.co.nz/index.php?extension='+ sel.getSelected().get('value'),
onRequest: function() {
},
onComplete: function(r1, r2, html, js) {
document.id('ExtensionResponse').set('html', html);
}
}).send();
}
});
}
The above code was set up to get from another document in the url: box but I would like to do it in one page.
for your code:
http://www.jsfiddle.net/dimitar/TXHYg/4/
(function() {
// anon closure for scope purposes of local vars.
// cache selectors used repeatedly into local vars.
var sel = document.id('LoadExtension'), resp = document.id('ExtensionResponse');
// if they are in the dom...
if (sel && resp) {
// ... then attach event listener.
sel.addEvent('change', function(event) {
// this == sel.
var value = this.get("value"); // cache getter.
if (value === '') {
return false; // do nothing if not selected/
}
// otherwise, it will run the request
new Request.HTML({
method: "get", // or post.
data: {
extension: value // etc etc, can add more object properties and values
},
url: 'http://domain.co.nz/index.php',
onComplete: function(r1, r2, html, js) {
resp.set('html', html);
}
}).send();
});
} // end if
})(); // end closure.
you should really look at some tutorials and examples and the documentation for Request and Request.HTML/JSON/JSONP
an example, similar to yours that works for jsfiddle through its echo testing service (slightly different data object that simulates the response)
http://www.jsfiddle.net/dimitar/TXHYg/3/
instead of document.id('ExtensionResponse') you can write $('ExtensionResponse')
an if you only update a content of a element you can use the update parameter from Request.HTML.
new Request.HTML({
url : 'http://domain.co.nz/index.php',
data: 'extension='+ sel.getSelected().get('value'),
update: $('ExtensionResponse')
}).send();
#medrod;
That's right about the $(), but using the latest version of mootools + making sure Jess stays library safe, document.id() is a much safer option for compatibility.
you need to build the rest of your form, and populate it, with in the result of the ajax request.
eg: http://domain.co.nz/index.php?extension=
start your first HTML form with only the drop down, then your ajax'd script will build and populate the rest of the form.