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.