Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

feralheart's avatar

Changing fields on text input

First Laravel Project. I want to make a form where if I write something in a textbock (for example a barcode) the code searches in a database and prints out a value (for example the price)

My code is so far:

The view:


<script>
function showProduct(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","script/getproduct.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>

//If I don't set the @vars first I get "unknown variable" error
<?php $name=0; $price=0; ?>
<table>
<tr>
<td>{{Form::text('barcode', null, ['onchange'=>'showProduct(this.value)'])}}</td>
<td><div id="txtHint">Name: {{ $name }}</div></td>
<td><div id="txtHint">Price: {{ $price }}</div></td>
</tr>
</table>

The showproduct.php:


<?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);

$price = $sql[0]->price;
$name = $sql[0]->name;
?>

But when I put a barcode to the textfield I still got 0 in the fields. What I did wrong?

0 likes
3 replies
somnathsah's avatar

In showProduct method you are using script/getproduct.php?q=", here the file name you mentioned is getproduct.php but you mention file name as showproduct.php. check if filename matches with url filename.

We should not keep the two element with the same id, So change below code to something like this

<td><div id="txtHintName">Name: {{ $name }}</div></td>
<td><div id="txtHintPrice">Price: {{ $price }}</div></td>

Add an alert to check if you getting the desired result in this.responseText And if you are getting the result in this.responseText then update the two id separately.

Also you need to return $name and $price from showproduct.php file.

Snapey's avatar

I guess you are using some tutorial from 10 years ago if you are building in support for IE5 and 6

Also, why bother with the Laravel framework if you just write plain php query?

You won't be able to use the DB: facade without passing through the Laravel framework.

By the way, one issue will be because you don't echo anything from your php script.

The next issue will be that you have two areas of your page called txtHint

The next issue might be that you cannot cast your barcode to an integer

Please or to participate in this conversation.