PHP : Sending data using fetch()

i’m trying to send some data using fetch() but in return i’m getting

SyntaxError: Unexpected token , in JSON at position 23

here’s what i’m doing

fetch('/api.php', {
        method: 'POST',
        body: JSON.stringify({
            nom : "Issa",
            prenom: "Oule"}),
        headers : {"Content-Type" : "application/json"},
    })
.then(res => res.json())

.then((res) => {

    console.log(res);
})
.catch((err) =>{

    console.log(err);
})
        

in my php file :

    <?php
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

    $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

    if($contentType === "application/json") {
  
    $content = trim(file_get_contents("php://input"));
    $decoded = json_decode($content, true);

    if(! is_array($decoded)) {
        echo '{"status":"error decoding"}';
  
    } else {
      
        echo '{"status":"ok", "Nom": '. $decoded['nom'];.', "Prenom": '.$decoded['prenom'].'}';
    }
}else{

    echo '{"status":"error data"}';
}

?>

someone can help me please

thanks in advance

67 thoughts on “PHP : Sending data using fetch()”

  1. 867841 876548Someone essentially lend a hand to make critically articles Id state. That could be the first time I frequented your web site page and so far? I amazed with the research you made to create this actual post extraordinary. Great activity! 522571

    Reply

Leave a Comment