Unexpected token < in JSON at position 0

Hi everybody , I hope everything is Ok
I have a probleme sendind and updating data to sql satabase , I use I ionic3 and php and http post method , when I send data I get the error

ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at Response.Body.json (http.js:1091)
at MapSubscriber.project (sos.ts:90)
at MapSubscriber._next (map.js:79)
at MapSubscriber.Subscriber.next (Subscriber.js:93)
at XMLHttpRequest.onLoad (http.js:1591)
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (core.js:4751)
at t.invokeTask (polyfills.js:3)
at r.runTask (polyfills.js:3)

my codes are like that :

the provider code

sendData(DATE,lat,LNG,ETATALERT_ID,idUser){

this.url  = "http://192.168.1.182/SOSMobile/GestionAlertes.php?action=envoyerAlerte";

let param = {DATE:DATE,lat:lat,LNG:LNG,ETATALERT_ID:ETATALERT_ID,idUser:idUser}

let type: string = “application/x-www-form-urlencoded; charset=UTF-8”,
headers: any = new Headers({‘Content-Type’: type}),
options: any = new RequestOptions({headers: headers});

return this.http.post(this.url, param,options).map(res => res.json());

}

home.ts

sendData(){

let date = new Date();

this.time =this.datepipe.transform(date, 'yyyy-MM-dd HH:mm');
console.log(this.time.toLocaleString());

//this.sosProvider.LancerAlerte('',this.time,this.latitude,this.longitude,1,'',localStorage.getItem('id'))


console.log(this.longitude);

console.log(this.latitude);

  this.sosProvider.sendData(this.time.toLocaleString(),this.latitude,this.longitude,1,localStorage.getItem('idUser'))
    .subscribe((data) => {
      // If the request was successful notify the user
      this.ResultatAlerte =data
      if (this.ResultatAlerte.CreationKO != null) {

        this.presentToast("Echec d'envoi d'Alerte") ;

        // this.presentToast("Login ou Mot de Passe Non Correct , Merci de résseyer");

      }

      else {
        console.log('here is the error')
        this.AlerteID=this.ResultatAlerte.CreationOK
        console.log( this.AlerteID) ;
        this.getListUrgences();
        this.etape2=true;


      }


    });

}

php file

rest_json = file_get_contents("php://input"); _POST= json_decode($rest_json, true);

$COMMENTAIRE=$_POST["COMMENTAIRE"] ;	
$DATE=$_POST["DATE"] ;
$lat=$_POST["lat"] ;
$LNG=$_POST["LNG"] ;
$ETATALERT_ID=$_POST["ETATALERT_ID"] ;
$URGENCE_ID=$_POST["URGENCE_ID"] ;
$idUser=$_POST["idUser"] ;		
$gravite_alerte=$_POST["gravite_alerte"] ;	
$AutreAlerte=$_POST["AutreAlerte"] ;	
    $PiecesJointes=$_POST["PiecesJointes"] ;

	
//	$stmt = $db->prepare("INSERT INTO alerte (COMMENTAIRE, DATE, LAT, LNG, ETATALERT_ID, URGENCE_ID, UTILISATEUR_ID) 
	//VALUES(:COMMENTAIRE, :DATE, :lat,:LNG,:ETATALERT_ID,:URGENCE_ID,:idUser)");
	
	
	$stmt = $db->prepare("INSERT INTO alerte (COMMENTAIRE, DATE, LAT, LNG, ETATALERT_ID, URGENCE_ID, UTILISATEUR_ID,gravite_alerte,AutreAlerte,PiecesJointes) 
	VALUES(:COMMENTAIRE, :DATE, :lat,:LNG,:ETATALERT_ID,:URGENCE_ID,:idUser,:gravite_alerte,:AutreAlerte,:PiecesJointes)");

 $stmt->bindParam(':COMMENTAIRE', $COMMENTAIRE);
 $stmt->bindParam(':DATE', $DATE);
 $stmt->bindParam(':lat', $lat);
 $stmt->bindParam(':LNG', $LNG);
 $stmt->bindParam(':ETATALERT_ID', $ETATALERT_ID);
 $stmt->bindParam(':URGENCE_ID', $URGENCE_ID);
     $stmt->bindParam(':idUser', $idUser);
 $stmt->bindParam(':gravite_alerte', $gravite_alerte);
     $stmt->bindParam(':AutreAlerte', $AutreAlerte);
     $stmt->bindParam(':PiecesJointes', $PiecesJointes); 
 
 
 
 $status= $stmt->execute();
 
 $id="";
 if( $status===true)
 {
	
$stmt1 = $db->prepare("SELECT MAX(ID) as AlerteID FROM alerte");	
$row= $stmt1->execute();
$row=$stmt1->fetchAll();

 echo '{"CreationOK": ' . json_encode($row[0]["AlerteID"]) . '}';

 }

else{
	
	 echo '{"CreationKO": ' . json_encode("Erreur d'envoi d'Alerte") . '}';

	
}	

when I change map(res => res.json()); to map(res => res); the error disapear but data aren’t sent to the database , so data are not updated
when I use http get method it ok , everything is working .

can you please help it’s urgent

Hi @kadi60 :wave:

By the looks of the error, it seems that the server is returning HTML instead of JSON, so the parser (JSON.parse()) is complaining about the first character <, usually in <!doctype html> or <html> .

Can you check what is the API actually returning from the Network tab in the dev tools?

Best,
Rodrigo

I am out of office , but I think it renders html

Hi
After viewing response in network , this is what i got :slight_smile:


( ! ) Notice: Undefined index: COMMENTAIRE in C:\wamp64\www\SOSMobile\GestionAlertes.php on line 20
Call Stack
# Time Memory Function Location
1 0.0005 284752 {main}( ) ...\GestionAlertes.php:0

( ! ) Notice: Undefined index: URGENCE_ID in C:\wamp64\www\SOSMobile\GestionAlertes.php on line 25
Call Stack
# Time Memory Function Location
1 0.0005 284752 {main}( ) ...\GestionAlertes.php:0

( ! ) Notice: Undefined index: gravite_alerte in C:\wamp64\www\SOSMobile\GestionAlertes.php on line 27
Call Stack
# Time Memory Function Location
1 0.0005 284752 {main}( ) ...\GestionAlertes.php:0

( ! ) Notice: Undefined index: AutreAlerte in C:\wamp64\www\SOSMobile\GestionAlertes.php on line 28
Call Stack
# Time Memory Function Location
1 0.0005 284752 {main}( ) ...\GestionAlertes.php:0

( ! ) Notice: Undefined index: PiecesJointes in C:\wamp64\www\SOSMobile\GestionAlertes.php on line 29
Call Stack
# Time Memory Function Location
1 0.0005 284752 {main}( ) ...\GestionAlertes.php:0
{"CreationOK": "569"}

it returns html instead of json , can you please help how to resolve it , itis urgent

cdt

So if your API is returning HTML and you want HTML and not JSON, you shouldn’t map your observable with .map(res => res.json()), because it will fail. Just remove this part and you will get HTML as a string in the response.

Best,
Rodrigo

Hi
I solved the problem , thank you , it was an additional post field not needed for the http post , when I comment it it workd .

I’m glad you found the problem. Cheers!

1 Like

I’am glad too , thank you so much