Sunday, April 2, 2017

JSON returns undefined

I have this script:

function showProduct(str) {
    if (str == "") {
        //if inputfield is empty the divs will be empty
        document.getElementById("nameHint").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 =  this.responseText;
                document.getElementById("nameHint").innerHTML = jsonObject["name"];
                document.getElementById("priceHint").innerHTML = jsonObject["price"];
}
        };
        xmlhttp.open("GET","/getproduct/q="+str,true);
        xmlhttp.send();
    }
}

Later on the file I have an input field, where if I put a barcode this script runs and WILL return (this is the plan) the name and the price of the product in two divs (nameHint and priceHint).

The divs are empty in the start and if I put a barcide in the input field I got undefined as the result.

If I replace var jsonObject = this.responseText; part of the code with var jsonObject = JSON.parse(this.responseText); and put barcode in the input field the divs remains empty and in console I can see the following output:

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

What am I missing? How to solve it?



via Feralheart

Advertisement