Saturday, April 1, 2017

JSON: getElementById returns Undefined

I have a text input where I write a barcode it returns the name and the price from the database.

My code looks like this:

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();
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
                var jsonObject =  JSON.stringify(this.responseText);
                document.getElementById("nameHint").innerHTML = jsonObject["name"];
                document.getElementById("priceHint").innerHTML = jsonObject["price"];
}
        };
        xmlhttp.open("GET","/getproduct/q="+str,true);
        xmlhttp.send();
    }
}
</script>


<div id="nameHint></div>
<div id="priceHint></div>


The controller:

public function getProduct($id){
    ini_set('display_errors', 1);error_reporting(E_ALL);

    $sql = DB::select('select * from inventory where barcode = ?', [$id]);
    $name = $sql[0]->name;
    $price= $sql[0]->price;

    echo json_encode(array("name"=>$name, "price"=>$price));
}

When I write the barcode it shows: undefined where it had to show the name and the price. What I missed?



via Feralheart

Advertisement