Unexpected token < in JSON at position 0 at JSON.parse(<Anonymous>)

Asked

Viewed 968 times

0

I am trying to get the data searched in a given text field of the main page to be displayed without the refresh of the page, through AJAX.

window.onload = function(){
    document.getElementById("boxsearch").onkeydown = function(e){
        if(e.keyCode == 13){
            var query = this.value==""?"*":this.value;
            enviar(query);
        }
    };

    document.getElementById("btnsearch").onclick = function(){
        var query, tb = document.getElementById("boxsearch");
        query = tb.value==""?"*":tb.value;
        enviar(query);
    };

    function enviar(query){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState===4&&xmlhttp.status===200){
                var json = JSON.parse(xmlhttp.responseText);
                alert(json[0].titulo);
                var resultados = "";
                for(var i=0; i<json.length; i++){
                    resultados+="<li><h3>"+json[i].titulo+"</h3><p>"+json[i].publicacao+"</p></li>";
                    document.getElementById("result").innerHTML = resultados;
                    document.getElementById("resultnumber").innerHTML = json.length;
                }
            }
        };
        xmlhttp.open("GET","dal.php?val="+query,true);
        xmlhttp.send();
    }
}
  • It has how to put in the answer the trafficked json?

  • Hey Marco, what appears if you put console.log(typeof json, json); on the line where alert(json[0].titulo);?

  • Hello Sergio. I did what you requested... Uncaught Syntaxerror: Unexpected token < in JSON at position 0 at JSON.parse (<Anonymous>) at Xmlhttprequest.xmlhttp.onreadystatechange (script.js:19) xmlhttp.onreadystatechange @script.js:19

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.