Json Unexpected end of JSON input

Hi all,
i have this two files:

function addToCart(id){
    var xhr = new XMLHttpRequest();
    xhr.open("POST","addToCart.php");
    
    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");
                    
                }else{
                    alert("dati inviati ma non memorizzati");
                }
                
            }
        }
    }
     //invio dati
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var product_id="product_id="+id;
    xhr.send("product_id");
}

and a php file:

<?php
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  
			$resp->set_response(1);
			//$resp->response=1;
			echo json_encode($resp);
		}
		else{//inserimento nel database non possibile avvisa l utente
			$response->set_response(0);
			//$resp->response=0;
			echo json_encode($resp);
		}
	}else{
		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;
    xhr.send("product_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.