Saturday, April 1, 2017

JSON onchange syntax error

First Laravel Project.

I have a page where I put a barcode it WILL prints out the name from the database, but I got syntax error.

The view:

@extends('layouts.master')
@section('title', 'Onchange test')
@section('main')
@parent
<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) {
                var jsonObject = JSON.parse(this.responseText);                document.getElementById("nameHint").innerHTML = jsonObject['name'];
}
        };
        xmlhttp.open("GET","/getproduct/q="+str,true);
        xmlhttp.send();
    }
}
</script>

<table>
<tr>
<td></td>
<td>
<td><div id="nameHint">Test</div></td>
</tr>
</table>
@endsection

The controller:

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

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

$test = $name;
echo json_encode(array("test"=> $test));

Console output:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 17 of the JSON data

What did I wrong?



via Feralheart

Advertisement