0

i'm facing an issue:

(Uncaught) : (in promise) Error: FormatException: SyntaxError: Unexpected token < in JSON at position 0

Below is my code

inscription.dart

InsertMethod() async {
    Uri theUrl =  Uri.parse("http://localhost/fonction_php_appli/inscription.php");
   //try {
    final response = await http.post(theUrl,
      headers: {
        "Accept": "application/json",
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "*", // Va de pair avec le code php pour autoriser la connexion des fichiers
        "Access-Control-Allow-Methods": "POST, OPTIONS",
        "Access-Control-Allow-Headers": "*", 
      },
      body: jsonEncode({
      "prenom":_controllerPrenom.text, // Sans l'extension .text les valeurs ne peuvent être convertit en Json
       "nom":_controllerNom.text,       // elle ne sont pas considéré comme des 'String'
       "identifiant":_controllerIdentifiant.text,
       "email":_controllerEmail.text,
       "mdp":_controllerEmail.text, 
    })); 
     final content = jsonDecode(response.body); // on récupère les données renvoyés par le script php au format json 
    if (content.data[1].success == true) {
      Navigator.push(
                context,
                MaterialPageRoute(builder: (context) =>  Connexion()),
              );
    }
    else () {
       Navigator.push(
                context,
                MaterialPageRoute(builder: (context) =>  FicheFrais()),
              );
    };
 /* } catch (e) {
    print(e);
  } */
    
    
  }

inscription.php

<?php
header('content-type: application/json; charset=utf-8');
 // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // We have to check if the origin in $_SERVER['HTTP_ORIGIN'] is an allowed origin.
        // If it is the case, we add the relevant header with lines bellow.
        //if($_SERVER['HTTP_ORIGIN'])=="https://www.gsb.best"
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // We have here to list all http method allowed for ajax calls.
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }


    include "connexion.php";

    $name = filter_var($_POST['nom'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
    $idd = filter_var($_POST['identifiant'], FILTER_SANITIZE_STRING);
    $prénom = filter_var($_POST['prenom'], FILTER_SANITIZE_STRING);
    $pass = filter_var($_POST['mdp'], FILTER_SANITIZE_STRING);

    try {
       if(isset($name, $email, $pass, $idd, $prénom)){
           $req = $db->prepare("SELECT * FROM authentification WHERE identifiant=?");
           $req->bindValue('identifiant', $idd);
           $req->execute(array($idd));
           $exist = $req->rowCount();
           if($exist == 0){ // Si le nombre de lignes dans la bdd trouvé par le fruit de la requête $req est égal à 0
            // autrement dit, si l'identifiant que l'utilisateur souhaite utiliser n'est pas déjà pris
            // le but de cette fonction est de déterminer si un mail, mdp ou nom est déja existant dans la bdd
               $req = $db->prepare("INSERT INTO authentification VALUES(null,?,?,?,?,?)");
                $req->execute(array($idd, $pass, $name, $prénom, $email));
                if($req){
                    $succes = true; // variable censée etre booleen signifiant succes =1 et succes = 0 en fonction de l'opération
                    $msg = "inscription réussit";
                }else{
                    $succes = false;
                    $msg = "erreur d'inscription";
                }
           }else{
               $msg = "ce mail est déjà existant";
               $succes = false;
           }
       }else{
          $succes = false;
          $msg = "veuillez remplir tous les champs"; 
       }
    } catch (\Throwable $th) {
       $succes = 0;
       $msg = "Error: ".$th->getMesage();
    }
    echo json_encode([ // convertie des données au format json
        "data"=>[
            'msgCome' => $msg,
            'success' => $succes
        ]
    ]);


?>
Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • 3
    Print the string that you think is JSON and you'll likely find it's HTML. Once you see the content of that, you'll probably see how to solve it. – Richard Heap Apr 13 '22 at 19:20
  • Your PHP page is returning HTML, probably due to an error. Check your Network tab to see the response to find out what's going on. At first glance, `getMesage` should be `getMessage`, but that would only cause an error if it hits it. Also, I'm not sure non-ascii characters `é` are acceptable in variable names. – aynber Apr 13 '22 at 19:31
  • 1
    Can you show us a print of response.body before the jsonDecode ? – ethicnology Apr 13 '22 at 19:33

0 Answers0