0

before starting with the code I try to explain what I would like to achieve:

I have an input where the user will write a code (bar code) with a barcode reader with keyboard emulation so he will write something like: 123465789.

  1. I would like to take all these numBers
  2. Truncate them because I only need first 4 chars: 1234.
  3. Pass this value to the db that will check which item corresponds to this number
  4. Add to 'stock' number of the item.
  5. Clean the form
  6. Repeat as fast as possible.

Ok, now that I tried to explain let's start with the funny part, my code:

file 1: change.php

<!DOCTYPE html>
<html>
<head>
  <style>
fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
  width: 100%;
}
.print-output-line {
  white-space: pre;
  padding: 5px;
  font-family: monaco, monospace;
  font-size: .7em;
}

</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <form>
  <fieldset>
    <label for="troncami">Type Something:</label>
    <input id="troncami" type="text" />
  </fieldset>
</form>
<div id="risultatotroncato"></div>
<script>
$('#troncami').keyup(function(event) {              


            var str = $(this).serialize();                   
               $.ajax({            
               type: "GET", // the kind of data we are sending
               url: "troncare.php", // this is the file that processes the form data
               data: str, // this is our serialized data from the form
               success: function(msg){  // anything in this function runs when the data has been successfully processed

                    // this sets up our notification area for error / success messages
                    $("#risultatotroncato").ajaxComplete(function(event, request, settings)
                    { 
                        result = msg; // msg is defined in sendmail.php
                        $(this).html(result); // display the messages in the #note DIV                           
                    }); 
                $('input[name=troncami]').val(msg);
                }                    
             });                     



}).keydown(function(event) {
  if (event.which == 13) {
    event.preventDefault();
  }  
});

$('#other').click(function() {
  $('#target').keyup();
});</script>

</body>
</html>

File 2: troncare.php

<?php
$risultatotroncato = 0;

$risultatotroncato = substr ($_GET['troncami'],0,4);

echo $risultatotroncato;
?>

Obviusly it doesn't work the only thing I can see is a NOTICE error:

Notice: Undefined index: troncami in D:\Locali\xampp\htdocs\combobox\troncare.php on line 6

So my question is how can I pass the value written in the input to $_GET / $_POST so I'll be able to 'manage' it with 'troncare.php' ? How can I do it as fast as possible so the user will be able to 'shot' with the barcode scanner without stopping and have the value saved on the DB in, almost, 'real time' ? Thank you very much!

(As you probably already know I'm still studying PHP and AJAX and jQuery so in a couple of years/months I'll be able to do it my by self but... I need it ASAP so, could you please help me?)

maisdesign
  • 51
  • 7

1 Answers1

1

To answer your main questrion, just add your GET parameters to the end of the URL that you are calling in the ajax call. Something along the lines of:

$.ajax({             
    type: "GET", // the kind of data we are sending 
    url: "troncare.php?troncami=" + $('#troncami').val(), // this is the file that processes the form data 
    success: function(msg){  // anything in this function runs when the data has been successfully processed 
        // this sets up our notification area for error / success messages 
        $("#risultatotroncato").ajaxComplete(function(event, request, settings) {  
            result = msg; // msg is defined in sendmail.php 
            $(this).html(result); // display the messages in the #note DIV                            
        });  
        $('#troncami').val(msg); 
    }                     
});

Or you can use the data setting of the $.ajax call to pass in key/value pairs:

$.ajax({             
    type: "GET", // the kind of data we are sending 
    url: "troncare.php", // this is the file that processes the form data 
    data: {"troncami" : $('#troncami').val()}, // this is our serialized data from the form 
    success: function(msg){  // anything in this function runs when the data has been successfully processed 
        // this sets up our notification area for error / success messages 
        $("#risultatotroncato").ajaxComplete(function(event, request, settings) {  
            result = msg; // msg is defined in sendmail.php 
            $(this).html(result); // display the messages in the #note DIV                            
        });  
        $('#troncami').val(msg); 
    }                     
});

Notice that I used '#troncami' instead of 'input[name=troncami]' as the selector for the input. While it might seem trivial, on a large scale it is much more efficient to use the ID of an element as a selector than to use a filter style selector. An ID should be unique in a page so the object is found quickly in the DOM. If you use a filter style selector (like 'input[name=troncami]') the object has to first be found. You should also consider investigating using callback parameters on Ajax/JSon calls as these can help with avoiding cross site scripting (XSS).

On another note I hope that you will do some data validation and cleansing on the receiving end of the ajax call. As your code is now it is wide open to injection attacks. At the very least in your case I would use something like this in troncare.php to validate the input value before querying or inserting into the database:

<?php
$risultatotroncato = 0;

if (isset($_GET['troncami']) && ctype_digit($_GET['troncami'])) {
    $risultatotroncato = substr ($_GET['troncami'],0,4);
    //echo or search the database here
}
else {
    //do whatever here if the value is blank or contains invalid characters
}
?>

That ensures that the value received can only be numbers (1234567890).

UPDATE: If I undertsand your situation correctly in this instance the value that should be received by troncare.php should always be only numbers if it is valid so the PHP function ctype_digit() will be enough to cleanse the data and will only return true if the value contains only numbers. That is enough of a cleanse in this situation. If you were allowing letters or numbers there are several other ctype functions that can help. If the data is of a non standard type you can use a preg_match which uses pattern matching. In all other situations there is normally a PHP function that matches your database type for cleansing data. Like for example if you are using MySQL there is a PHP function called mysqli_real_escape_string(), and mysql_real_escape_string() which cleanses data before using it in any way with the database. I won't re-invent the wheel in this department but there are many good questions on SO (and elsewhere on the web) that deal with this topic for example: here

Community
  • 1
  • 1
Zappa
  • 453
  • 1
  • 5
  • 14
  • Thank you very much for your response, the first one works, but not the second one, anyway do you know also how can I clean the input after php is executed? – maisdesign Sep 21 '12 at 12:41