Json Unexpected end of JSON input

Hi all,
i have this two files:

function addToCart(id){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange= function(){
        if( this.readyState === 4){
            if( (this.status == 200) && (this.status < 300)){
                var resp = JSON.parse(this.responseText);
                if( resp.response === 1){
                    alert("dati inviati e memorizzati");
                    alert("dati inviati ma non memorizzati");
     //invio dati
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var product_id="product_id="+id;

and a php file:

header("Content-Type: application/json; charset=UTF-8");
class response_obj{
    //response=1 ok $response=0 not ok
    private $response=0;
    public function set_response($value){
         $response = $value;
    public function get_response(){
	    return $response;
function addToCart(){
	$resp = new response_obj();
	if( isset($_POST['product_id'])){
		//inserisci il prodotto nel carrello e invia dati al client
		$db= new PDO('sqlite:/home/and/Documenti/sqlite/ecomm') or die("Could not connect to the database");
		$sql = "Insert into cart (id) values (".$_POST['product_id'].")"; 
		echo $sql."\n";
		if( $db->exec($sql) == true){
			//invia risposta al client  
			echo json_encode($resp);
		else{//inserimento nel database non possibile avvisa l utente
			echo json_encode($resp);
		echo "\$_POST['product_id'] non definito\n";


every time that i execute it in the browser i receive this error:
VM84:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at XMLHttpRequest.xhr.onreadystatechange (jsFunctions.js:11)
what is the problem?I think i make some errors in the php file.

Is it because you’re echoing the contents of the query before you echo the actual output? As your javascript doesn’t skip that part, it’s trying to JSON-decode something that wasn’t encoded in the first place.

Also, in here:

    var product_id="product_id="+id;

doesn’t that mean you’re sending a string literal containing “product_id” as text, rather than sending the contents of the product_id variable that you create on the previous line? That would surely mean that your PHP code isn’t getting a product id, so it’s throwing an error message. The error message also isn’t JSON-encoded, so would cause a problem when you try to decode it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.