0

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

2
  • Do not build your json manually. Instead, create an array, then use json_encode to make sure it's in a correct format Commented Jan 31, 2021 at 2:08
  • Most likely you are missing double quotes around nom, prenom in "Nom": '. $decoded['nom'];.', "Prenom": '.$decoded['prenom']. But as mentioned, do this with json_encode() because utf characters need handling as well. Commented Jan 31, 2021 at 2:17

2 Answers 2

1

You have a spurious semi-colon in the JSON string you're creating:

echo '{"status":"ok", "Nom": '. $decoded['nom'];.', "Prenom": '.$decoded['prenom'].'}';
                                               ^ here

But that's not your only error here.

It's better to create an array and use json_encode() to create the JSON:

$jsonData = ["status"=>"ok", "Nom"=>$decoded['nom'], "Prenom"=>$decoded['prenom']];
echo json_encode($jsonData);
Sign up to request clarification or add additional context in comments.

Comments

0

Just Change your echo statement to return json_encode array like this.

echo json_encode([
            "status" => "ok",
            "Nom" => $decoded['nom'],
            "Prenom" => $decoded['prenom']
        ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.