Feralheart
Feralheart

Reputation: 1938

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>
{{ Form::open() }}
{{Form::text('barcode', null, ['onchange'=>"showProduct(this.value)"])}}
<div id="nameHint></div>
<div id="priceHint></div>
{{Form::close}}

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?

Upvotes: 1

Views: 1159

Answers (1)

Freyja
Freyja

Reputation: 40904

You have a JSON string (this.responseText), you want a JavaScript object (jsonObject). You want to use JSON.parse, which turns a JSON string into a JavaScript object, instead of JSON.stringify, which does the reverse, turning a JavaScript object into a JSON string.

var jsonObject =  JSON.parse(this.responseText);
                // ^-- here

Upvotes: 2

Related Questions